Skip to main content.

API ReferenceComplete reference of the LambdaLog API.

Using lambda-log is very simple and can be utilized by either using the default export or by instantiating the LambdaLog class.

lambda-log

The default export for this package which is an instance of the LambdaLog class.

Kind: LambdaLog Instance


Example

1const log = require('lambda-log');
2 
3log.info('Hello world!');

log.LambdaLog

Access to the uninstantiated LambdaLog class. Useful for creating your own instance or adding/overridding functionality.

Example

1const { LambdaLog } = require('lambda-log');
2const log = new LambdaLog();
3 
4log.info('Hello world!');

log.LogMessage

Access to the uninstantiated LogMessage class. You can override this property to use a custom logging class that inherits the same methods.


LambdaLog

Main class for the module.

Extends: EventEmitter


constructor([options], [levels])
this

Constructor for the LambdaLog class. Provided to be utilized in more advanced cases to allow overriding and configuration. By default, this module will export an instance of this class but you may access the class and create your own instance via log.LambdaLog.

Parameters

options Object Optional. Configuration options for LambdaLog. See log.options for available options. Default is {}.

levels Object DEPRECATED Optional. Allows adding and customizing log levels. See Custom Log Levels. Default is [].


log.options
Object

Configuration object for LambdaLog. All options are optional. Most options can be changed at any time via log.options.OPTION = VALUE; unless otherwise noted. Options changed using log.options apply to the specific instance of LambdaLog. If you need to use different options throughout your app, it's best to create a new instance of LambdaLog for each corresponding need.

Properties

meta Object Global metadata to be included in all logs for the instance of LambdaLog. Default is {}. See Metadata.

tags String[]|Function[] Global tags to be included in all logs for the instance of LambdaLog. Default is []. See Enhanced Tags.

dynamicMeta Function Function that is executed for each log message to retrieve additional metadata. Default is null. See Dynamic Metadata.

debug Boolean DEPRECATED Enables log.debug(). Default is false. See Debug Logs.

dev Boolean Enables pretty-printing of JSON logs to the console. Default is false. See Pretty Printing.

silent Boolean Disables logging to console but messages and events are still generated. Can be controlled by LAMBDALOG_SILENT environment variable. Default is false. See Silent Mode.

replacer Function Replacer function for JSON.stringify() to allow handling of sensitive data before logs are written. Default is null. See JSON.stringify.

logHandler Object A console-like object containing all standard console functions. Allows logs to be written to any custom location. Default is console. See Log Handler.

levelKey String|null Since 3.0.0 — Override the key in the JSON log message for the log level. Set to null to remove this key from the JSON output. Default is "_logLevel".

messageKey String Since 3.0.0 — Override the key in the JSON log message for the message. Default is "msg".

tagsKey String|null Since 3.0.0 — Override the key in the JSON log message for the tags. Set to null to remove this key from the JSON output. Default is "_tags".


log.<info|warn|error|debug|*>(msg, [meta], [tags])
LogMessageBoolean

Shortcut methods for log.log(). By default, the following methods are available: log.info(), log.warn(), log.error() and log.debug(). Additional methods will be added for any custom log levels provided. This method will return the instance of LogMessage or false if debug logs are enabled and you are calling log.debug().

The provided msg can be any type, although a string or Error is recommended. If Error is provided the stack trace is added as metadata to the log as stack.

Custom Log Levels have been deprecated in version 3.1.0 and will be removed in version 4.0.0. Once removed, this shortcut methods will only be added for the built-in log levels.

Parameters

msg String|Number|Object|Array|Error Required. Message to log. Can be any type listed, but string or Error reccommended.

meta Object|String|Number|Array Optional. Metadata to include in the logged JSON. If an object is provided, each of the properties are merged into the root of the JSON. If any other type is provided, the value will be set on the meta key within the root of the JSON. See Metadata. Default is {}.

tags String[]|Function[] Optional. Tags to set for this log message. See Tagging. Default is [].

Example

1const log = require('lambda-log');
2 
3log.info('Test info log');
4log.debug('Test debug log');
5log.warn('Test warn log');
6log.error('Test error log');
7 
8log.error(new Error('There was an error!'));
9log.info('Success!', { stats }, ['success']);

log.log(level, msg, [meta], [tags])
LogMessageBoolean

Generates JSON log message based on the provided parameters and the global configuration. Once the JSON message is created, it is properly logged to the console and emitted through an event. If an Error or Error-like object is provided for msg, it will parse out the message and include the stacktrace in the metadata. This method will return the instance of LogMessage or false if debug logs are enabled and you using the debug log level.

Parameters

level String Required. The log level for this log. Must be one of info, warn, error, debug or the name of a custom log level.

