How do I put a unique filename for winston?

I have 10 files where I was writing logs for each file, putting these 2 lines in each 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) to be in only one file. Can someone help me. Thank.

+3


source to share


1 answer


Just change the property filename

to the passed object so the new one is winston.transports.File

unique.

For example, if you add these first two lines in 10 separate files, you can do something like this that will add _${__filename}

to the name of the log file generated by winston. Node Module Wrapper is__filename

provided for each module at runtime.

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

      

If you want everything in one file, you can simply create a new module that represents the 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') 

      

+2


source







All Articles