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

perj write Option

The write option enables you to change the default output target of process.stdout for Node.js, or console.log for the browser, to a custom function.

Type: Function

Default:

Node: process.stdout.write.bind(process.stdout)

Browser: console.log

Valid:

With passThrough set to false:

  • function (String) { // process JSON here }

With passThrough set to true:

  • function (String, Object) { // process JSON and Object here }

Description:

The write option allows you to intercept the JSON string. To send the JSON log strings to a data store, consider piping standard out to standard in of a transport module. See the Transports document for more detail.

If you enable the passThrough option when creating the logger, then perj will pass the JSON string and the object used to create it through to the write function. This can be useful for getting the time or other values from the log message without having to JSON.parse() the JSON string. See the passThrough document for more detail.

See the Examples document for ideas how you can use the write option.

Example

This example changes the write option to display full log message details out to the console:

import Perj from 'perj';
import os from 'os';
import path from 'path';

// Customize the variables below as needed. They are not required.
const ver = 1;
const name = 'example';
const host = os.hostname();
const pid = process.pid;
const file = path.basename(import.meta.url, '.js');
const passThrough = true

const log = new Perj({ name, host, pid, file, passThrough, write })

function write (logString, logObject) {
  const dt = new Date(logObject.time)
  let output = `[${dt.toISOString()}][${logObject.level}][${logObject.name}](${logObject.host}:${logObject.pid}:${logObject.file}) ${logObject.msg}\n`
  output += JSON.stringify(logObject.data, null, 2)
  console.log(output)
}

log.info('example text for logging', { foo: 'bar' })


/*

Console output will be:

[2018-05-03T02:46:54.611Z][info][example](Dev:7094:console-full.js) example text for logging
{
  "foo": "bar"
}

*/