Reputation: 88
I am using winston for logging in my nodejs project. I am storing an error level log in my connected mongo db.The following is my configuration -
logger = new (winston.Logger)({
transports : [
new(winston.transports.MongoDB)({
name : 'admin_log_error',
db : mongodbConfig.developmentUrl,
collection : 'admin_log',
expireAfterSeconds : oneWeekInSeconds,
level : 'error'
}),
new(winston.transports.MongoDB)({
name : 'admin_log_warn',
db : mongodbConfig.developmentUrl,
collection : 'admin_log',
expireAfterSeconds : oneWeekInSeconds,
level : 'warn'
}),
new(winston.transports.MongoDB)({
name : 'admin_log_debug',
db : mongodbConfig.developmentUrl,
collection : 'admin_log',
expireAfterSeconds : oneWeekInSeconds,
level : 'debug'
})
]
});
This is the way I use it.
logger.log('error',message,metadata);
But on checking in mongo db in the collection admin_log whenever there is an error level log there are two duplicate documents. No such thing in warn or debug level. How can I resolve this, has anyone faced similar problem.
Upvotes: 0
Views: 905
Reputation: 1
I used this code, worked for me
const { createLogger, transports, format } = require('winston');
require('winston-mongodb');
const myLevels = {
superImportant: 0,
mediocre: 1,
whoCares: 2
}
const logger = createLogger({
levels: myLevels,
transports: [
new transports.MongoDB({
level: 'whoCares',
db: 'mongodb://localhost:27017/mylib',
options: {
useUnifiedTopology: true
},
collection: 'book',
format: format.combine(format.timestamp(), format.json())
}),
]
})
module.exports = logger;
just define the last level key for me it's "whoCares", in the new transports.MongoDB level object.
Upvotes: 0
Reputation: 11330
Winston's documentation states that -
winston allows you to define a level property on each transport which specifies the maximum level of messages that a transport should log.
By default the priority given to various levels is -
{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }
So if you specify the level as error
then the maximum level of messages that winston will log is 0
. As a result all the levels having value more than 0
will not be logged so you would only see error
level logs.
Instead if you specify the log level as info
then winston will log all the levels whose value is upto 2
as this is the value for info
level. As a result error
, warn
and info
- All 3 levels will be logged in this logger as their value is less than or equal to 2
.
In your case you've specified 3 loggers with different levels. Now when you execute
logger.log('error',message,metadata);
Then all the 3 loggers in your configuration have their levels set to greater than the level of error
. As a result all three loggers will log that value. That's the problem you're having.
Hope this makes things clear.
Upvotes: 2