No log files are being created using winston node js library

不羁岁月 提交于 2019-12-12 19:23:08

问题


I am working in node js and using Winston library for logging. The following code does not create a log file.

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("hello world");

It logs to the terminal fine:

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

Directory Structure is like this

-test.js
-winston.js
-log

回答1:


Here's you should use Winston:

Below code creates log files in /log/ directory.


First, install the winston-daily-rotate-file, fs, and winston using:

npm i winston-daily-rotate-file fs winston

Create a file with name 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(),
            )
        }),
    ]
});

Now all you have to do is, import the logger and use it. Below is the example.

Now in the same directory, create a new file test.js and add following code:

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

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

Now run test.js using

node test.js

Hope this is what you are looking for.



来源:https://stackoverflow.com/questions/51545819/no-log-files-are-being-created-using-winston-node-js-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!