msg String|Number|Object|Array|Error Required. Message to log. Can be any type listed, but string or Error reccommended.

meta Object|String|Number|Array Optional. Metadata to include in the logged JSON. If an object is provided, each of the properties are merged into the root of the JSON. If any other type is provided, the value will be set on the meta key within the root of the JSON. See Metadata. Default is {}.

tags String[]|Function[] Optional. Tags to set for this log message. See Tagging. Default is [].

Example

1log.log('error', 'Something failed!');
2// same as:
3log.error('Something failed!');

log.assert(test, msg, [meta], [tags])
LogMessageBoolean

Generates a log message if test is a falsy value. If test is truthy, the log message is skipped and returns false. Allows creating log messages without the need to wrap them in an if statement. The log level will be error.

Parameters

test Any Required. A value which is tested for a falsy value.

msg String|Number|Object|Array|Error Required. Message to log. Can be any type listed, but string or Error reccommended.

meta Object|String|Number|Array Optional. Metadata to include in the logged JSON. If an object is provided, each of the properties are merged into the root of the JSON. If any other type is provided, the value will be set on the meta key within the root of the JSON. See Metadata. Default is {}.

tags String[]|Function[] Optional. Tags to set for this log message. See Tagging. Default is [].

Example

1let results = null;
2// This log will be displayed since `results` is a falsy value.
3log.assert(results, 'No results provided!');
4//=> { msg: "No results provided!" ... }
5 
6// But if they are truthy, the log is ignored:
7results = [1, 2, 3];
8log.assert(results, 'No results provided!');
9//=> false

log.result(promise, [meta], [tags])

Generates a log message with the result or error provided by a promise. This method does not take a message, instead it uses the result or error of the provided Promise as the message. Useful for debugging and testing.

Parameters

promise Promise<Any> Required. A Promise to retrieve a result from.

meta Object|String|Number|Array Optional. Metadata to include in the logged JSON. If an object is provided, each of the properties are merged into the root of the JSON. If any other type is provided, the value will be set on the meta key within the root of the JSON. See Metadata. Default is {}.

tags String[]|Function[] Optional. Tags to set for this log message. See Tagging. Default is [].

Example

1let promise = new Promise(resolve => resolve('this is a test'));
2 
3log.result(promise);
4// => { "_logLevel": "info", "msg": "this is a test" ... }
5 
6// If the Promise rejects:
7let promise = new Promise((resolve, reject) => reject(new Error('Something failed')));
8log.result(promise);
9// => { "_logLevel": "error", "msg": "Something failed" ... }

log.addLevel(name, handler)
this

Add a custom log level to this instance of LambdaLog. A dynamic method for the new log level will be added to the class. If you pass a function as handler, the function is called for each log message with the parameter msg — The LogMessage instance for the current log message — and the function is scoped to the current instance of LambdaLog. This function must return either false to disable the log from being generated or a string console method name such as log, info, warn, error, and debug.

See Custom Log Levels.

Parameters

name String Required. The name of the log level.

handler String|Function Required. The console method as a string to use to log this message or a function that returns a console method as a string.

Example

1// Add a new level called "fatal" and log messages with "console.error()":
2log.addLevel('fatal', 'error');
3log.fatal('There was a very bad error');
4 
5// With a function:
6log.addLevel('trace', function (msg) {
7 // Called with param "msg" which is the LogMessage instance for the particular log message.
8 // This function is scoped to the LambdaLog instance.
9 
10 // If you add your own config option to `log.options`, you can check it here:
11 if(!this.options.trace) return false;
12 return 'log';
13});
14 
15log.options.trace = true;
16log.trace('This is a trace message');

Event: log

The log event is emitted (using EventEmitter) for every log generated. This allows for custom integrations, such as logging to a thrid-party service. This event is emitted with the LogMessage instance for the log. You may control events using all the methods of EventEmitter.

Example

1log.on('log', message => {
2 // an example would be sending the log message to another service
3 someLogService(message.toJSON());
4});

LambdaLog.symbols
Object

Static object which contains Symbol definitions used within the LambdaLog class. Available only for advanced usage.

The use of Symbols will be removed in the next major release of LambdaLog due to switching to TypeScript.

Properties

LEVELS Symbol The symbol used for the log levels configuration internally. For example: log[LambdaLog.symbols.LEVELS].


LogMessage

A new instance of this class is created for every log message. The instance of this class is returned from various log methods and passed into the log event. The purpose of this class is to transform and compile a log message into JSON to be outputted.


constructor(log, opts)
this

Constructor for the LogMessage class. Called with an object log that contains the data for the log message and an object opts which is the LambdaLog options.

Parameters

log Object Required. Data for the given log message.

log.level String Required. The log level for this message.

log.msg String|Number|Object|Array|Error Required. The message of the log.

