Reputation: 904
I want to use Winston for logging in my nodejs express project. In my main file( server.js ) I have the following code :
const winston = require('winston');
winston.level = process.env.LOG_LEVEL
winston.log('info', 'Hello log files!')
I want to use this library in other files as well, so do I have to add these 2 lines to every file I want to use it or is there a better way to do it.
Upvotes: 0
Views: 390
Reputation: 303
The preferred way of doing this is adding your custom logger to the winston object:
var winston = require('winston');
// add a new logger to the winston object
winston.loggers.add('logger1', {
console: {
level: 'silly',
colorize: true,
label: 'Console One'
},
file: {
filename: '/path/to/your/logfile.log'
level: process.env.LOG_LEVEL
}
}
After setting up your logger as described in the snippet above you can just "get" the logger in any other file in your application:
var winston = require('winston');
// get your preconfigured logger
var myLogger = winston.loggers.get('logger1');
// start logging!
myLogger.error('FooError');
myLogger.log('warn', 'Exiting application');
This is also the way, which is described in the winston documentation: Winston Docs
Upvotes: 1
Reputation: 6364
You can export and call it like this.
const winston = require('winston');
winston.level = process.env.LOG_LEVEL
module.exports = winston;
In other file
const winston = require('/path/to/winston');
winston.log('blah blah');
Or, just make it global and call it. (not recommended)
const winston = require('winston');
winston.level = process.env.LOG_LEVEL
global.WINSTON = winston;
...
// other file
WINSTON.log('blah')
Upvotes: 1
Reputation: 412
you can create customWinston.js File:
let winston = require('winston');
winston.level = process.env.LOG_LEVEL
winston.log('info', 'Hello log files!')
exports.customWinston = winston;
and then require your custom Winston:
let customWinston = require('./customWinston').customWinston;
Upvotes: 1