Skip to content

Instantly share code, notes, and snippets.

@doasync
Last active June 2, 2023 21:57
Show Gist options
  • Select an option

  • Save doasync/5833b370759594e88b084a97198bd93b to your computer and use it in GitHub Desktop.

Select an option

Save doasync/5833b370759594e88b084a97198bd93b to your computer and use it in GitHub Desktop.
Pino logger: log prettyfied messages to console + log to separate files WARN, ERROR, FATAL (pino-tee module in child process)
const pino = require('pino');
const childProcess = require('child_process');
const stream = require('stream');
// Environment variables
const cwd = process.cwd();
const {env} = process;
const logPath = `${cwd}/log`;
// Create a stream where the logs will be written
const logThrough = new stream.PassThrough();
const log = pino({name: 'project'}, logThrough);
// Log to multiple files using a separate process
const child = childProcess.spawn(process.execPath, [
require.resolve('pino-tee'),
'warn', `${logPath}/warn.log`,
'error', `${logPath}/error.log`,
'fatal', `${logPath}/fatal.log`
], {cwd, env});
logThrough.pipe(child.stdin);
// Log pretty messages to console (optional, for development purposes only)
const pretty = pino.pretty();
pretty.pipe(process.stdout);
logThrough.pipe(pretty);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment