-
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.
By default a simple epoch function is used. If you wish your logs to use unix time or iso time format, change the function by using the dateTimeFunction
option.
Please consider the logger performance when changing this option. Using the iso time format or other more complex formatting functions can have a large effect on the logger speed.
Here are the common time format functions for reference:
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:
import Perj from '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:
import Perj from '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":""}
*/