问题
I have a project nodejs and use log4js to write log.
I want create new file log when start new date.
Example:
daily.2017_07_31.log
daily.2017_08_01.log
daily.2017_08_02.log
daily.2017_08_03.log
In java, I know config log4j but in nodejs with log4js I don't know.
Thank every body for your help :)
回答1:
winston is recommended for nodejs. Its pretty easy to use.
Create a logger.js file and have this configuration '
require('winston-daily-rotate-file');
var winston = require('winston');
winston.loggers.add('logger', {
transports: [
new (winston.transports.Console)(
{
level: config.debugLogLevel,
colorize: true
}),
//new files will be generated each day, the date patter indicates the frequency of creating a file.
new winston.transports.DailyRotateFile({
name: 'debug-log',
filename: '<log file name>',
level: '<level>',
prepend: true,
datePattern: '<pattern>',
maxFiles: <max file>
}
),
new (winston.transports.DailyRotateFile)({
name: 'error-log',
filename: '<log file name>',
level: '<level>',
prepend: true,
datePattern: '<pattern>',
maxFiles: <max file>
})
]
});
var logger = winston.loggers.get('logger');
Object.defineProperty(exports, "LOG", {value: logger});
now you can use it anywhere like
var log = require('./logger.js').LOG
log.error('hello');
回答2:
Not found for daily rolling, but for size the configuration of log4js allows file rolling. Pay attention to maxLogSize, backups and compress properties. Example from its docs:
log4js.configure({
appenders: {
everything: {
type: 'file',
filename: 'all-the-logs.log',
maxLogSize: 10485760,
backups: 3,
compress: true
}
},
categories: {
default: { appenders: [ 'everything' ], level: 'debug'}
}
});
See https://github.com/log4js-node/log4js-node/blob/master/docs/file.md
回答3:
See: https://github.com/log4js-node/log4js-node/blob/master/docs/dateFile.md
log4js.configure({
appenders: {
everything: { type: 'dateFile', filename: 'all-the-logs.log' }
},
categories: {
default: { appenders: [ 'everything' ], level: 'debug' }
}
});
This example will result in files being rolled every day. The initial file will be all-the-logs.log, with the daily backups being all-the-logs.log.2017-04-30, etc.
来源:https://stackoverflow.com/questions/45479473/log4js-javascript-create-daily-log-file