Git Product home page Git Product logo

roarr's Introduction

Roarr

NPM version Canonical Code Style Twitter Follow

JSON logger for Node.js and browser.

Motivation

For a long time I have been a big fan of using 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.
  • Decouples transports.
  • Has a CLI program.
  • 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:

import {
  Roarr as log,
} from 'roarr';

log('foo');

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.

ROARR_LOG=true node ./index.js

All logs will be written to stdout.

Browser

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

import {
  ROARR,
} from 'roarr';

ROARR.write = () => {};

The API of the ROARR.write is:

(message: string) => void;

Example implementation:

import {
  ROARR,
} from 'roarr';

ROARR.write = (message) => {
  console.log(JSON.parse(message));
};

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

// Ensure that `globalThis.ROARR` is configured.
const ROARR = globalThis.ROARR = globalThis.ROARR || {};

ROARR.write = (message) => {
  console.log(JSON.parse(message));
};

If your platform does not support globalThis, use globalthis polyfill.

You may also use @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 documentation).

Use @roarr/cli program to filter logs, e.g.

ROARR_LOG=true node ./index.js | roarr --filter 'context.logLevel:>30'

Browser

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

globalThis.ROARR.write = (message) => {
  const payload = JSON.parse(message);

  if (payload.context.logLevel > 30) {
    console.log(payload);
  }
};

Log message format

Property name Contents
context Arbitrary, user-provided structured data. See context property names.
message User-provided message formatted using printf.
sequence Incremental sequence ID (see adopt for description of the format and its meaning).
time Unix timestamp in milliseconds.
version Roarr log message format version.

Example:

{
  "context": {
    "application": "task-runner",
    "hostname": "curiosity.local",
    "instanceId": "01BVBK4ZJQ182ZWF6FK4EC8FEY",
    "taskId": 1
  },
  "message": "starting task ID 1",
  "sequence": "0",
  "time": 1506776210000,
  "version": "1.0.0"
}

API

roarr package exports a function with the following API:

export type Logger =
  (
    context: MessageContext,
    message: string,
    c?: SprintfArgument,
    d?: SprintfArgument,
    e?: SprintfArgument,
    f?: SprintfArgument,
    g?: SprintfArgument,
    h?: SprintfArgument,
    i?: SprintfArgument,
    k?: SprintfArgument
  ) => void |
  (
    message: string,
    b?: SprintfArgument,
    c?: SprintfArgument,
    d?: SprintfArgument,
    e?: SprintfArgument,
    f?: SprintfArgument,
    g?: SprintfArgument,
    h?: SprintfArgument,
    i?: SprintfArgument,
    k?: SprintfArgument
  ) => void;

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

<T>(routine: () => Promise<T>, context: MessageContext | TransformMessageFunction<MessageContext>) => Promise<T>,

adopt function uses Node.js async_context 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.

log.adopt(
  () => {
    log('foo 0');

    log.adopt(
      () => {
        log('foo 1');
      },
      {
        baz: 'baz 1',
      },
    );
  },
  {
    bar: 'bar 0',
  },
);
{"context":{"bar":"bar 0"},"message":"foo 0","sequence":"0","time":1506776210000,"version":"2.0.0"}
{"context":{"bar":"bar 0","baz":"baz 1"},"message":"foo 1","sequence":"0.0","time":1506776210000,"version":"2.0.0"}

sequence value

sequence represents async context hierarchy in ltree format, i.e.

<top-level sequential invocation ID>[.<async operation sequential invocation ID>]

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.

log.adopt(() => {
  log('foo 0');
  log.adopt(() => {
    log('bar 0');
    log.adopt(() => {
      log('baz 0');
      setTimeout(() => {
        log('baz 1');
      }, 10);
    });
    log('bar 1');
  });
});
{"context":{},"message":"foo 0","sequence":"0.0","time":1506776210000,"version":"2.0.0"}
{"context":{},"message":"bar 0","sequence":"0.1.0","time":1506776210000,"version":"2.0.0"}
{"context":{},"message":"baz 0","sequence":"0.1.1.0","time":1506776210000,"version":"2.0.0"}
{"context":{},"message":"bar 1","sequence":"0.1.2","time":1506776210000,"version":"2.0.0"}
{"context":{},"message":"baz 1","sequence":"0.1.1.1","time":1506776210010,"version":"2.0.0"}

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

