-
Notifications
You must be signed in to change notification settings - Fork 1
dateTimeFunction
The dateTimeFunction
option enables you to change the date / time output format.
The default will return the epoch time.
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.
The dateTimeFunction
option is used to change the value assigned to the dateTimeKey key in the JSON output. There is an example file containing the default epoch time function and a unix time and iso time formats.
Here are the three functions from the example file mentioned above:
function epoch () { return Date.now() }
function unix () { return Math.round(Date.now() / 1000.0) }
function iso () { return '"' + (new Date()).toISOString() + '"' }
This example changes the dateTimeFunction
to show the different results of the common three functions:
const Perj = require('perj')
const epochLog = new Perj({ dateTimeFunction: epoch })
const unixLog = new Perj({ dateTimeFunction: unix })
const isoLog = new Perj({ dateTimeFunction: iso })
function epoch () { return Date.now() }
function unix () { return Math.round(Date.now() / 1000.0) }
function iso () { return '"' + (new Date()).toISOString() + '"' }
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 = new Perj({ 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":""}
*/