In this simple app where two different files foo.js
and bar.js
imports Logger.js
to create a bunyan
child logger.
Problem: foo.js
works flawlessly but bar.js
has a problem finding MyService.log
defined in Logger.js
. This appears to be due to the relative path to MyService.log
being fixed, while foo.js
and bar.js
resides in different directory levels relative to the project root directory.
What will be a better way to create bunyan
child logger?
.
├── lib
| └── Logger.js
├── foo
| └── foo.js
├── bar.js
/src/lib/Logger.js
const bunyan = require('bunyan')
const logger = bunyan.createLogger({
name: 'MyService',
streams: [
{
stream: process.stdout,
level: "info"
},
{
type: 'rotating-file',
path: '../logs/MyService.log',
period: '1w',
count: 100,
level: "debug"
}
]
})
module.exports = {
getChildLogger(componentName) {
return logger.child({
component: componentName
})
}
}
/src/foo/foo.js
const log = require('../lib/Logger').getChildLogger('foo')
log.info('Foo')
/src/bar.js
const log = require('./lib/Logger').getChildLogger('foo')
log.info('Bar')
Instead of relative path, try using absolute file path using path module (core).
const path = require('path');
const loggerPath = path.join(__dirname, '..', 'logs', 'MyService.log');