For a long time I have been a big fan of using . is simple to use, works in Node.js and browser, does not require configuration and it is fast. However, problems arise when you need to parse logs. Anything but one-line text messages cannot be parsed in a safe way.
To log structured data, I have been using Winston and Bunyan. These packages are great for application-level logging. I have preferred Bunyan because of the Bunyan CLI program used to pretty-print logs. However, these packages require program-level configuration – when constructing an instance of a logger, you need to define the transport and the log-level. This makes them unsuitable for use in code designed to be consumed by other applications.
Then there is pino. pino is fast JSON logger, it has CLI program equivalent to Bunyan, it decouples transports, and it has sane default configuration. Unfortunately, you still need to instantiate logger instance at the application-level. This makes it more suitable for application-level logging just like Winston and Bunyan.
Members of sequence value represent log index relative to the async execution context. This information can be used to establish the origin of the log invocation in an asynchronous context, e.g.
Notice that even though logs baz 0 and baz 1 were produced at different times, you can tell that one was produced after another by looking at their sequence values 0.1.1.0 and 0.1.1.1.
Requirements
adopt method only works in Node.js.
child
The child function has two signatures:
Accepts an object.
Accepts a function.
Object parameter
(context: MessageContext): Logger,
Creates a child logger that appends child context to every subsequent message.
Example:
import { Roarr as log } from "roarr";const barLog = log.child({ foo: "bar",});log.debug("foo 1");barLog.debug("foo 2");
Just like the regular logger methods, but logs the message only once.
Note: Internally, Roarr keeps a record of the last 1,000 Once invocations. If this buffer overflows, then the message is going to be logged again until the next time the buffer overflows again.
Utilities
getLogLevelName
Provides log level name (trace, debug, ...) for a numeric log level (10, 20, ...).
If numeric log level is between two ranges, then resolves to the one with greater severity (e.g. 5 => trace).
If numeric log level is greater than the maximum supported, then falls back to the greatest severity (fatal).
import { getLogLevelName,} from 'roarr';import type { LogLevelName,} from 'roarr';getLogLevelName(numericLogLevel: number): LogLevelName;
Middlewares
Roarr logger supports middlewares implemented as child message translate functions, e.g.
import { Roarr as log } from "roarr";import createSerializeErrorMiddleware from "@roarr/middleware-serialize-error";const childLog = log.child(createSerializeErrorMiddleware());const error = new Error("foo");log.debug({ error }, "bar");childLog.debug({ error }, "bar");
Raise an issue to add your middleware of your own creation.
CLI program
Roarr CLI program provides ability to filter and pretty-print Roarr logs.
CLI program has been moved to a separate package @roarr/cli.
npm install @roarr/cli -g
Explore all CLI commands and options using roarr --help or refer to @roarr/cli documentation.
Transports
A transport in most logging libraries is something that runs in-process to perform some operation with the finalized log line. For example, a transport might send the log line to a standard syslog server after processing the log line and reformatting it.
Roarr does not support in-process transports.
Roarr does not support in-process transports because Node processes are single threaded processes (ignoring some technical details). Given this restriction, Roarr purposefully offloads handling of the logs to external processes so that the threading capabilities of the OS can be used (or other CPUs).
Depending on your configuration, consider one of the following log transports:
Beats for aggregating at a process level (written in Go).
logagent for aggregating at a process level (written in JavaScript).
Fluentd for aggregating logs at a container orchestration level (e.g. Kubernetes) (written in Ruby).
Node.js environment variables
Use environment variables to control roarr behavior.
Name
Function
Default
ROARR_LOG
Boolean
Enables/ disables logging.
false
ROARR_STREAM
STDOUT, STDERR
Name of the stream where the logs will be written.
STDOUT
When using ROARR_STREAM=STDERR, use 3>&1 1>&2 2>&3 3>&- to pipe stderr output.
Conventions
Context property names
Roarr does not have reserved context property names. However, I encourage use of the following conventions:
Context property name
Use case
application
Name of the application (do not use in code intended for distribution; see package property instead).
logLevel
A numeric value indicating the log level. See API for the build-in loggers with a pre-set log-level.
namespace
Namespace within a package, e.g. function name. Treat the same way that you would construct namespaces when using the debug package.
package
Name of the NPM package.
The roarr pretty-printCLI program is using the context property names suggested in the conventions to pretty-print the logs for the developer inspection purposes.
Log levels
The roarr pretty-printCLI program translates logLevel values to the following human-readable names:
logLevel
Human-readable name
10
TRACE
20
DEBUG
30
INFO
40
WARN
50
ERROR
60
FATAL
Using Roarr in an application
To avoid code duplication, you can use a singleton pattern to export a logger instance with predefined context properties (e.g. describing the application).
I recommend to create a file Logger.js in the project directory. Inside this file create and export a child instance of Roarr with context parameters describing the project and the script instance, e.g.
/** * @file Example contents of a Logger.js file. */import { Roarr } from "roarr";export const Logger = Roarr.child({ // .foo property is going to appear only in the logs that are created using // the current instance of a Roarr logger. foo: "bar",});
Roarr does not have reserved context property names. However, I encourage use of the conventions.
Recipes
Overriding message serializer
Roarr is opinionated about how it serializes (converts objects to JSON string) log messages, e.g. in Node.js it uses a schema based serializer, which is very fast, but does not allow custom top-level properties.
You can override this serializer by defining ROARR.serializeMessage:
In Node.js, Roarr registers an error listener on the configured output stream to ignore EPIPE errors. Test runners that create isolated module environments may need to remove that listener during teardown.
import { ROARR } from "roarr";afterEach(() => { ROARR.teardown?.();});
This is only needed for test environments that repeatedly load Roarr in the same process.
Logging errors
This is not specific to Roarr – this suggestion applies to any kind of logging.
If you want to include an instance of Error in the context, you must serialize the error.
The least-error prone way to do this is to use an existing library, e.g. serialize-error.
import { Roarr as log } from "roarr";import serializeError from "serialize-error";// [..]send((error, result) => { if (error) { log.error( { error: serializeError(error), }, "message not sent due to a remote error", ); return; } // [..]});
Without using serialization, your errors will be logged without the error name and stack trace.
Anti-patterns
Overriding globalThis.ROARR.write in Node.js
Overriding globalThis.ROARR.write in Node.js works the same way as it does in browser. However, overriding ROARR.write in Node.js is considered an anti-pattern because it defeats some of the major benefits outlined in Motivation section of the documentation. Namely, by overriding ROARR.write in Node.js you are adding blocking events to the event cycle and coupling application logic with log handling logic.
If you have a use case that asks for overriding ROARR.write in Node.js, then raise an issue to discuss your requirements.
The following serves as the ground work for the index template. It includes the main Roarr log message properties (context, message, time) and the context properties suggested in the conventions.
and configure the individual programs to use RoarrLogger. In case of Kubernetes, this means adding a log.config.scalyr.com/attributes.parser: RoarrLogger annotation to the associated deployment, pod or container.
Using with NestJS
If you are using NestJS, you can use nestjs-logger-roarr to perform logging inside your application.
To enable one shared logger for the entire application:
To enable mutiple injected loggers via the usual Module syntax:
import { Module } from '@nestjs/common';import { ConfigModule } from '@nestjs/config;import { RoarrLoggerModule } from 'nestjs-logger-roarr';@Module({ imports: [ RoarrLoggerModule.forRoot({ logLevel: 'warn', // this is the *minimum* log level that will be displayed }), ]})export class AppModule {}
Documenting use of Roarr
If your package is using Roarr, include instructions in README.md describing how to enable logging, e.g.
## LoggingThis project uses [`roarr`](https://www.npmjs.com/package/roarr) logger to log the program's state.Export `ROARR_LOG=true` environment variable to enable log printing to `stdout`.Use [`roarr-cli`](https://github.com/gajus/roarr-cli) program to pretty-print the logs.
Context Truncation
Roarr by default truncates context properties if the context object is wider or deeper than 10 properties. At the moment, this is a hard-coded value. Waiting for feedback on whether this is a reasonable default and if it needs to be configurable.
When the context goes over this limit, you will start seeing ... entries in your logs, e.g.