Skip to content

Commit

Permalink
Merge 7737143 into 30f558f
Browse files Browse the repository at this point in the history
  • Loading branch information
anton-johansson committed Mar 8, 2019
2 parents 30f558f + 7737143 commit cfcdf0d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
14 changes: 14 additions & 0 deletions README.md
Expand Up @@ -88,6 +88,20 @@ Level and output:
| `{ level: 'fatal' }` | - | - | - | - | - | O |
| `{ level: 'none' }` | - | - | - | - | - | - |
## loggerName
Specify the name of the logger. Useful when logging from different files.
```js
const Logger = require('node-json-logger');
const logger = new Logger({ loggerName: 'server/index.js' });

logger.info('message');
```
Output:
```json
{"timestamp":"2001-03-14T01:00:00.000Z","level":"info","loggerName":"server/index.js","message":"message"}
```
## timestamp
Specify enable or disable timestamp. (optional, default is true)
Expand Down
13 changes: 13 additions & 0 deletions index.test.js
Expand Up @@ -162,3 +162,16 @@ test('Timezone can be declared with config.', t => {
t.is('America/Sao_Paulo', logger.options.timezone);
});
});

test('Logger name can be set', t => {
const console = new Console();
const logger = new Logger({ level: 'info', loggerName: 'server/index.js' });
const timestamp = "2001-03-14T01:00:00.000Z";
logger.timestamp = () => timestamp;
logger.writeln = o => console.log(JSON.stringify(o));

logger.info('Hello world!');
const expected = `{"timestamp":"${timestamp}","level":"info","loggerName":"server/index.js","message":"Hello world!"}`;
const actual = console.last();
t.is(expected, actual);
});
14 changes: 11 additions & 3 deletions lib/logger.js
Expand Up @@ -17,9 +17,17 @@ module.exports = class Logger {

this.writeln = $object => console.log(JSON.stringify($object));

this.head = this.options.timestamp
? level => ({ timestamp: this.timestamp(), level: level })
: level => ({ level: level });
this.head = level => {
const data = {};
if (this.options.timestamp) {
data.timestamp = this.timestamp();
}
data.level = level;
if (this.options.loggerName) {
data.loggerName = this.options.loggerName;
}
return data;
};

this.trace = this.debug = this.info = this.warn = this.error = this.fatal = () => { };
const level = levels.includes(this.options.level) ? this.options.level : 'debug';
Expand Down

0 comments on commit cfcdf0d

Please sign in to comment.