zia*_*aab 108
没有日志文件.每个node.js"app"都是一个单独的实体.默认情况下,它会将错误记录到STDERR并输出到STDOUT.当您从shell运行它以记录到文件时,可以更改它.
node my_app.js > my_app_log.log 2> my_app_err.log
Run Code Online (Sandbox Code Playgroud)
或者(推荐),您可以手动或使用众多日志库之一在应用程序内添加日志记录:
如果您在开发中使用 docker,则可以在另一个 shell 中执行此操作:docker attach running_node_app_container_name
这将向您显示 STDOUT 和 STDERR。
小智 5
对于nodejs日志文件,您可以使用winston和morgan并代替console.log()语句用户winston.log()或其他winston方法来记录。要使用 Winston 和 Morgan,您需要使用 npm 安装它们。示例: npm i -S 温斯顿 npm i -S 摩根
然后在项目中创建一个名为 Winston 的文件夹,然后在该文件夹中创建一个 config.js 并复制下面给出的代码。
const appRoot = require('app-root-path');
const winston = require('winston');
// define the custom settings for each transport (file, console)
const options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
],
exitOnError: false, // do not exit on handled exceptions
});
} else {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
}
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write(message) {
logger.info(message);
},
};
module.exports = logger;
Run Code Online (Sandbox Code Playgroud)
复制上述代码后,创建一个名为“logs”的文件夹,与“winston”或任何您想要的位置平行,并在该日志文件夹中创建一个文件“app.log”。返回 config.js 并将第 5 行“filename: ${appRoot}/logs/app.log
,”中的路径设置为您创建的相应 app.log。
之后,转到您的 index.js 并在其中包含以下代码。
const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));
winston.info('You have successfully started working with winston and morgan');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
163639 次 |
最近记录: |