We are using log4js-node for logging in our node.js applications. It includes a bunch of log appenders, like console or file. But since we need an audit trail in our applications, we have to log into the database. So we wrote a log4js-node appender for logging into mongodb.
Install
Business a usual…$ npm install log4js-node-mongodb
Usage
You can use this appender like all other log4js-node appenders. It just needs the connection-string to the mongo db. The default collection used is log. You can log astring or any kind of object. The objects are stored as they are and not converted to strings.var log4js = require('log4js'),
mongoAppender = require('log4js-node-mongodb');
log4js.addAppender(
mongoAppender.appender({
connectionString: 'localhost:27017/logs'
}),
'cheese'
);
var logger = log4js.getLogger('cheese');
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');
// log objects
logger.info({id: 1, name: 'wayne'});
logger.info([1, 2, 3]);
Or you can use the configure method.var log4js = require('log4js');
log4js.configure({
appenders: [
{
type: 'console'
},
{
type: 'log4js-node-mongodb',
connectionString: 'localhost:27017/logs',
category: 'cheese'
}
]
});
The log data is stored in the following format.{
_id: ObjectID,
timestamp: loggingEvent.startTime,
data: loggingEvent.data,
level: loggingEvent.level,
category: loggingEvent.logger.category
}
Here some examples.var log4js = require('log4js'),
mongoAppender = require('log4js-node-mongodb');
log4js.addAppender(
mongoAppender.appender(
{connectionString: 'localhost:27017/logs'}),
'audit'
);
var logger = log4js.getLogger('audit');
logger.debug('Hello %s, your are user no %d!', 'wayne', 10);
// saved as
{
_id: new ObjectID(),
timestamp: new Date(),
data: 'Hello wayne, your are user no 10!',
level: {
level: 10000,
levelStr: 'DEBUG'
},
category: 'audit'
}
logger.info({id: 1, name: 'wayne'});
// saved as
{
_id: new ObjectID(),
timestamp: new Date(),
data: {
id: 1,
name: 'wayne'
},
level: {
level: 20000,
levelStr: 'INFO'
},
category: 'audit'
}
Options
There are some options which can by set through the config object.| name | type | default value | required |
|---|---|---|---|
| connectionString | string |
undefined |
yes |
| collectionName | string |
'log' |
no |
| write | string |
'fast' |
no |
| layout | string |
'messagePassThroughLayout' |
no |
var log4js = require('log4js'),
mongoAppender = require('log4js-node-mongodb');
log4js.addAppender(
mongoAppender.appender({
connectionString: 'localhost:27017/logs',
collectionName: 'audit',
write: 'safe'
}),
'audit'
);
var logger = log4js.getLogger('audit');
logger.info('User %s logged in', 'wayne');
The complete documentation can be found in the github repo.
Keine Kommentare:
Kommentar veröffentlichen