(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');
{"context":{"logLevel":20},"message":"foo 1","sequence":"0","time":1506776210000,"version":"2.0.0"}
{"context":{"foo":"bar","logLevel":20},"message":"foo 2","sequence":"1","time":1506776210000,"version":"2.0.0"}

Function parameter

<T>(context: TransformMessageFunction<MessageContext<T>>): Logger<T>

Creates a child logger that translates every subsequent message.

Example:

import {
  Roarr as log,
} from 'roarr';

const barLog = log.child<{error: Error}>((message) => {
  return {
    ...message,
    context: {
      ...message.context,
      ...message.context.error && {
        error: {
          message: message.context.error.message,
        },
      },
    },
  };
});

log.debug('foo 1');

barLog.debug({
  error: new Error('bar'),
}, 'foo 2');
{"context":{"logLevel":20},"message":"foo 1","sequence":"0","time":1506776210000,"version":"2.0.0"}
{"context":{"logLevel":20,"error":{"message":"bar"}},"message":"bar 2","sequence":"1","time":1506776210000,"version":"2.0.0"}

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:

import {
  Roarr as log,
} from 'roarr';

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

childLogger.getContext();

// {foo: 'bar'}

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.

import {
  Roarr as log,
} from 'roarr';

log.trace('foo');
log.debug('foo');
log.info('foo');
log.warn('foo');
log.error('foo');
log.fatal('foo');

Produces output:

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

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

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');
{"context":{"logLevel":20,"error":{}},"message":"bar","sequence":"0","time":1506776210000,"version":"2.0.0"}
{"context":{"logLevel":20,"error":{"name":"Error","message":"foo","stack":"[REDACTED]"}},"message":"bar","sequence":"1","time":1506776210000,"version":"2.0.0"}

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

The following are the official middlewares:

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.

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-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 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:

import type {
  MessageSerializer,
} from 'roarr';

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

const serializeMessage: MessageSerializer = (message) => {
  return JSON.stringify(message);
};

ROARR.serializeMessage = serializeMessage;

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.

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.

{
  "mappings": {
    "log_message": {
      "_source": {
        "enabled": true
      },
      "dynamic": "strict",
      "properties": {
        "context": {
          "dynamic": true,
          "properties": {
            "application": {
              "type": "keyword"
            },
            "hostname": {
              "type": "keyword"
            },
            "instanceId": {
              "type": "keyword"
            },
            "logLevel": {
              "type": "integer"
            },
            "namespace": {
              "type": "text"
            },
            "package": {
              "type": "text"
            }
          }
        },
        "message": {
          "type": "text"
        },
        "time": {
          "format": "epoch_millis",
          "type": "date"
        }
      }
    }
  },
  "template": "logstash-*"
}

Using with Scalyr

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

{
  patterns: {
    tsPattern: "\\w{3},\\s\\d{2}\\s\\w{3}\\s\\d{4}\\s[\\d:]+",
    tsPattern_8601: "\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z"
  }
  formats: [
    {format: "${parse=json}$"},
    {format: ".*\"time\":$timestamp=number$,.*"},
    {format: "$timestamp=tsPattern$ GMT $detail$"},
    {format: "$timestamp=tsPattern_8601$ $detail$"}
  ]
}

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:

import { RoarrLoggerService } from nestjs-logger-roarr';
import { AppModule } from "app.module";

const logger = RoarrLoggerService.sharedInstance();
const app = await NestFactory.create(AppModule, { logger });

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.

## Logging

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

{"a":"a","b":"b","c":"c","d":"d","e":"e","f":"f","g":"g","h":"h","i":"i","j":"j","...":"1 item not stringified"}

The reason for this is to prevent accidental logging of massive objects that can cause context truncation and performance issues.

Developing

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

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

roarr's People

Contributors

0xflotus avatar gajus avatar gitschwifty avatar kikobeats avatar mrhyde avatar psychedelicious avatar rafi993 avatar rondinif avatar t3hmrman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

roarr's Issues

application name not prepended to logs

Found another one (this time on 2.3.0). So I have a file in my project that looks exactly like this:

const roarr = require('roarr').default;

global.ROARR.prepend = {
  ...global.ROARR.prepend,
  application: 'test-app',
};

module.exports = settings => roarr.child(settings);

And then I require that file everywhere where needed and create a child with additional property namespace. Like this:

const loggerFactory = require('./logger-factory');
const logger = loggerFactory({ namespace: 'test-namespace' });
logger.info('lorem ipsum');

On 2.0.2 it worked perfectly I had application name prepended to every log and namespace accrodingly. Unfortunately on 2.3.0 it does not work, roarr does not add application property to context.

I did look through readme this time before posting an issue but didn't find any related information about this.

Slonik pollutes console log with "async_hooks are unavailable; Roarr.child will not function as expected"

I use a custom log format in my application when I log to console. Slonik, upon starting up, prints async_hooks are unavailable; Roarr.child will not function as expected. Is there any way to disable polluting my console logs with this message? This is really inconvenient while running tests or passing the logs to a log parser.

PS. I have not enabled roarr logging.

Expected Behavior

Slonik must not log to console without the user explicitly enabling some kind of logging.

Current Behavior

Slonik writes async_hooks are unavailable; Roarr.child will not function as expected to console on start

Possible Solution

If async_hooks is a required package for roarr then it must be included as a dependency or a peer dependency. Or print this message only if roarr logging is enabled.

Steps to Reproduce

  1. npm i slonik
  2. Import slonik into your application
  3. Run your application

Cannot read property 'split' of undefined

Error trace

TypeError: Cannot read property 'split' of undefined
    at Object.cmp [as default] (/usr/src/app/node_modules/semver-compare/index.js:5:16)
    at Object.exports.default (/usr/src/app/node_modules/roarr/dist/cjs/src/factories/createRoarrInitialGlobalState.js:15:80)
    at Object.<anonymous> (/usr/src/app/node_modules/roarr/dist/cjs/src/log.js:35:46)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at Module.Hook._require.Module.require (/home/blessuser/.npm/_npx/5f7878ce38f1eb13/node_modules/require-in-the-middle/index.js:80:39)
    at require (node:internal/modules/cjs/helpers:92:18)

It's happening at this code point

https://github.com/gajus/roarr/blob/master/src/factories/createRoarrInitialGlobalState.ts#L12

I debugged that on my side. The thing happening is versions is an array of 1 element:

const versions = (currentState.versions || []).concat();
// => versions is [ '2.15.4' ]

so the sort fn

versions.sort(cmp);

is receiving

{ a: undefined, b: '2.15.4' }

so the semver-compare receives something non expected (it expects an string):

https://github.com/substack/semver-compare/blob/master/index.js#L2

Add new env variable to ROARR

It would be nice, if we can add some options to ROARR with env.

exemple is better than word :

ROARR_USE_COLORS=true
ROARR_OUTPUT_FORMAT=pretty

I have one use case, when I make unit testing with my IDE,
I don't find the way to put extra parameters.

I use web storm with JEST

Newest version does not log anything

So I have two projects. I introduced roarr to the first one some time ago when the newest version available was 2.0.2 and everything works smoothly there. Today I wanted to introduce it to the other application and currently the newest release is 2.2.0. There's no difference in logger-related code in both applications and roarr in version 2.2.0 does not log anything. Here's the snipper from entrypoint to the app:

process.env.ROARR_LOG = true;
const roarr = require('roarr');
const logger = roarr.default;
logger('test-one');
logger.child({test:true}).info('test-two');

WIth 2.0.2 no problems, I get the following output:

{"context":{},"message":"test-one","sequence":0,"time":1526456311629,"version":"1.0.0"}
{"context":{"test":true,"logLevel":30},"message":"test-two","sequence":1,"time":1526456311631,"version":"1.0.0"}

With 2.2.0 I get nothing.

Rotating files?

How can I rotate files with roarr?

I couldn't find infomation about this in the docs on Github, do you recommend something to workaround this?

Rotating files is something useful too and that's the only thing that I couldn't find here, the rest is a good logger as far I can see.

thanks.

Logging message together with error object

Hi! I'm using roarr in a project and I think it's great.

I have a question, if I want to log an error message together with a message, how would you do it?

Example: I'm trying to send an email and it returns an error.

mailer.send(email, error => {
  if (error) {
    logger.error('Error sending email'); // here I want log the serialized error too
  }
});

Changing `ROARR_LOG` at runtime has no effect

Example index.mjs (please ignore the gymnastics to run it under Node 13.5.0):

process.env.ROARR_LOG = undefined;

import log from "roarr";

log.default("This should be hidden");

process.env.ROARR_LOG = "true";

log.default("This should be shown");

Running it (Windows):

λ set ROARR_LOG=true

λ node index.mjs
(node:6088) ExperimentalWarning: The ESM module loader is experimental.
{"context":{},"message":"This should be hidden","sequence":0,"time":1577971598534,"version":"1.0.0"}
{"context":{},"message":"This should be shown","sequence":1,"time":1577971598535,"version":"1.0.0"}

λ set ROARR_LOG=

λ node index.mjs
(node:7116) ExperimentalWarning: The ESM module loader is experimental.

This behaviour is because the decision to log or not to log is made the first time the module is loaded:

roarr/src/log.js

Lines 20 to 27 in 5f856d9

if (environmentIsNode) {
// eslint-disable-next-line no-process-env
const enabled = boolean(process.env.ROARR_LOG || '');
if (!enabled) {
logFactory = createMockLogger;
}
}

Defining ROARR_LOG in a .env file then fails, because roarr will be loaded before that file is ever read and parsed. I think this is the correct behaviour in and of itself; I would just suggest exporting createLogger and createMockLogger so that something like this works:

import { processDotEnvFile } from "my-dotenv-module";
import { createLogger, createMockLogger } from "roarr";

/* … */

const someFile = getFileNameFromUser();
processDotEnvFile(someFile);
const LOGGER = (process.env.SHOULD_LOG) ? createLogger() : createMockLogger();

Error when using Roarr version > 4 with Node 16

I just started a new project with create-react-app, added Roarr, and configured it according to the readme (https://github.com/gajus/roarr#roarr-usage). When I ran npm start, I got a "Failed to compile" error.

The error was: "Can't resolve 'async_hooks'" in:
https://github.com/gajus/roarr/blob/master/src/factories/createRoarrInitialGlobalState.ts#L34

This error happens if I use Roarr versions 5.0.0, 6.0.0, and 7.0.0. Version 4.2.5 works fine.

Environment:
node: 16.4.2
npm: 7.19.1
macOS: 11.4

Use numbers instead of strings to represent log levels

I believe that, like other loggers available out there, Roarr should represent log level internally as number to ease filtering using jq or building queries on log storage/search engines.

Imagine I want to log all levels, except by trace. Then I'd have to have:

jq 'select(.context.logLevel == "debug" or .context.logLevel == "info" or .context.logLevel == "warn" or .context.logLevel == "error" or .context.logLevel == "fatal")'

If Roarr were to attribute a numeric value to all levels, like:

  • silly: 10
  • debug: 20
  • info: 30
  • warn: 40
  • error: 50
  • fatal: 60

Then that jq expression would be reduced to:

jq 'select(.context.logLevel > 10)'

Makes sense?

Roarr drop error?

sometimes, I have the feeling that roarr drop some error.

console.log("e:",error) give me that :

Is it because the errorMessage is inside stack?

On typing error by example:

e: TypeError: Cannot read property 'oneFirst' of undefined at ... [stack]

and with roarr

log.error({e: e}, "ERROR IN getLanguageConfigDB : ");
[DATE] ERROR (50) (@getLanguageConfigDB) (#TzHiSKm0CaA6M7UVAAAA): ERROR IN getLanguageConfigDB : 
e: (empty YAML)

There is no details, did I something wrong?

there is a bug?

Missing export default

With Node 9.3 doing

import log from 'roarr';
log('foo')

results in TypeError: log is not a function. I think it's because roarr is missing the default export:

console.log(log)

outputs

{ default: 
   { [Function: log]
     child: [Function],
     debug: [Function],
     error: [Function],
     fatal: [Function],
     info: [Function],
     trace: [Function],
     warn: [Function] } }

What would be the best way to integrate Datadog APM tracing?

According to:

https://docs.datadoghq.com/tracing/connect_logs_and_traces/nodejs/

To enable this feature, I'd have to wrap the record that writes out with the following:

        const span = tracer.scope().active();
        const time = new Date().toISOString();
        const record = { time, level, message };

        if (span) {
            tracer.inject(span.context(), formats.LOG, record);
        }

Based on reading the roarr docs, it seems I'd want to inject this in the child logger function / create middleware?

Please add `license` field to package.json

Though I confirmed that there has been the LICENSE file (#15), npm site doesn't recognize content of LICENSE file and displays license field of package.json so that it displays that roarr has no license .

https://www.npmjs.com/package/roarr

Also, license checkers like js-green-licenses use license field of package.json so that they point roarr has no license.

As a result, I need to do some bureaucratic works to use this great library.

Adding license field to roarr’s package.json reduces such extra works and it makes easier to recommend using roarr to others.

So please add license field to package.json.

Troubles with new import method in the browser

I've been using/loving roarr for quite a while using versions up to and including 4.x.

After upgrading to 7.0.1, I can't get the example code to work:

For example, this is how I'm importing into my vue-cli webpack 4 project:

import { Roarr as log } from "roarr";

const Logger = log.child({
  application: "webapp",
  version: process.env.VERSION,
});

At run time I get:

Uncaught TypeError: roarr__WEBPACK_IMPORTED_MODULE_2__.Roarr is undefined

And of course log ends up undefined. Ideas? Thanks!

version 7.1.0 started giving compile errors

I was logging with the following format:

import { Roarr as log } from 'roarr';

try {
 doSomething();
} catch (err) {
  log.error({err}, "Something failed");
}

I did not update anything and this use to work, I am guessing a new patch version came out that changed the compile behavior making this no longer valid.

package.json looks like this:

"roarr": "^7.1.0",

Was this intentional? It seems odd to have a breaking change like this on a patch version?

/var/runtime/app/node_modules/ts-node/src/index.ts:750
    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/middleware/index.ts(49,9): error TS2769: No overload matches this call.
  Overload 1 of 2, '(context: { [x: string]: JsonValue<{}> | undefined; }, message: string, c?: SprintfArgument | undefined, d?: SprintfArgument | undefined, e?: SprintfArgument | undefined, f?: SprintfArgument | undefined, g?: SprintfArgument | undefined, h?: SprintfArgument | undefined, i?: SprintfArgument | undefined, j?: SprintfArgument | undefined): void', gave the following error.
    Type 'unknown' is not assignable to type 'JsonValue<{}> | undefined'.
      Type 'unknown' is not assignable to type '{ [x: string]: JsonValue<{}> | undefined; }'.
  Overload 2 of 2, '(message: string, b?: SprintfArgument | undefined, c?: SprintfArgument | undefined, d?: SprintfArgument | undefined, e?: SprintfArgument | undefined, f?: SprintfArgument | undefined, g?: SprintfArgument | undefined, h?: SprintfArgument | undefined, i?: SprintfArgument | undefined, j?: SprintfArgument | undefined): void', gave the following error.
    Argument of type '{ error: unknown; }' is not assignable to parameter of type 'string'.

    at createTSError (/var/runtime/app/node_modules/ts-node/src/index.ts:750:12)
    at reportTSError (/var/runtime/app/node_modules/ts-node/src/index.ts:754:19)
    at getOutput (/var/runtime/app/node_modules/ts-node/src/index.ts:941:36)
    at Object.compile (/var/runtime/app/node_modules/ts-node/src/index.ts:1243:30)
    at Module.m._compile (/var/runtime/app/node_modules/ts-node/src/index.ts:1370:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/var/runtime/app/node_modules/ts-node/src/index.ts:1374:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/var/runtime/app/src/server.ts:45:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module.m._compile (/var/runtime/app/node_modules/ts-node/src/index.ts:1371:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/var/runtime/app/node_modules/ts-node/src/index.ts:1374:12) {
  diagnosticText: 'src/middleware/index.ts(49,9): error TS2769: No overload matches this call.\n' +
    "  Overload 1 of 2, '(context: { [x: string]: JsonValue<{}> | undefined; }, message: string, c?: SprintfArgument | undefined, d?: SprintfArgument | undefined, e?: SprintfArgument | undefined, f?: SprintfArgument | undefined, g?: SprintfArgument | undefined, h?: SprintfArgument | undefined, i?: SprintfArgument | undefined, j?: SprintfArgument | undefined): void', gave the following error.\n" +
    "    Type 'unknown' is not assignable to type 'JsonValue<{}> | undefined'.\n" +
    "      Type 'unknown' is not assignable to type '{ [x: string]: JsonValue<{}> | undefined; }'.\n" +
    "  Overload 2 of 2, '(message: string, b?: SprintfArgument | undefined, c?: SprintfArgument | undefined, d?: SprintfArgument | undefined, e?: SprintfArgument | undefined, f?: SprintfArgument | undefined, g?: SprintfArgument | undefined, h?: SprintfArgument | undefined, i?: SprintfArgument | undefined, j?: SprintfArgument | undefined): void', gave the following error.\n" +
    "    Argument of type '{ error: unknown; }' is not assignable to parameter of type 'string'.\n"

Add ability to define instance context formatters

One of the patterns that I constantly repeat is using serialize-error to serialize errors before logging them in the context.

import serializeError from 'serialize-error';
import Roarr from 'roarr';

const log = Roarr
  .child({
    package: '@applaudience/data-management-program'
  });

const someError = new Error();

log.error({
  error: serializeError(someError)
}, 'some error has occurred');

What would be useful if I could define Logger instance specific formatters of the context, e.g.

import serializeError from 'serialize-error';
import Roarr from 'roarr';

const log = Roarr
  .child({
    package: '@applaudience/data-management-program'
  })
  .formatMessage((context, message, ...args) => {
    let newContext = context;

    if (newContext.error) {
      newContext = {
        ...newContext,
        error: serializeError(newContext.error)
      };
    }

    return [
      newContext,
      message,
      ...args
    ];
  });

const someError = new Error();

log.error({
  error: someError
}, 'some error has occurred');

Chained namespace

Now:

import roarr from 'roarr'

const log1 = roarr.child({ namespace: 'parent' })
const log2 = log1.child({ namespace: 'first_child' })

log2 will only have namespace: 'first_child'

My expectation: namespace: 'parent:first_child'

Improve message filtering

To filter logs currently it is necessary to parse the messages that it passed to ROARR.write in JSON format, resulting in a potentially CPU-intensive filtering logic.

My proposal is to pass unserialized message as second parameter to ROARR.write to avoid JSON parsing for each log message.

Context: gajus/slonik#277

Including sequence reset capability or local sequence capability

I'm currently using Roarr for a node.js API server. I find the inclusion of a sequence number to be useful, but I was hoping that I can use it to see the sequence of events in a single API call. So for example if Request A comes I might see 4 events with sequence 1, 2, 3 and 4. The next Request B that comes will have 3 events with sequence 1, 2 and 3 occur

However, currently I notice that the sequence always increments across different API requests (and likely between API requests). This causes Request B in the above example to start with sequence = 5 and increments to sequence = 7. I did notice that Roarr makes use of a global sequence variable that increments every time a log call is made so I understand why this is happening.

I was wondering what are your thoughts on providing a capability to either use a locally specified sequence, or reset the sequence so that it would be possible to use the sequence to show the sequence of events for a particular action

Adding namespace to the context

@gajus In the README conventions suggestions you mentioned 'namespace'. How would you go about and add namespace as another context property?
Should i instanciate a new log child with the name of the file/module/class?

What I want is to log the file and the line of code which produces the log. Is there any recommended way to do so?

Logs written with AsyncLocalStorage are not written to stdout when running on k8s pods

Hey! Glad I found this library. I enjoy it and have been using it for a while for some pet projects.

Lately, I've been trying to use roarr to write logs to the stdout stream, which are later collected by fluentd and written to our Elastic.

When locally running a Nodejs express api that uses roarr (we create a log child for each log level and add some different context properties depending on the log level) the logs get printed to the console. However, when deploying that api to a k8s cluster, the logs do not appear on the pod logs, and as a result are not collected by fluentd.

I took some time to try and investigate whether or not any of this has to do with AsyncLocalStorage. I thought it might run in a slightly different context and might point to a different stdout, and so forgive my ignorance as this is only an assumption and I haven't used this Node API before.

When downgrading to the last stable version before AsyncLocalStorage, the issue is not reproduced and logs are successfully written (that is, version 4.2.5).

Could you please help shed some light on where you thing this issue resides? I'd be happy to jump in and open a PR to fix this but I do not know for sure that it in fact happens due to the use of this Node API.

Thanks! (feel free to change the issue title as this is an assumption)

Printing maps to logger output

I am currently using Node 9.5.0.
Unfortunately it seems that i can't print Maps with this logger.

let map: Map<string, number[]> = new Map();
map.set("some key", [1,2,3]);
map.set("another key", [1]);
map.set("the third key", [3]);
log.debug({map: map, keys: map.keys(), values: map.values()}, " theres no output here");

however, with console.log(map); i can print all of its content.

Why "Roarr"?

Maybe this is a stupid question, but I think that somewhere at the start of Readme it should be explained

Add async sequence ID

Related to this issue: #43

Premise

It may be desired to track sequence in which events are taking place, e.g.

const request = (url) => {
  log('foo %s', url);

  setTimeout(() => {
    log('bar %s', url);
  }, Math.random());
};

Promise.all([
  request('https://a'),
  request('https://b'),
]);

This requirement is already achieved using sequence:

{"time":1,"sequence":1,"message":"foo https://a"}
{"time":1,"sequence":2,"message":"foo https://b"}
{"time":1,"sequence":3,"message":"bar https://b"}
{"time":1,"sequence":4,"message":"bar https://a"}

As a reminder, the current use case for sequence is to allow sorting of sub-millisecond events (where time alone cannot be used to distinguish event order).

Problem

However, in the above example, other than by analyzing message values, it is not possible to tell how 3rd and 4th log entries relate to 1st and 2nd.

Solution

This problem could be solved by changing "sequence" field to include the ID of the parent sequence that was used to generate the logs, e.g.

{"time":1,"sequence":"1","message":"foo https://a"}
{"time":1,"sequence":"2","message":"foo https://b"}
{"time":1,"sequence":"2.1","message":"bar https://b"}
{"time":1,"sequence":"1.1","message":"bar https://a"}

This format allows to continue using sequence for sorting sub-millisecond events, but it also adds ability to identify the origin of the events.

Discussion

This is the first (breaking or any) change to the log format since the release of Roarr.

  • Is this a valuable addition?
  • Is there a better way to implement the desired functionality?

printf message formatting broken

I have just upgraded the version of roarr logger from 2.15.4 to 3.2.0 within a Node 12.19.0 application.

I make use of printf message formatting extensively throughout the application. With v2.15.4, I had not encountered any issues with this. For example:

log.debug('Processing feed [%s] for %d agents', feedId, agentCount)

would work perfectly and output something like this:

Processing feed [abc123] for 25 agents

With roarr v3.2.0, however, the output is this:

Processing feed [abc123] for %d agents

In fact, the behaviour I am observing is that all substitution variables apart from the first one seem to be completely ignored.

To resolve the issue, I reverted to roarr v2.15.4.

node 10 required

Looks like the 1.0.0 release updated the boolean package which requires Node 10 or above (since it uses regex capture groups).

I was wondering if you would consider locking the version of that package in order for roarr to support older versions of node.

Happy to contribute if you have a recommended path forward for roarr.

This is the error I'm getting on node 8.16.1

{path}/node_modules/roarr/node_modules/boolean/build/lib/boolean.js:5
        return /^(?<truthy>true|t|yes|y|on|1)$/iu.test(value.trim());
        ^

SyntaxError: Invalid regular expression: /^(?<truthy>true|t|yes|y|on|1)$/: Invalid group
    at boolean (/{path}/node_modules/roarr/node_modules/boolean/build/lib/boolean.js:5:9)
    at Object.<anonymous> (/{path}/node_modules/roarr/dist/log.js:24:38)

Having a hard time understanding the motivation behind having no control over the log-level

I like a lot of things about this logger, but I'm struggling to understand why there's no control for the log-level anywhere, why isn't that another environment variable?

if I want to use TRACE a lot when developing but don't want production to trace anything unless somehow told to, is there no way of controlling that besides using an external json filterer?

jq is another dependency to bring in - is the official suggestion to use jq in production? or find a "transport" that can do the filtering?

Thanks

Browser usage

Hello! I read your Medium post and this package seems to be exactly what I'm looking for :)

You mentioned it can be used in the browser as well, could you share an example of how this would work?
Since process.stdout isn't available in browser environments, I'm not sure where the logs would be sent.

I'd imagine they'd be sent to some logging server while being visible to some degree in the browser console as well. Unfortunately, the browser console doesn't really provide a way to filter the logs like you would be able to with node and jq. Perhaps this part could be handled by a browser extension?

pretty print crashes when there is no log level

My code:

const log = require('roarr').default

log('foo')

If I run:

node index.js

it works just fine:

{"context":{},"message":"foo","sequence":0,"time":1507231220906,"version":"1.0.0"}

However, if I run

node index.js | $(npm bin)/roarr pretty-print

I get the following error:

    var logLevel = message.context.logLevel.toUpperCase();
                                           ^
TypeError: Cannot read property 'toUpperCase' of undefined
    at DestroyableTransform.mapper (/home/henrique/labs/roarr-test/node_modules/roarr/dist/bin/commands/pretty-print.js:52:44)
    at DestroyableTransform.transform [as _transform] (/home/henrique/labs/roarr-test/node_modules/split2/index.js:33:21)
    at DestroyableTransform.Transform._read (/home/henrique/labs/roarr-test/node_modules/readable-stream/lib/_stream_transform.js:182:10)
    at DestroyableTransform.Transform._write (/home/henrique/labs/roarr-test/node_modules/readable-stream/lib/_stream_transform.js:170:83)
    at doWrite (/home/henrique/labs/roarr-test/node_modules/readable-stream/lib/_stream_writable.js:406:64)
    at writeOrBuffer (/home/henrique/labs/roarr-test/node_modules/readable-stream/lib/_stream_writable.js:395:5)
    at DestroyableTransform.Writable.write (/home/henrique/labs/roarr-test/node_modules/readable-stream/lib/_stream_writable.js:322:11)
    at Socket.ondata (_stream_readable.js:555:20)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)

Consider simplifying log function interface

There is no real difference between:

log.info({time: 1}, 'foo');

and

log.child({time: 1}).info('foo');

If we dropper the former API interface, it would make it easier to avoid mistakes such as attempting to pass context as printf parameters.

Great suggestion by @mikeroelens.

The only concern here is that it is a major breaking change with no easy way to add backwards compatibility. I doubt it will be implemented due to the latter reason, but worth considering how we could promote this pattern more.

Why is it bad to instantiate a logger?

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'm looking for a logger for one of my apps and I stumbled upon Roarr. Looks pretty good. The only question I have is, why is it bad to instantiate a logger at the application level?

And when you say instantiate you mean "new Logger()"? if you could expand more on this point I would appreciate it.

Thanks.

Missing license

Hi! I found this logger via your Medium post. This is great and thank you for the project.

However it doesn't seem to have a license. Are you planning to add one?

Cannot re-assign log level using transformer

Our logs are picked up via the DataDog agent, and with the way the processing pipelines are set up (I don't have control over this), the log level is picked up by reading a level property at the object root.

I've attempted to insert one, but it seems anything that isn't message or context gets dropped:

  const barLog = log.child((message) => {
    return {
      message: 'test',
      context: { test: 'test123' },
      level: 'ERROR',
    };
  });

outputs

{"context":{"test":"test123"},"message":"test"}

Add a utility to identify Roarr location

I start pretty much every file with a variation of:

import Logger from '../Logger';

const log = Logger.child({
  namespace: 'createUpstreamHttpClientConfiguration',
});

namespace is most of the time the name of the file.

I am wondering if we could provide a utility to automate this, e.g.

import log from 'roarr.macro';

that would transpile to a version above.

Logger file is usually simply used to add the package name to the context. That could be pulled from package.json or we could resolve location of the Logger.js file to always use as a base.

Warn if Roarr is used without blocking stdout/ stderr

// Make writing to stdout/ stderr blocking.
// Without this, we are risking of loosing logs when program crashes.
// @see https://github.com/nodejs/node/issues/6379
if (process.stdout._handle) {
  process.stdout._handle.setBlocking(true);
}

if (process.stderr._handle) {
  process.stderr._handle.setBlocking(true);
}

Agree upon a common JSON format with other structured logging frameworks

Hi! I've recently become more interested in structured logging, and have looked into a few structured logging libraries.

You get amazing power when you dump the logs from all of your different systems and sources into a centralized log store, and can then view and analyze them as one whole.

What I've noticed though is that the various structured logging frameworks all save JSON log entries in similar, but slightly different schemas.

For example, for storing timestamps, this library uses the JSON key "time", while other libraries use "timestamp" or "at". Another area where libraries differ is in how they store log levels.

These small differences cause friction when analyzing the central logstore, which contains structured logs that have been collected from multiple systems/microservices.

For example, one service might tag warnings with the string "WARN" while another with the string "warning". So if I want to view only warnings, I need to take this difference into account and write a tricky "OR" filter expression. This may seem minor, but these small inconsistencies cause great pain.

I believe that these small differences between the various structured logging libraries exist not because of any strongly held opinions, but simply because mainstream structured and centralized logging is still relatively young, and so there is no standard or common consensus.

I think it would be very beneficial to everyone if we could all unite around a common format.

To get things started, I have created a GitHub repository to centralize discussions here: https://github.com/bitc/structured-logging-schema

It contains a comparison between several structured logging libraries, summarizing the differences between them all. This can hopefully be a start to help us arrive at common ground.

I encourage the authors of this library (and anyone else who has an opinion) to participate in the discussion!

Discussion takes place in the issues for this repo: https://github.com/bitc/structured-logging-schema

Unexpected `[sprintf] unexpected placeholder` in simple logging (single param) strings contains a '%'

code that reproduce the issue

    console.log("[[[");
    try {
        console.log(JSON.stringify(sparqlQueryScientificName.results));
        console.log("===");
        log.trace('%s', JSON.stringify(sparqlQueryScientificName.results));
    } catch(errorLogging) {
        log.error(errorLogging.message);
    }
    console.log("]]]");

actual

    [[[
    {"bindings":[{"scientificname":{"type":"literal","value":"Cucumis anguria"},"taxonrank":{"type":"uri","value":"http://www.wikidata.org/entity/Q7432"},"image":{"type":"uri","value":"http://commons.wikimedia.org/wiki/Special:FilePath/Cucumis%20anguria.JPG"},"taxonrankLabel":{"xml:lang":"en","type":"literal","value":"species"}}]}
    ===
    {"context":{"logLevel":50},"message":"[sprintf] unexpected placeholder","sequence":31,"time":1556820461648,"version":"1.0.0"}
    ]]]

expected

    [[[ 
    {"bindings":[{"scientificname":{"type":"literal","value":"Cucumis anguria"},"taxonrank":{"type":"uri","value":"http://www.wikidata.org/entity/Q7432"},"image":{"type":"uri","value":"http://commons.wikimedia.org/wiki/Special:FilePath/Cucumis%20anguria.JPG"},"taxonrankLabel":{"xml:lang":"en","type":"literal","value":"species"}}]}
    ===
    {"context":{"logLevel":10},"message":"{\"bindings\":[{\"scientificname\":{\"type\":\"literal\",\"value\":\"Cucumis anguria\"},\"taxonrank\":{\"type\":\"uri\",\"value\":\"http://www.wikidata.org/entity/Q7432\"},\"image\":{\"type\":\"uri\",\"value\":\"http://commons.wikimedia.org/wiki/Special:FilePath/Cucumis%20anguria.JPG\"},\"taxonrankLabel\":{\"xml:lang\":\"en\",\"type\":\"literal\",\"value\":\"species\"}}]}","sequence":33,"time":1556821362583,"version":"1.0.0"}
    ]]]

JsonObject<T> -- Index signature for type 'string' is missing in type

When attempting to use a serializable class instance in the context of a log method, a typescript error is generated stating that the key signatures are incompatible.

For example, given the following code:

class TestSerializableClass {
  public constructor (public someKey: string) {}
}

log.info({
  obj: new TestSerializableClass('someValue'), // Error!
}, 'any message');

The following error is generated:

No overload matches this call.
  Overload 1 of 2, '(context: { [x: string]: JsonValue<{}> | undefined; }, message: string, c?: SprintfArgument | undefined, d?: SprintfArgument | undefined, e?: SprintfArgument | undefined, f?: SprintfArgument | undefined, g?: SprintfArgument | undefined, h?: SprintfArgument | undefined, i?: SprintfArgument | undefined, j?: SprintfArgument | undefined): void', gave the following error.
    Type 'TestSerializableClass' is not assignable to type 'JsonValue<{}> | undefined'.
      Type 'TestSerializableClass' is not assignable to type '{ [x: string]: JsonValue<{}> | undefined; }'.
        Index signature for type 'string' is missing in type 'TestSerializableClass'.
  Overload 2 of 2, '(message: string, b?: SprintfArgument | undefined, c?: SprintfArgument | undefined, d?: SprintfArgument | undefined, e?: SprintfArgument | undefined, f?: SprintfArgument | undefined, g?: SprintfArgument | undefined, h?: SprintfArgument | undefined, i?: SprintfArgument | undefined, j?: SprintfArgument | undefined): void', gave the following error.
    Argument of type '{ obj: TestSerializableClass; }' is not assignable to parameter of type 'string'.ts(2769)
[types.ts(5, 38): ]()The expected type comes from property 'obj' which is declared here on type '{ [x: string]: JsonValue<{}> | undefined; }'

This seems to be because the JsonObject<T> type is defined as T & { [Key in string]?: JsonValue<T> }, which typescript interprets as "any key of type string must be assignable with JsonValue<T>".

In reality, I believe that roarr doesn't need to assign anything to the object; it just requires that every existing key falls within a set of serializable types.

This can be fixed by redefining JsonObject<T> as T & { [Key in string & keyof T]?: JsonValue<T> }, but that causes instances of Error to also be allowed through, which leads to several tests failing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.