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.

Module

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.

Classes

LambdaLog

Main class for the module.

Extends: EventEmitter

constructor([options], [levels])

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.

ParamTypeRequired?DescriptionDefault
optionsObjectNoOptions object. See log.options for available options.{}
levelsObjectNoDeprecated Allows adding and customizing log levels. See Custom Log Levels.{}

Returns: this

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.

OptionTypeDefaultDescription
metaObject{}Global metadata to be included in all logs for the instance of LambdaLog.
tagsString[]¦Function[][]Global tags to be included in all logs for the instance of LambdaLog. See Enhanced Tags.
dynamicMetaFunctionnullFunction that is executed for each log message to retrieve additional metadata. See Dynamic Metadata.
debugBooleanfalseEnables log.debug().
devBooleanfalseEnables pretty-printing of JSON logs to the console.
silentBooleanfalseDisables logging to console but messages and events are still generated. Can be controlled by LAMBDALOG_SILENT environment variable.
replacerFunctionnullReplacer function for JSON.stringify() to allow handling of sensitive data before logs are written. See JSON.stringify.
logHandlerObjectconsoleA console-like object containing all standard console functions. Allows logs to be written to any custom location. See Log Handler.
levelKeyString¦null_logLevelSince 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.
messageKeyStringmsgSince 3.0.0 — Override the key in the JSON log message for the message.
tagsKeyString¦null_tagsSince 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.

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

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.

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.

ParamTypeRequired?DescriptionDefault
msgAnyYesMessage to log. Can be any type, but string or Error reccommended.--
metaObjectNoMetadata 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.{}
tagsString[]¦Function[]NoTags to set for this log message. See Enhanced Tags.[]

Returns: LogMessage

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.

ParamTypeRequired?DescriptionDefault
levelStringYesThe log level for this log. Must be one of info, warn, error, debug or the name of a custom log level.--
msgAnyYesMessage to log. Can be any type, but string or Error reccommended.--
metaObjectNoMetadata 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.{}
tagsString[]¦Function[]NoTags to set for this log message. See Enhanced Tags.[]

Returns: LogMessage

Example

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

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

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.

ParamTypeRequired?DescriptionDefault
testAnyYesA value which is tested for a falsy value.--
msgAnyYesMessage to log. Can be any type, but string or Error reccommended.--
metaObjectNoMetadata 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.{}
tagsString[]¦Function[]NoTags to set for this log message. See Enhanced Tags.[]

Returns: LogMessage or false if test passed.

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])
2.3.0

Generates a log message with the result or error provided by a promise. Useful for debugging and testing.

ParamTypeRequired?DescriptionDefault
promisePromiseYesA Promise to retrieve a result from.--
metaObjectNoMetadata 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.{}
tagsString[]¦Function[]NoTags to set for this log message. See Enhanced Tags.[]

Returns: Promise<LogMessage>

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

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.

ParamTypeRequired?DescriptionDefault
nameStringYesThe name of the log level.--
handlerString¦FunctionYesThe console method as a string to use to log this message or a function that returns a console method as a string.--

Returns: this

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
3.0.0

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

PropertyDescription
LEVELSThe 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)

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.

ParamTypeRequired?DescriptionDefault
logObjectYesData for the given log message.--
log.levelStringYesThe log level for this message.--
log.msgAnyYesThe message of the log.--
log.metaObjectNoMetadata to attach to this log message.{}
log.tagsString[]¦Function[]NoTags to attach to this log message.[]
optsObjectYesOptions from the LambdaLog instance.--

Returns: this

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.

ParamTypeRequired?DescriptionDefault
formatBooleanNoPretty-print the JSON object with 4-space indentation.false

Returns: String — JSON string of message.value.

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.

ParamTypeRequired?DescriptionDefault
valAnyYesValue to test if it's an Error or Error-like object.--

Returns: Boolean — true if is an error, otherwise false.

LogMessage.stubError(err)
Error

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

ParamTypeRequired?DescriptionDefault
errErrorYesThe Error to stub with a toJSON method.--

Returns: Error

LogMessage.symbols
Object
3.0.0

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

PropertyDescription
LOGThe symbol used for the log data internally. For example: message[LogMessage.symbols.LOG].
METAThe symbol used for the log metadata internally. For example: message[LogMessage.symbols.META].
ERRORThe symbol used for the original passed Error, if applicable, internally. For example: message[LogMessage.symbols.ERROR].
OPTSThe symbol used for the LambdaLog options internally. For example: message[LogMessage.symbols.OPTS].