Node.js Winston 日志记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20880540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js Winston logging
提问by Subburaj
In my node app I am using "Winston" Logging to print the errors in a separate file.
在我的节点应用程序中,我使用“Winston”日志记录在单独的文件中打印错误。
I followed this tutorial.
我跟着这个教程。
When I tried to access the logger from other files....
当我尝试从其他文件访问记录器时......
My code:
我的代码:
var winston = require('winston');
var fs = require('fs');
fs.mkdir('./logs', function(err) {
if (err) throw err;
});
// Define levels to be like log4j in java
var customLevels = {
levels: {
debug: 0,
info: 1,
warn: 2,
error: 3
},
colors: {
debug: 'blue',
info: 'green',
warn: 'yellow',
error: 'red'
}
};
// create the main logger
var logger = new(winston.Logger)({
level: 'debug',
levels: customLevels.levels,
transports: [
// setup console logging
new(winston.transports.Console)({
level: 'info', // Only write logs of info level or higher
levels: customLevels.levels,
colorize: true
}),
// setup logging to file
new(winston.transports.File)({
filename: './logs/project-debug.log',
maxsize: 1024 * 1024 * 10, // 10MB
level: 'debug',
levels: customLevels.levels
})
]
});
// create the data logger - I only log specific app output data here
var datalogger = new (winston.Logger) ({
level: 'info',
transports: [
new (winston.transports.File) ({
filename: './logs/project-data.log',
maxsize: 1024 * 1024 * 10 // 10MB
})
]
});
// make winston aware of your awesome colour choices
winston.addColors(customLevels.colors);
var Logging = function() {
var loggers = {};
// always return the singleton instance, if it has been initialised once already.
if (Logging.prototype._singletonInstance) {
return Logging.prototype._singletonInstance;
}
this.getLogger = function(name) {
return loggers[name];
}
Logging.prototype.get = this.getLogger;
loggers['project-debug.log'] = logger;
loggers['project-data.log'] = datalogger;
Logging.prototype._singletonInstance = this;
};
new Logging(); // I decided to force instantiation of the singleton logger here
logger.info('Logging set up OK!');
module.exports = Logging;
Error is throwing:
错误抛出:
Logging() is undefined.
回答by Ivan Vergiliev
The tutorial seems to have a bunch of errors. I got it working by calling
该教程似乎有一堆错误。我通过打电话让它工作
var logger = logging.Logging().get('project-debug.log');
Notice the .login the argument. The argument has to match one of the names defined in the loggersarray.
注意.log参数中的 。参数必须匹配loggers数组中定义的名称之一。
回答by user3575777
I spent hours on this, here is my solution: Do not create a new Logger, just change the default one.
我花了几个小时来解决这个问题,这是我的解决方案:不要创建一个新的Logger,只需更改默认的。
Create a module lib/logger.js:
创建一个模块lib/logger.js:
var logger = require('winston');
logger.setLevels({debug:0,info: 1,silly:2,warn: 3,error:4,});
logger.addColors({debug: 'green',info: 'cyan',silly: 'magenta',warn: 'yellow',error: 'red'});
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, { level: 'debug', colorize:true });
module.exports = logger;
Use in app.js:
用于app.js:
var logger = require('./lib/log.js');
Use from all other modules:
从所有其他模块使用:
var logger = require('winston');
回答by uzay95
The file I have created and explaind:
我创建并解释的文件:
var winston = require('winston'),
winstonRedis = require('winston-redis').Redis;
// TR: console'da sadece hepsi tutuluyor olacak ?ünkü info log seviyesinden sonra di?er tüm log seviyeleri s?ralanm??
// EN: all log level will be shown in Console, because 'info' is on the top of list with 0 value.
var transportConsole = new winston.transports.Console({ json: false, timestamp: true, prettyPrint:true, colorize: true, level:'info' }),
// TR: File'da sadece i ve db tutuluyor olacak ?ünkü i den sonra db log seviyesi s?ralanm??
// EN: 'i' and 'db' log levels will be shown in File, because db is after i and for File transport level is 'i'
transportFileDebug = new winston.transports.File({ filename: __dirname + '/debug.log', json: true }),
transportFileException = new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false }),
// TR: rediste sadece db tutuluyor olacak ?ünkü db den sonra bir log seviyesi yok
// EN: only 'db' will be stored in rediste because 'db' is the last one
transportRedis = new (winstonRedis)({host: '127.0.0.1', port: 6379, level:'db'});
var logger = new (winston.Logger)({
levels: {
info: 0,
warn: 1,
error: 2,
verbose: 3,
i: 4,
db: 5
},
transports: [
transportConsole,
transportFileDebug,
transportRedis
],
exceptionHandlers: [
transportConsole,
transportFileException
],
exitOnError: false
});
winston.addColors({
info: 'green',
warn: 'cyan',
error: 'red',
verbose: 'blue',
i: 'gray',
db: 'magenta'
});
logger.i('iiiii foobar level-ed message');
logger.db('dbbbbb foobar level-ed message');
logger.info('infoo foobar level-ed message');
logger.warn('warnnnn foobar level-ed message');
logger.error('errroor foobar level-ed message');
module.exports = logger;
回答by Sougata Pal
I have used winston debug logging but it's not that effective. I faced similar problems as well as it crashed sometimes. I recently switched to an new module used by mopublish team. It's wonderful also support http logging via morgan. NPM module elogger - https://github.com/techunits/elogger
我使用了 winston 调试日志记录,但它不是那么有效。我遇到了类似的问题,有时也会崩溃。我最近切换到 mopublish 团队使用的新模块。通过摩根还支持 http 日志记录也很棒。NPM 模块 elogger - https://github.com/techunits/elogger

