Skip to content

Commit

Permalink
Allow setting logger name to separate components (#355)
Browse files Browse the repository at this point in the history
  • Loading branch information
bkeepers committed Jan 29, 2018
1 parent 8a5ad67 commit 0a4b297
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 4 deletions.
12 changes: 11 additions & 1 deletion lib/logger.js
Expand Up @@ -44,7 +44,17 @@ Logger.prototype.wrap = function () {
})

// Expose `child` method for creating new wrapped loggers
fn.child = (attrs) => this.child(attrs, true).wrap()
fn.child = (attrs) => {
// Bunyan doesn't allow you to overwrite name…
const name = attrs.name
delete attrs.name
const log = this.child(attrs, true)

// …Sorry, bunyan, doing it anwyway
if (name) log.fields.name = name

return log.wrap()
}

// Expose target logger
fn.target = logger
Expand Down
2 changes: 1 addition & 1 deletion lib/middleware/logging.js
Expand Up @@ -11,7 +11,7 @@ module.exports = function logRequest ({logger}) {
res.setHeader('x-request-id', req.id)

// Make a logger available on the request
req.log = logger.wrap().child({id: req.id})
req.log = logger.wrap().child({name: 'http', id: req.id})

// Request started
req.log.trace({req}, `${req.method} ${req.url}`)
Expand Down
4 changes: 2 additions & 2 deletions lib/robot.js
Expand Up @@ -93,7 +93,7 @@ class Robot {

return this.events.on(name, async event => {
if (!action || action === event.payload.action) {
const log = this.log.child({id: event.id})
const log = this.log.child({name: 'event', id: event.id})

try {
const github = await this.auth(event.payload.installation.id, log)
Expand Down Expand Up @@ -141,7 +141,7 @@ class Robot {
debug: process.env.LOG_LEVEL === 'trace',
host: process.env.GHE_HOST || 'api.github.com',
pathPrefix: process.env.GHE_HOST ? '/api/v3' : '',
logger: log.child({installation: id})
logger: log.child({name: 'github', installation: id})
})

if (id) {
Expand Down
29 changes: 29 additions & 0 deletions test/logger.test.js
@@ -0,0 +1,29 @@
const logger = require('../lib/logger')

describe('logger', () => {
let output

beforeEach(() => {
output = []

logger.addStream({
level: 'trace',
type: 'raw',
stream: {write: log => output.push(log)}
})
})

describe('child', () => {
test('sets attributes', () => {
const child = logger.wrap().child({user: 'me'})
child.debug('attributes will get added to this')
expect(output[0]).toHaveProperty('user', 'me')
})

test('allows setting the name', () => {
const child = logger.wrap().child({name: 'test'})
child.debug('hello')
expect(output[0]).toHaveProperty('name', 'test')
})
})
})

0 comments on commit 0a4b297

Please sign in to comment.