question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Winston logs to all files. (or: Restrict transport to only 1 level)

See original GitHub issue

This is my winston config:

var winston = require('winston');
var fs = require('fs');
var _ = require('lodash');

winston.emitErrs = true;

var logDir = 'logs';
if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
}

//add custom logging levels
var levels = _.clone(winston.config.syslog.levels);
var colors = _.clone(winston.config.syslog.colors);

levels.request = _.max(levels) + 1;
colors.request = 'blue';

var logger = new winston.Logger({
    levels: levels,
    colors: colors,
    exceptionHandlers: [
        new winston.transports.File({filename: 'logs/exceptions.log'})
    ],
    transports: [
        new winston.transports.File({
            name: 'info-file',
            level: 'info',
            filename: 'logs/all-logs.log',
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.File({
            name: 'error-file',
            level: 'error',
            filename: 'logs/error-logs.log',
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.File({
            name: 'request-file',
            level: 'request',
            filename: 'logs/requests.log',
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        })
    ],
    exitOnError: false
});

module.exports = logger;

I’m trying to log, errors, http-requests, and exceptions to their own files. However, I see, for example, in error-logs.log (http)requests logs.

Can anybody explain to me what I’m doing wrong?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:4
  • Comments:25 (2 by maintainers)

github_iconTop GitHub Comments

24reactions
ngthienlinhcommented, Jul 14, 2018

I’m using the 3.x winston, after trials and errors I find out that we can filter log by level to log them to separate files. Here is the code I used:

const customFormat = winston.format.printf(i => {
	return `${i.level.toUpperCase()}: ${i.timestamp} ${i.message}`;
});

// Log unhandled exceptions to separate file
var exceptionHandlers = [
	new (winston.transports.DailyRotateFile)({
		name: 'Error Logs',
		filename: 'server/logs/errlogs/exceptions-%DATE%.log',
		datePattern: 'YYYY-MM-DD',
		zippedArchive: true,
		maxSize: '128m',
		maxFiles: '14d'
	})
]

const infoAndWarnFilter = winston.format((info, opts) => { 
	return info.level === 'info' || info.level === 'warn' ? info : false
})

const errorFilter = winston.format((info, opts) => { 
	return info.level === 'error' ? info : false 
})

// Separate warn/error 
var transports = [
	new (winston.transports.DailyRotateFile)({
		name: 'Error Logs',
		filename: 'server/logs/errlogs/application-%DATE%.log',
		datePattern: 'YYYY-MM-DD',
		zippedArchive: true,
		maxSize: '128m',
		maxFiles: '14d',
		level: 'warn',
		json: true,
		colorize: false,
		format: winston.format.combine(
			errorFilter(),
			winston.format.timestamp(),
			customFormat
		)
	}),
	new (winston.transports.DailyRotateFile)({
		name: 'INFO logs',
		filename: 'server/logs/infologs/application-%DATE%.log',
		datePattern: 'YYYY-MM-DD',
		zippedArchive: true,
		maxSize: '128m',
		maxFiles: '14d',
		json: true,
		colorize: false,
		level: 'info',
		format: winston.format.combine(
			infoAndWarnFilter(),
			winston.format.timestamp(),
			customFormat
		)
	}),
	new (winston.transports.Console)({		
		level: config.debugMode ? 'debug' : 'warn', // log warn level to console only
		handleExceptions: true,
		json: false,
		colorize: true,
		format: winston.format.combine(
			winston.format.colorize(),
			winston.format.simple()
		)
	})
]

var logger = winston.createLogger({
	transports: transports,
	exceptionHandlers: exceptionHandlers,
	level: config.debugMode ? 'debug' : 'info',
	exitOnError: false,
	// Default format
	format: winston.format.combine(
		winston.format.timestamp(),
		customFormat
	)
})
9reactions
masomcommented, Jun 22, 2015

@NukaPunk Isn’t this the expected behaviour of a logger?

Usually a logger instance will log to all transports that match the minimum level of the message. Ex: debug -> info -> warning -> error. A transport that handles info will not log debug messages but will log info, warning and error.

This is usually solved by creating multiple logger instances, each handling a specific case.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Winston Logging - separate levels to separate Transports
Winston allows you to define a level property on each transport which specifies the maximum level of messages that a transport should log....
Read more >
Winston logs to all files. (or: Restrict transport to only 1 level)
This is my winston config: var winston = require('winston'); var fs = require('fs'); var _ = require('lodash'); winston.emitErrs = true; var logDir =...
Read more >
A Complete Guide to Winston Logging in Node.js - Better Stack
Learn how to start logging with Winston in Node.js and go from basics to best practices ... (not just File ), since they...
Read more >
Complete Winston Logger Guide With Hands-on Examples
With Winston, you can change your code in a single place and customize the format of your logs (e.g., logging in JSON format,...
Read more >
Node.js Logging with Winston - Reflectoring
Transports is a Winston feature that makes use of the Node.js networking, stream, and non-blocking I/O properties. Transport in Winston refers ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found