log.meta Object|String|Number|Array Optional. Metadata to attach to this log message.

log.tags String[]|Function[] Optional. Tags to attach to this log message.

opts Object Options from the LambdaLog instance.


message.level
String

Gets the level for this log message.

Example

1const message = log.info('This is an info log');
2console.log(message.level);
3// => "info"

message.msg
String

Gets the transformed message for this log message.

Alias: message.message

Example

1const message = log.error(new Error('There was an error'));
2console.log(message.msg);
3// => "There was an error"

message.msg = String

Set the message for the log message, overwriting the existing message.

Alias: message.message = String

Example

1const message = log.info('Info message');
2console.log(message.msg);
3// => "Info message"
4 
5message.msg = 'New message';
6console.log(message.msg);
7// => "New message"

message.meta
Object

Gets the combined metadata for this log message. This includes metadata passed into the log message, global metadata, and dynamic metadata. From version 3.0.0, any Error or Error-like objects found in the root of the metadata will be converted to a plain object.

Example

1log.options.meta = { prop: 'value' };
2const message = log.info('This is an info log', { with: 'metadata', err: new Error('An error') });
3 
4console.log(message.meta);
5// => { prop: 'value', with: 'metadata', err: { message: 'An error', stack: '...' } }

message.meta = Object

Adds or overwrites metadata for the log message while keeping the existing metadata.

Example

1log.options.meta = { prop: 'value' };
2const message = log.info('This is an info log', { with: 'metadata' });
3 
4console.log(message.meta);
5// => { prop: 'value', with: 'metadata' }
6 
7message.meta = { abc: 123, prop: 'newValue' };
8console.log(message.meta);
9// => { prop: 'newValue', with: 'metadata', abc: 123 }

message.tags
String[]

Gets the tags for this log message. This includes tags passed into the log message and global tags. The tags are generated from strings or by using enhanced tags.

Example

1log.options.tags = ['a-tag', '<<level>>'];
2const message = log.info('This is an info log', {}, ['success']);
3 
4console.log(message.tags);
5// => ['a-tag', 'info', 'success']

message.tags = String[]|Function[]

Adds additional tags to the log message while keeping existing tags. You may include enhanced tags.

Example

1log.options.tags = ['a-tag'];
2const message = log.info('This is an info log', {}, ['success']);
3 
4console.log(message.tags);
5// => ['a-tag', 'success']
6 
7message.tags = ['<<level>>', 'more-tags'];
8console.log(message.tags);
9// => ['a-tag', 'success', 'info', 'more-tags']

message.value
Object

Gets the compiled log object for this log message. From version 3.0.0, the key names of the properties in this object can be overridden using the options levelKey, messageKey, and tagsKey in log.options. If levelKey or tagsKey is set to null or undefined, those properties will not be included in the output of the log message.

Alias: message.log

Example

1const message = log.info('This is an info log');
2console.log(message.value);
3// => { _logLevel: 'info', msg: 'This is an info log', _tags: [] }

message.throw

Throws the an error. If an error was not provided, one will be generated for you and thrown. This is useful in cases where you need to log an error, but also throw it.

Example

1log.error('This is an error').throw;
2 
3// Shorthand for:
4let logMsg = log.error('This is an error');
5let error = new Error(logMsg.msg);
6error.log = logMsg;
7 
8throw error;

message.toJSON([format])
String

Returns the compiled log object converted into a JSON string. This method utilizes log.options.replacer for the replacer function. Uses fast-safe-stringify to prevent circular reference issues. Returns message.value JSON stringified.

Parameters

format Boolean Optional. Pretty-print the JSON object with 4 spaces of indentation. Default is false.

Example

1log.error('This is an error').toJSON(true);
2// => {
3// "_logLevel": "error",
4// "msg": "This is an error",
5// ...
6// }

LogMessage.isError(val)
Boolean

Static function that checks if provided val is an Error or Error-like object. Returns true if the provided value is an Error, otherwise false.

Parameters

val Any Required. Value to test if it's an Error or Error-like object.


LogMessage.stubError(err)
Error

Static function that stubs an Error with a toJSON method for easily converting an Error into a plain object.

Parameters

err Error Required. The Error to stub with a toJSON method.


LogMessage.symbols
Object

Static object which contains Symbol definitions used within the LogMessage class. Available only for advanced usage.

Properties

LOG Symbol The symbol used for the log data internally. For example: message[LogMessage.symbols.LOG].

META Symbol The symbol used for the log metadata internally. For example: message[LogMessage.symbols.META].

ERROR Symbol The symbol used for the original passed Error, if applicable, internally. For example: message[LogMessage.symbols.ERROR].

OPTS Symbol The symbol used for the LambdaLog options internally. For example: message[LogMessage.symbols.OPTS].