Roarr

JSON logger for Node.js and browser.

README

Roarr

Travis build status Coveralls NPM version Canonical Code Style Twitter Follow

JSON logger for Node.js and browser.

    Motivation
    Usage
        Producing logs
        Consuming logs
        Filtering logs
    API
        [adopt](#roarr-api-adopt)
        [child](#roarr-api-child)
        [getContext](#roarr-api-getcontext)
        [trace](#roarr-api-trace)
        [debug](#roarr-api-debug)
        [info](#roarr-api-info)
        [warn](#roarr-api-warn)
        [error](#roarr-api-error)
        [fatal](#roarr-api-fatal)
        [traceOnce](#roarr-api-traceonce)
        [debugOnce](#roarr-api-debugonce)
        [infoOnce](#roarr-api-infoonce)
        [warnOnce](#roarr-api-warnonce)
        [errorOnce](#roarr-api-erroronce)
        [fatalOnce](#roarr-api-fatalonce)
    Utilities
        [getLogLevelName](#roarr-utilities-getloglevelname)
    Middlewares
    CLI program
    Transports
    Conventions
        Context property names
    Recipes
        Logging errors
        [Overriding globalThis.ROARR.write in Node.js](#roarr-anti-patterns-overriding-globalthis-roarr-write-in-node-js)
    Integrations
        Using with Sentry
        Using with Fastify
        Using with Elasticsearch
        Using with Scalyr
    Developing


Motivation


For a long time I have been a big fan of using [debug](https://github.com/visionmedia/debug). debug 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.

I needed a logger that:

Does not block the event cycle (=fast).
Does not require initialization.
Produces structured data.
Works in Node.js and browser.
Configurable using environment variables.

In other words,

a logger that I can use in an application code and in dependencies.
a logger that allows to correlate logs between the main application code and the dependency code.
a logger that works well with transports in external processes.

Roarr is this logger.

Usage


Producing logs


Roarr logger API for producing logs is the same in Node.js and browser.

1. Import roarr
2. Use any of the API methods to log messages.

Example:

  1. ```ts
  2. import {
  3.   Roarr as log,
  4. } from 'roarr';

  5. log('foo');
  6. ```

Consuming logs


Roarr logs are consumed differently in Node.js and browser.

Node.js


In Node.js, Roarr logging is disabled by default. To enable logging, you must start program with an environment variable ROARR_LOG set to true, e.g.

  1. ``` sh
  2. ROARR_LOG=true node ./index.js
  3. ```

All logs will be written to stdout.

Browser


In a browser, you must implement ROARR.write method to read logs, e.g.

  1. ```ts
  2. import {
  3.   ROARR,
  4. } from 'roarr';

  5. ROARR.write = () => {};
  6. ```

The API of the ROARR.write is:

  1. ```ts
  2. (message: string) => void;
  3. ```

Example implementation:

  1. ```ts
  2. import {
  3.   ROARR,
  4. } from 'roarr';

  5. ROARR.write = (message) => {
  6.   console.log(JSON.parse(message));
  7. };
  8. ```

or if you are initializing ROARR.write _before_ roarr is loaded:

  1. ```ts
  2. // Ensure that `globalThis.ROARR` is configured.
  3. const ROARR = globalThis.ROARR = globalThis.ROARR || {};

  4. ROARR.write = (message) => {
  5.   console.log(JSON.parse(message));
  6. };
  7. ```

If your platform does not support [globalThis](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), use [globalthis polyfill](https://www.npmjs.com/package/globalthis).

You may also use [@roarr/browser-log-writer](https://github.com/gajus/roarr-browser-log-writer) that implements and opinionated browser logger with Liqe query support for filtering logs.

Filtering logs


Node.js


In Node.js, Roarr prints all or none logs (refer to the [ROARR_LOG environment variable](#environment-variables) documentation).

Use [@roarr/cli program](https://github.com/gajus/roarr-cli#filtering-logs) to filter logs, e.g.

  1. ``` sh
  2. ROARR_LOG=true node ./index.js | roarr --filter 'context.logLevel:>30'
  3. ```

Browser


In a browser, Roarr calls globalThis.ROARR.write for every log message. Implement your own custom logic to filter logs, e.g.

  1. ```ts
  2. globalThis.ROARR.write = (message) => {
  3.   const payload = JSON.parse(message);

  4.   if (payload.context.logLevel > 30) {
  5.     console.log(payload);
  6.   }
  7. };
  8. ```

Log message format


|Property|Contents|
|---|---|
|`context`|Arbitrary,
|`message`|User-provided
|`sequence`|Incremental
|`time`|Unix
|`version`|Roarr

Example:

  1. ``` json
  2. {
  3.   "context": {
  4.     "application": "task-runner",
  5.     "hostname": "curiosity.local",
  6.     "instanceId": "01BVBK4ZJQ182ZWF6FK4EC8FEY",
  7.     "taskId": 1
  8.   },
  9.   "message": "starting task ID 1",
  10.   "sequence": "0",
  11.   "time": 1506776210000,
  12.   "version": "1.0.0"
  13. }
  14. ```

API


roarr package exports a function with the following API:

  1. ```ts
  2. export type Logger =
  3.   (
  4.     context: MessageContext,
  5.     message: string,
  6.     c?: SprintfArgument,
  7.     d?: SprintfArgument,
  8.     e?: SprintfArgument,
  9.     f?: SprintfArgument,
  10.     g?: SprintfArgument,
  11.     h?: SprintfArgument,
  12.     i?: SprintfArgument,
  13.     k?: SprintfArgument
  14.   ) => void |
  15.   (
  16.     message: string,
  17.     b?: SprintfArgument,
  18.     c?: SprintfArgument,
  19.     d?: SprintfArgument,
  20.     e?: SprintfArgument,
  21.     f?: SprintfArgument,
  22.     g?: SprintfArgument,
  23.     h?: SprintfArgument,
  24.     i?: SprintfArgument,
  25.     k?: SprintfArgument
  26.   ) => void;
  27. ```

To put it into words:

First parameter can be either a string (message) or an object.
  If first parameter is an object (context), the second parameter must be a string (message).
Arguments after the message parameter are used to enable printf message formatting.
  Printf arguments must be of a primitive type (string | number | boolean | null).
  There can be up to 9 printf arguments (or 8 if the first parameter is the context object).

Refer to the Usage documentation for common usage examples.

### adopt

  1. ```ts
  2. <T>(routine: () => Promise<T>, context: MessageContext | TransformMessageFunction<MessageContext>) => Promise<T>,
  3. ```

adopt function uses Node.js [async_context](https://nodejs.org/api/async_context.html) to pass-down context properties.

When using adopt, context properties will be added to all _all_ Roarr messages within the same asynchronous context, e.g.

  1. ```ts
  2. log.adopt(
  3.   () => {
  4.     log('foo 0');

  5.     log.adopt(
  6.       () => {
  7.         log('foo 1');
  8.       },
  9.       {
  10.         baz: 'baz 1',
  11.       },
  12.     );
  13.   },
  14.   {
  15.     bar: 'bar 0',
  16.   },
  17. );
  18. ```

  1. ``` json
  2. {"context":{"bar":"bar 0"},"message":"foo 0","sequence":"0","time":1506776210000,"version":"2.0.0"}
  3. {"context":{"bar":"bar 0","baz":"baz 1"},"message":"foo 1","sequence":"0.0","time":1506776210000,"version":"2.0.0"}
  4. ```

#### sequence value

sequence represents async context hierarchy in [ltree](https://www.postgresql.org/docs/current/ltree.html) format, i.e.

  1. ```xml
  2. <top-level sequential invocation ID>[.<async operation sequential invocation ID>]
  3. ```

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.

  1. ```ts
  2. log.adopt(() => {
  3.   log('foo 0');
  4.   log.adopt(() => {
  5.     log('bar 0');
  6.     log.adopt(() => {
  7.       log('baz 0');
  8.       setTimeout(() => {
  9.         log('baz 1');
  10.       }, 10);
  11.     });
  12.     log('bar 1');
  13.   });
  14. });
  15. ```

  1. ``` json
  2. {"context":{},"message":"foo 0","sequence":"0.0","time":1506776210000,"version":"2.0.0"}
  3. {"context":{},"message":"bar 0","sequence":"0.1.0","time":1506776210000,"version":"2.0.0"}
  4. {"context":{},"message":"baz 0","sequence":"0.1.1.0","time":1506776210000,"version":"2.0.0"}
  5. {"context":{},"message":"bar 1","sequence":"0.1.2","time":1506776210000,"version":"2.0.0"}
  6. {"context":{},"message":"baz 1","sequence":"0.1.1.1","time":1506776210010,"version":"2.0.0"}
  7. ```

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:

1. Accepts an object.
2. Accepts a function.

Object parameter


  1. ```ts
  2. (context: MessageContext): Logger,
  3. ```

Creates a child logger that appends child context to every subsequent message.

Example:

  1. ```ts
  2. import {
  3.   Roarr as log,
  4. } from 'roarr';

  5. const barLog = log.child({
  6.   foo: 'bar'
  7. });

  8. log.debug('foo 1');

  9. barLog.debug('foo 2');
  10. ```

  1. ``` json
  2. {"context":{"logLevel":20},"message":"foo 1","sequence":"0","time":1506776210000,"version":"2.0.0"}
  3. {"context":{"foo":"bar","logLevel":20},"message":"foo 2","sequence":"1","time":1506776210000,"version":"2.0.0"}
  4. ```

Function parameter


  1. ```ts
  2. <T>(context: TransformMessageFunction<MessageContext<T>>): Logger<T>
  3. ```

Creates a child logger that translates every subsequent message.

Example:

  1. ```ts
  2. import {
  3.   Roarr as log,
  4. } from 'roarr';

  5. const barLog = log.child<{error: Error}>((message) => {
  6.   return {
  7.     ...message,
  8.     context: {
  9.       ...message.context,
  10.       ...message.context.error && {
  11.         error: {
  12.           message: message.context.error.message,
  13.         },
  14.       },
  15.     },
  16.   };
  17. });

  18. log.debug('foo 1');

  19. barLog.debug({
  20.   error: new Error('bar'),
  21. }, 'foo 2');
  22. ```

  1. ``` json
  2. {"context":{"logLevel":20},"message":"foo 1","sequence":"0","time":1506776210000,"version":"2.0.0"}
  3. {"context":{"logLevel":20,"error":{"message":"bar"}},"message":"bar 2","sequence":"1","time":1506776210000,"version":"2.0.0"}
  4. ```

A typical use case for this pattern is serialization (e.g. of HTTP request, response or error object) and redaction of sensitive data from logs.

### getContext

Returns the current context.

Example:

  1. ```ts
  2. import {
  3.   Roarr as log,
  4. } from 'roarr';

  5. const childLogger = log.child({
  6.   foo: 'bar'
  7. });

  8. childLogger.getContext();

  9. // {foo: 'bar'}
  10. ```

### trace### debug### info### warn### error### fatal

Convenience methods for logging a message with logLevel context property value set to a numeric value representing the log level, e.g.

  1. ```ts
  2. import {
  3.   Roarr as log,
  4. } from 'roarr';

  5. log.trace('foo');
  6. log.debug('foo');
  7. log.info('foo');
  8. log.warn('foo');
  9. log.error('foo');
  10. log.fatal('foo');
  11. ```

Produces output:

  1. ``` json
  2. {"context":{"logLevel":10},"message":"foo","sequence":"0","time":1506776210000,"version":"2.0.0"}
  3. {"context":{"logLevel":20},"message":"foo","sequence":"1","time":1506776210000,"version":"2.0.0"}
  4. {"context":{"logLevel":30},"message":"foo","sequence":"2","time":1506776210000,"version":"2.0.0"}
  5. {"context":{"logLevel":40},"message":"foo","sequence":"3","time":1506776210000,"version":"2.0.0"}
  6. {"context":{"logLevel":50},"message":"foo","sequence":"4","time":1506776210000,"version":"2.0.0"}
  7. {"context":{"logLevel":60},"message":"foo","sequence":"5","time":1506776210000,"version":"2.0.0"}
  8. ```

### traceOnce### debugOnce### infoOnce### warnOnce### errorOnce### fatalOnce

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).

  1. ```ts
  2. import {
  3.   getLogLevelName,
  4. } from 'roarr';
  5. import type {
  6.   LogLevelName,
  7. } from 'roarr';

  8. getLogLevelName(numericLogLevel: number): LogLevelName;
  9. ```

Middlewares


Roarr logger supports middlewares implemented as [child](#child) message translate functions, e.g.

  1. ```ts
  2. import {
  3.   Roarr as log,
  4. } from 'roarr';
  5. import createSerializeErrorMiddleware from '@roarr/middleware-serialize-error';

  6. const childLog = log.child(createSerializeErrorMiddleware());

  7. const error = new Error('foo');

  8. log.debug({error}, 'bar');
  9. childLog.debug({error}, 'bar');
  10. ```

  1. ``` json
  2. {"context":{"logLevel":20,"error":{}},"message":"bar","sequence":"0","time":1506776210000,"version":"2.0.0"}
  3. {"context":{"logLevel":20,"error":{"name":"Error","message":"foo","stack":"[REDACTED]"}},"message":"bar","sequence":"1","time":1506776210000,"version":"2.0.0"}
  4. ```

Roarr middlewares enable translation of every bit of information that is used to construct a log message.

The following are the official middlewares:

[@roarr/middleware-serialize-error](https://github.com/gajus/roarr-middleware-serialize-error)

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 output demo

CLI program has been moved to a separate package [@roarr/cli](https://github.com/gajus/roarr-cli).

  1. ``` sh
  2. npm install @roarr/cli -g
  3. ```

Explore all CLI commands and options using roarr --help or refer to [@roarr/cli](https://github.com/gajus/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 behaviour.

|Name||Function|Default|
|---|---|---|---|
|`ROARR_LOG`|Boolean|Enables/
|`ROARR_STREAM`|`STDOUT`,

When using ROARR_STREAM=STDERR, use [3>&1 1>&2 2>&3 3>&-](https://stackoverflow.com/a/2381643/368691) 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|Use
|---|---|
|`application`|Name
|`logLevel`|A
|`namespace`|Namespace
|`package`|Name

The roarr pretty-print CLI 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-print CLI program translateslogLevel values to the following human-readable names:

|`logLevel`|Human-readable
|---|---|
|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.

  1. ```ts
  2. /**
  3. * @file Example contents of a Logger.js file.
  4. */

  5. import {
  6.   Roarr,
  7. } from 'roarr';

  8. export const Logger = Roarr.child({
  9.   // .foo property is going to appear only in the logs that are created using
  10.   // the current instance of a Roarr logger.
  11.   foo: 'bar'
  12. });
  13. ```

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:

  1. ```ts
  2. import type {
  3.   MessageEventHandler,
  4. } from 'roarr';

  5. const ROARR = globalThis.ROARR = globalThis.ROARR || {};

  6. const serializeMessage: MessageEventHandler = (message) => {
  7.   return JSON.stringify(message);
  8. };

  9. ROARR.serializeMessage = serializeMessage;
  10. ```

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://www.npmjs.com/package/serialize-error).

  1. ```ts
  2. import {
  3.   Roarr as log,
  4. } from 'roarr';
  5. import serializeError from 'serialize-error';

  6. // [..]

  7. send((error, result) => {
  8.   if (error) {
  9.     log.error({
  10.       error: serializeError(error)
  11.     }, 'message not sent due to a remote error');

  12.     return;
  13.   }

  14.   // [..]
  15. });
  16. ```

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 down in browser. However, overridingROARR.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 overridingROARR.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.

Integrations


Using with Sentry


https://github.com/gajus/roarr-sentry

Using with Fastify


https://github.com/gajus/roarr-fastify

Using with Elasticsearch


If you are using Elasticsearch, you will want to create an index template.

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.

  1. ``` json
  2. {
  3.   "mappings": {
  4.     "log_message": {
  5.       "_source": {
  6.         "enabled": true
  7.       },
  8.       "dynamic": "strict",
  9.       "properties": {
  10.         "context": {
  11.           "dynamic": true,
  12.           "properties": {
  13.             "application": {
  14.               "type": "keyword"
  15.             },
  16.             "hostname": {
  17.               "type": "keyword"
  18.             },
  19.             "instanceId": {
  20.               "type": "keyword"
  21.             },
  22.             "logLevel": {
  23.               "type": "integer"
  24.             },
  25.             "namespace": {
  26.               "type": "text"
  27.             },
  28.             "package": {
  29.               "type": "text"
  30.             }
  31.           }
  32.         },
  33.         "message": {
  34.           "type": "text"
  35.         },
  36.         "time": {
  37.           "format": "epoch_millis",
  38.           "type": "date"
  39.         }
  40.       }
  41.     }
  42.   },
  43.   "template": "logstash-*"
  44. }
  45. ```

Using with Scalyr


If you are using Scalyr, you will want to create a custom parserRoarrLogger:

  1. ```ts
  2. {
  3.   patterns: {
  4.     tsPattern: "\\w{3},\\s\\d{2}\\s\\w{3}\\s\\d{4}\\s[\\d:]+",
  5.     tsPattern_8601: "\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z"
  6.   }
  7.   formats: [
  8.     {format: "${parse=json}$"},
  9.     {format: ".*\"time\":$timestamp=number$,.*"},
  10.     {format: "$timestamp=tsPattern$ GMT $detail$"},
  11.     {format: "$timestamp=tsPattern_8601$ $detail$"}
  12.   ]
  13. }
  14. ```

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.

Documenting use of Roarr


If your package is using Roarr, include instructions in README.md describing how to enable logging, e.g.

  1. ```md
  2. ## Logging

  3. This project uses [`roarr`](https://www.npmjs.com/package/roarr) logger to log the program's state.

  4. Export `ROARR_LOG=true` environment variable to enable log printing to `stdout`.

  5. Use [`roarr-cli`](https://github.com/gajus/roarr-cli) program to pretty-print the logs.
  6. ```

Developing


Every time a change is made to the logger, one must update ROARR_VERSION value in [./src/config.ts](./src/config.ts).

Unfortunately, this process cannot be automated because the version number is not known before semantic-version is called.