【问题标题】:No log files are being created using winston node js library没有使用winston node js库创建日志文件
【发布时间】:2019-01-03 20:41:25
【问题描述】:

我正在使用 node js 并使用 Winston 库进行日志记录。以下代码不会创建日志文件。

var winston = require('winston');


var logger = winston.createLogger({
    transports: [
        new winston.transports.File({
            level: 'info',
            filename: './logs/all-logs.log',
            handleExceptions: true,
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.Console({
            level: 'debug',
            handleExceptions: true,
            json: false,
            colorize: true
        })
    ],
    exitOnError: false
});

module.exports = logger;
module.exports.stream = {
    write: function(message, encoding){
        logger.info(message);
    }
};

logger.info("你好世界");

正常登录终端:

 {"message":"hello world","level":"info"}

目录结构是这样的

-test.js
-winston.js
-log

【问题讨论】:

  • 好问题!! +1,为此,请在下面查看我的答案。
  • 我已经对答案进行了一些最终更改,您可以重试答案中的所有步骤吗? MOST IMP 执行所需软件包的 npm 安装。

标签: javascript node.js logging npm winston


【解决方案1】:

你应该使用 Winston:

以下代码在/log/ 目录中创建日志文件。


首先,使用以下命令安装 winston-daily-rotate-file、fs 和 winston

npm i winston-daily-rotate-file fs winston

创建一个名为 winston.js

的文件
const fs = require("fs");
const winston = require("winston");
const logDir = "log";

if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
}

const tsFormat = () => (new Date()).toLocaleTimeString();
module.exports = logger = winston.createLogger({
    transports: [
        new (winston.transports.Console)({
            format: winston.format.combine(
                winston.format.colorize(),
                winston.format.timestamp(),
                winston.format.align(),
                winston.format.simple(),
            ),
            level: 'info'
        }),
        new (require("winston-daily-rotate-file"))({
            filename: `${logDir}/-results.log`,
            format: winston.format.combine(
                winston.format.timestamp(),
                winston.format.json(),
            )
        }),
        new winston.transports.File({ 
            filename: 'log/error.log', 
            level: 'error',
            format: winston.format.combine(
                winston.format.timestamp(),
                winston.format.simple(),
            )
        }),
    ]
});

现在您要做的就是导入记录器并使用它。下面是示例。

现在在同一目录下,创建一个新文件 test.js 并添加以下代码:

const logger = require("./winston.js");

logger.info(`Test info Log!`);
logger.error(`Test error Log!`);

现在使用

运行 test.js
node test.js

希望这是您正在寻找的。​​p>

【讨论】:

  • 有什么问题?
  • 此代码应在项目文件夹中创建/log/ 目录。你能检查你的项目的根目录吗?
  • 现在检查答案。如果创建了日志目录,则说明上面的代码可以正常工作,你只需要正确使用即可。
  • 你能发布你的目录结构吗?在你的问题中
  • 我不确定,你在这里做错了什么,但我刚刚发布的代码。我又试了一次,现在也正常了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
  • 2021-04-26
  • 2018-03-21
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多