rotating-file can't be found when it's required in multiple modules/files
Hi all,
Thanks for your help in advance!
I am using bunyan 1.4.0 and node 0.10.24 on Linux. I have define a log with bunyan in a local file utils.js:
exports.getLogger = function (logLevel) {
var log = bunyan.createLogger({
name: 'log_test',
streams: [
{
type: 'rotating-file',
path: __dirname + '/logs/node.log',
level: logLevel || 'info',
period: '6000ms',
count: 7
},
{
path: './logs/node_err.log',
level: 'error'
},
],
serializers: {
req: reqSerializer,
res: bunyan.stdSerializers.res
}
});
return log;
};
The utils.js has to be required in several other files. I find that if it is required in 2 files, both of them use log.info() and log.error(), I'll get ENOENT, rename '/.../node.log.X', and X is usually the 2nd last number. for e.g, if the rotation count is 6, and X is 5 almost all the time.
If I include the utils.js in only one file by require(), the rotation works fine.
sorry for typos. The ENOENT error comes up when the utils.js is required in more than 2 files.
If you call getLogger multiple times you're going to be running multiple instances of the file rotator. Each one will try to rotate the files and they'll conflict with each other.
You need to create a single log instance, cache it and return it. There's currently no way of having multiple file rotators play nice together.
I'd change your code to something like:
var log = null
exports.getLogger = function (logLevel) {
log = log || bunyan.createLogger({
name: 'log_test',
streams: [
{
type: 'rotating-file',
path: __dirname + '/logs/node.log',
level: logLevel || 'info',
period: '6000ms',
count: 7
},
{
path: './logs/node_err.log',
level: 'error'
},
],
serializers: {
req: reqSerializer,
res: bunyan.stdSerializers.res
}
});
return log;
};
This appears to be a very common mistake. We can't do much at the moment when working between processes, but when creating multiple rotators in the same process, we can detect that.
My 3rd party rotating file stream will detect that you're trying to do this and fail with an error immediately so you know what's wrong.
I think @Rcomian answered this. Thanks.
@Rcomian , Thank you. The issue has been fixed.