Skip to content
Grant Carthew edited this page May 13, 2018 · 13 revisions

perj dateTimeFunction Option

The dateTimeFunction option enables you to change the date / time output format.

Type: Function

Default: function () { return Date.now() }

The default will return the epoch time.

Valid: function () { return // valid JSON type }

The assigned function should take no arguments and return a valid JSON data type. See the JSON specification for valid data types. If you are returning a String it should be encapsulated within quotes. It probably goes without saying that the returned value from the function should be related to the date and time of the log message.

Description:

The dateTimeFunction option is used to change the value assigned to the dateTimeKey key in the JSON output. There is a set of helper functions you can use to switch from the default epoch time to unix time or iso format.

Here is a copy of the helper functions in the perj.js file:

const dateTimeFunctions = Object.freeze({
  epoch () { return Date.now() },
  unix () { return Math.round(Date.now() / 1000.0) },
  iso () { return '"' + (new Date()).toISOString() + '"' }
})

Example

This example changes the dateTimeFunction to show the different results of the three helper functions:

const perj = require('perj')
const epochLog = perj.create({ dateTimeFunction: perj.dateTimeFunctions.epoch })
const unixLog = perj.create({ dateTimeFunction: perj.dateTimeFunctions.unix })
const isoLog = perj.create({ dateTimeFunction: perj.dateTimeFunctions.iso })

epochLog.info('epoch time format')
unixLog.info('unix time format')
isoLog.info('iso time format')

/*

Standard out will be:

{"level":"info","lvl":30,"time":1526204540185,"msg":"epoch time format","data":""}
{"level":"info","lvl":30,"time":1526204540,"msg":"unix time format","data":""}
{"level":"info","lvl":30,"time":"2018-05-13T09:42:20.187Z","msg":"iso time format","data":""}

*/

The following example uses a custom format function assigned to the dateTimeFunction option. It will have a performance hit:

const perj = require('./perj')
const log = perj.create({ dateTimeFunction: myDateFormat })

function myDateFormat () {
  const dt = new Date()
  return '"' + dt.getFullYear() +
  '-' + ('0' + (dt.getMonth() + 1)).slice(-2) +
  '-' + ('0' + dt.getDate()).slice(-2) +
  ' ' + ('0' + dt.getHours()).slice(-2) +
  ':' + ('0' + dt.getMinutes()).slice(-2) +
  ':' + ('0' + dt.getSeconds()).slice(-2) +
  '.' + ('00' + dt.getMilliseconds()).slice(-3) +
  '"'
}

log.info('How\'s this for a format?')

/*

Standard out will be:

{"level":"info","lvl":30,"time":"2018-05-13 20:16:09.786","msg":"How's this for a format?","data":""}

*/