Skip to content

By-Nordenfelt-AB/log4njs

Repository files navigation

log4njs

log4njs is a very simple log utility for nodejs & typescript.

npm version Build Status

Installation

npm i log4njs --save

Migration to 3.0.0

See CHANGELOG for breaking changes.

Default usage

import { getLogger } from 'log4njs';
const log = getLogger();
$ log.info('Hello world', { foo: 'bar' });
> '[INFO] Hello world' { foo: 'bar' }

API

Settings

  • level: enum LogLevel. The log level of the logger instance. Defaults to INFO (300).
  • prefix: String. An optional string that is prefixed to all log messages. Note that no spacing is not automatically added and must be included in the prefix string if required. Defaults to ''.
  • timestamp: Boolean. Indicate if the log messages should include the current timestamp (YYYY-MM-DDTHH:mm:ss:mmmZ). Defaults to false.
  • callerInfo: Boolean. Best effort attempt to include caller filename & line number in the log entries. Defaults to false.
    • Note: callerInfo has a fairly big performance impact and is not suitable for regular production use.
  • hideLogLevel: Boolean. Will not output the log level as part of the message if set to true. Default to false.

Example

import { getLogger, LogLevel } from 'log4njs';
const log = getLogger({ level: LogLevel.DEBUG, prefix: 'MyPrefix::', timstamp: true });

Using environment variables:

  • level: LOG_LEVEL=ERROR
  • prefix: LOG_PREFIX=MyPrefix::
  • timestamp: LOG_TIMESTAMP=true
  • callerInfo: LOG_CALLERINFO=true
  • hideLogLevel: LOG_HIDE_LOG_LEVEL=true

Modify settings runtime

Settings can be modified after the logger has been created:

const log = getLogger({ timstamp: true });
log.info('Foo');
log.getSettings().timestamp = false;
log.info('Bar');
log.getSettings().timestamp = true;
log.info('Baz');

> [INFO] 2024-01-14T13:35:08.683Z Foo
> [INFO] Bar
> [INFO] 2024-01-14T13:35:40.637Z Baz

Suppress logs

In unit tests, for example, you may want to suppress all log statements:

$ LOG_LEVEL=suppress npm test

Audit Logging

There are two Audit log level, introduced in 2.1.0.: AUDIT & AUDIT_ALERT. They can only be turned off by suppressing all logs.

Audit logging is typically sensitive and important but monitored separate from error logs which is why these two new log levels were introduced.

Log levels

Each log level corresponds to a valid configuration value.

$ log.trace(message[, attachment]);
> [TRACE] ...

$ log.debug(message[, attachment]);
> [DEBUG] ... 

$ log.info(message[, attachment]);
> [INFO] ...

$ log.warning(message[, attachment]);
> [WARNING] ...

$ log.error(message[, attachment]);
> [ERROR] ...

$ log.critical(message[, attachment]);
> [CRITICAL] ...

$ log.audit(message[, attachment]);
> [AUDIT] ...

$ log.auditAlert(message[, attachment]);
> [AUDIT_ALERT] ...

Masking data

To ensure that certain values are not printed to the log you can mask data.
Note: It is important to clear the masks after you are done, or it may cause a memory leak over time.
Note: Masks are case-sensitive. The exact string provided will be masked, nothing else.

let data = { id: 12, secret: 'abc123' };
try {
    log.addMask(data.secret);
    log.info('My masked log', data);
    > '[INFO] My masked log' { id: 12, secret: '***' }
} finally {
    log.clearMasks();
    log.info('My masked log', data);
    > '[INFO] My masked log' { id: 12, secret: 'abc123' }
}

You can optionally set a custom placeholder

let data = { id: 12, secret: 'abc123' };
log.addMask(data.secret, 'placeholder');
log.info('My masked log', data);
> '[INFO] My masked log' { id: 12, secret: 'placeholder' }

Benchmarks

There are a couple of sample scripts provided to highlight the performance impact of various configurations.
All benchmarks run 10000 iterations.

Before running the benchmarks, run:

cd resources/benchmarks
npm i

Default usage

Default logging with or without a simple attachment:

Sample, with attachment:

node default-use.js true
> default benchmark: true: 141.929ms

Sample, without attachment:

node default-use.js
> default benchmark: false: 133.035ms

isDebugEnabled

Debug logging is usually disabled in production.
Log4njs provides the option to do a pre-check when debug logging to increase performance when debug logging is turned off.
Note that this does take a slight performance hit when debug logging is turned on.

Sample, with check enabled:

node check-debug.js true
> isDebugEnabled benchmark: true: 0.604ms

Sample, with check disabled:

node check-debug.js
> isDebugEnabled benchmark: false: 0.91ms

callerInfo

The callerInfo setting will attempt to extract the filename & line number of the caller.
This provides useful information when it is difficult to pinpoint the source of a specific logger call but takes a fairly big performance hit.

Sample, with callerInfo enabled:

node resources/benchmarks/caller-info.js true
> CallerInfo benchmark: true: 627.254ms

Sample, with callerInfo disabled (equivalent to default use with no attachment):

node resources/benchmarks/caller-info.js
CallerInfo benchmark: false: 140.666ms