节点Winston使用名称实例化每个实例

时间:2017-03-03 19:44:21

标签: node.js winston

这是我的winston记录器类:

const winston = require('winston');
const config = require('../config');
const env = process.env;

winston.setLevels({
    debug:0,
    info: 1,
    silly:2,
    warn: 3,
    error:4,
});

winston.addColors({
    debug: 'green',
    info:  'cyan',
    silly: 'magenta',
    warn:  'yellow',
    error: 'red'
});

let transports = [];
transports.push(new (winston.transports.File)({filename: config.logger.fileName}));
if (env.CONSOLE == 'true' || config.logger.consoleLog) {
    transports.push(new (winston.transports.Console)({colorize:true}));
}

winston.configure({
    transports: transports
});

if (config.logger.debug || env.DEBUG == 'true') {
    winston.level = 'debug';
}


module.exports = winston;

我这样使用它:

const logger = require('src/logger');
logger.info("Hello there");

问题是所有文件都会附加到同一个文件而没有任何区别;我希望能够设置"名称"所以在我的日志中,我看到类似" [Name1] ......" " [Name2] ......"等

我如何做到这一点?

1 个答案:

答案 0 :(得分:1)

温斯顿有一个' categories'的概念。但是没有简单的方法将类别名称放入日志消息中。

这是一种利用'标签'的解决方法。财产来实现这个目标:



'use strict';

const winston = require('winston');

winston.setLevels({
	debug: 0,
	info: 1,
	silly: 2,
	warn: 3,
	error: 4,
});

winston.addColors({
	debug: 'green',
	info: 'cyan',
	silly: 'magenta',
	warn: 'yellow',
	error: 'red'
});

const getLogger = function (category) {
	//If we call .get it'll create a default logger
	//We don't need a default one, we want to configure the
	//transports/labels, so we check if it exists
	//and return only if it's configured properly
	if (winston.loggers[category]) {
		return winston.loggers.get(category);
	}

	//Apply your logic to identify log level here.
	let level = 'silly';

	//Set up the transports you need (omit console if needed)
	let transports = [
		new (winston.transports.File)({
			filename: './logs.txt',
			//Notice this 'label' property
			label: category,
			level
		}),
		new (winston.transports.Console)({
			colorize: true,
			label: category,
			level
		})
	];

	return winston.loggers.add(category, {transports});
};

module.exports = {getLogger};

const generalLogger = getLogger('general');
const appleLogger = getLogger('apple');
const orangeLogger = getLogger('orange');

generalLogger.log('info', 'general logger');
appleLogger.log('info', 'apple logger');
orangeLogger.log('info', 'orange logger');




因此,您导出getLogger而不是winston,然后您将获得以下日志消息:

info: [general] general logger
info: [apple] apple logger
info: [orange] orange logger



{"level":"info","message":"general logger","label":"general","timestamp":"2017-03-06T07:08:04.959Z"}
{"level":"info","message":"apple logger","label":"apple","timestamp":"2017-03-06T07:08:04.962Z"}
{"level":"info","message":"orange logger","label":"orange","timestamp":"2017-03-06T07:08:04.963Z"}




希望这会有所帮助。此处还有similar thread