Skip to content
Grant Carthew edited this page Oct 25, 2024 · 9 revisions

Method Signature

log.child(object)

Type: Function

Parameter: Object with one or more key / value pairs.

Returns: Object as a child logger.

Example:

import Perj from 'perj'
const log = new Perj(options)
const child = log.child({ module: 'mail' })
child.info('child log message')

Description

When you create a logger object from the perj object const log = new Perj() it will get some default top level properties being level, lvl, time, msg, and data. You may wish to add to these properties. You can do so using two different techniques.

The first technique is during the logger creation call. When you use the new Perj() function and create a logger you can pass an object with one or more key / value pairs to assign as top level properties.

import Perj from 'perj'
const log = new Perj({ extra: 'top' })
log.info('foo')
// output: {"level":"info","lvl":30,"extra":"top","time":1526279544491,"msg":"foo","data":""}

The second technique is to use the log.child function call to extend the parent logger with extra top level properties:

// continue from above
const childLog = log.child({ more: 'toppy' })
log.info('parent')
// output: {"level":"info","lvl":30,"extra":"top","time":1526279764200,"msg":"parent","data":""}

childLog.info('child')
// output: {"level":"info","lvl":30,"extra":"top","more":"toppy","time":1526279764200,"msg":"child","data":""}

If you use a top level key that already exists in the parent logger and the key is holding a string value, the value becomes hierarchical. For example:

// continue from above
const newChildLog = log.child({ extra: 'toppy' })
log.info('parent')
// output: {"level":"info","lvl":30,"extra":"top","time":1526279764200,"msg":"parent","data":""}

newChildLog.info('child')
// output: {"level":"info","lvl":30,"extra":"top:toppy","time":1526279764200,"msg":"child","data":""}

See the Top Level Properties document for more detail.

Examples

This example creates three loggers: a parent, first child, and second child.

import Perj from 'perj'
const parent = new Perj()
const firstChild = parent.child({ firstChild: true })
const secondChild = firstChild.child({ secondChild: true })

// Using the three loggers
parent.info('one')
firstChild.info('two')
secondChild.info('three')

/*
Standard output:

{"level":"info","lvl":30,"time":1526280039569,"msg":"one","data":""}
{"level":"info","lvl":30,"firstChild":true,"time":1526280039570,"msg":"two","data":""}
{"level":"info","lvl":30,"firstChild":true,"secondChild":true,"time":1526280039571,"msg":"three","data":""}

*/