Search code examples
node.jsloggingmean-stackwinston

How to put unique file name for winston?


I have 10 files in which i wrote loggs for every file by putting this 2 lines in every file.

winston = require('winston');
winston.add(winston.transports.File, { filename: 'project.log' });

Then i got the error

throw new Error('Transport already attached: ' + instance.name + ", assign a different name");
^

Error: Transport already attached: file, assign a different name

I want the logs of all my controllers(node.js) in only one file.Can anyone help me.Thanks.


Solution

  • Just change your filename property on the object being passed for the new winston.transports.File to be unique.

    For instance, if you're adding those two first lines to 10 separate files you can do something like this which will add _${__filename} to the name of the log file being created by winston. __filename is provided by the Node Module Wrapper to every single module at runtime.

    const winston = require('winston')
    winston.add(winston.transports.File, {filename: `project_${__filename}.log`})
    

    If you want everything in a single file you can just create a new module that represents a Logger.

    // logger.js
    const winston = require('winston')
    const logger = new winston.Logger({
      transports: [ new winston.transports.File({filename: 'project.log'}) ]
    })
    
    module.exports = logger
    

    Then you can require logger.js inside your controllers

    // controller.js
    const logger = require('./logger')
    
    // logs "[controller.js] test-log-entry" to project.log as an info entry
    logger.info(`[${__filename}] test-log-entry')