Search code examples
node.jswinston

Add module name in winston log entries


Is there a possibility to save the current module name in order to be printed automatically in winston log entries when they are called later?

Currently, when I want to print the module name in logs, I have to add it manually:

var logHeader = 'mymodule'

log.info(logHeader + 'Hello')

For example, with debug, you can do (ignore the log format feature %s for now):

var debug = require('debug')('http')
  , name = 'My App'

debug('booting %s', name);

This will prin http prefix before the log:

http booting My App

Can this be done in winston? I have searched in the documentation but I couldn't find anything relevant.


Solution

  • I found a better way to do this.

    I added an additional layer over the winston logger, in this case a function, that keeps the module name for each module that needs the logger. So when a module requires my new logger, it actually calls the exported function with the module name, in this case __filename.

    log.js

    var winston = require('winston')
    
    var winstonLogger = new (winston.Logger)({
        transports: [
            new (winston.transports.File) ({
                filename: 'MyLogs.txt',
                handleExceptions: true,
                humanReadableUnhandledException: true,
                level: 'info',
                timestamp: true,
                json: false
            }),
            new (winston.transports.Console) ({
                level: 'info',
                prettyPrint: true,
                colorize: true,
                timestamp: true
            })
        ]
    })
    
    module.exports = function(fileName) {    
        var myLogger = {
            error: function(text) {
                winstonLogger.error(fileName + ': ' + text)
            },
            info: function(text) {
                winstonLogger.info(fileName + ': ' + text)
            }
        }
    
        return myLogger
    }
    

    module1.js

    var log = require('log')(__filename)
    
    log.info('Info log example')
    

    info: C:\Users\user1\project\module1.js: Info log example

    module2.js

    var log = require('log')(__filename)
    
    log.error('Error log example')
    

    error: C:\Users\user1\project\module2.js: Error log example

    Also, this way, I didn't need to change anywhere the way I submit a text log; log.info('text') stays exactly like before.