lambda-log-json
Basic logging mechanism for Node 6.10+ Lambda Functions which properly formats various logs into JSON format for easier reading through Cloudwatch Logs. The module includes functionality to include custom metadata and tags for each log, allowing increased filtering capabilities within Cloudwatch.
Why another lambda logger?
There are others out there, but seemed to be convoluted, included more functionality than needed, not maintained, or not configurable enough. I created lambda-log-json to include the important functionality from other loggers, but still keeping it simple and dependency-free.
Features
- Global metadata and tags that are included with every log.
- Pluggable by wrapping/extending the LambdaLog class.
- Emits event on log to allow third-party integration.
- Error and Error-like objects logged include stacktraces in the metadata automatically.
- Pretty-printing of JSON object in dev mode.
- Well-documented and commented source.
- Small footprint and dependency-free!
Getting Started
Requirements
Node v6.10+ is required. You need to ensure that your Lambda function is running with the correct Node version.
Install
Install via NPM:
$ npm install lambda-log-json --save
Usage
Here is a basic usage example, read the API documentation below to learn more.
const log = ; exports { // set some optional metadata to be included in all logs (this is an overkill example) logconfigmetaevent = event; // add additional tags to all logs logconfigtags; // Log info message log; //=> { _logLevel: 'info' msg: 'my lambda function is running!', event:..., _tags: ['log', 'info', ...] } ifsomethingHappenedButNotFatal log; //=> { _logLevel: 'warn', msg: 'something is missing, but it is OK', event:..., _tags: ['log', 'warn', ...] } // Debug messages are not generated or displayed unless enabled in the config log; //=> false // Enable debug messages logconfigdebug = true; log; //=> { _logLevel: 'debug', msg: 'some debug message again', event:..., _tags: ['log', 'debug', ...] } ; // New in version 1.4.0 - assert ;};
API Documentation
lambdalog
Instance of the LambdaLog
class which is exported when calling require('lambda-log-json')
.
lambdalog.config
Configuration object for LambdaLog. These options can be changed at any time.
- meta (object) - Global metadata to be included in all logs. (Default:
{}
) - tags (Array) - Global tags to be included in all logs. (Default:
[]
) - debug (Boolean) - Enables
lambdalog.debug()
. (Default:false
) - dev (Boolean) - Enable development mode which pretty-prints JSON to the console. (Default:
false
) - silent (Boolean) - Disables logging to
console
but messages and events are still generated. (Default:false
)
lambdalog.log(level, msg[, meta={}])
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 and Error
or Error
-like object is provided for msg
, it will parse out the message and include the stacktrace in the metadata.
Argument | Type | Required? | Description |
---|---|---|---|
level |
String | Yes | Log level to create log for. Must be either info , debug , warn or error . |
msg |
Any | Yes | Message to log. Can be of any type, but string or Error is recommended. |
meta |
Object | No | Optional metadata object to include into the log JSON. |
Example:
const log = ; log;log;
Throws: - Error
If improper log level is provided.
logResponse
Returns:The generated log message or
false
iflevel="debug"
andconfig.debug=false
.
lambdalog.info(msg[, meta={}])
Shorthand method for calling lambdalog.log('info')
.
Argument | Type | Required? | Description |
---|---|---|---|
msg |
Any | Yes | Message to log. Can be of any type, but string or Error is recommended. |
meta |
Object | No | Optional metadata object to include into the log JSON. |
Example:
const log = ; log;log;
logResponse
Returns:The generated log message.
lambdalog.warn(msg[, meta={}])
Shorthand method for calling lambdalog.log('warn')
.
Argument | Type | Required? | Description |
---|---|---|---|
msg |
Any | Yes | Message to log. Can be of any type, but string or Error is recommended. |
meta |
Object | No | Optional metadata object to include into the log JSON. |
Example:
const log = ; log;log;
logResponse
Returns:The generated log message.
lambdalog.error(msg[, meta={}])
Shorthand method for calling lambdalog.log('error')
.
Argument | Type | Required? | Description |
---|---|---|---|
msg |
Any | Yes | Message to log. Can be of any type, but string or Error is recommended. |
meta |
Object | No | Optional metadata object to include into the log JSON. |
Example:
const log = ; log;log; let err = 'Some error happened!';log;
logResponse
Returns:The generated log message.
lambdalog.debug(msg[, meta={}])
(Since v1.1.0) Shorthand method for calling lambdalog.log('debug')
. By default, debug messages are not generated, displayed or emitted. To enable this functionality, you must set config.debug
to true
.
Argument | Type | Required? | Description |
---|---|---|---|
msg |
Any | Yes | Message to log. Can be of any type, but string or Error is recommended. |
meta |
Object | No | Optional metadata object to include into the log JSON. |
Example:
const log = ; // This log will return false and not display any message since config.debug is false by defaultlog;//=> false // But if we enable config.debug, it will act the same as the other log methods:logconfigdebug = true;log;//=> { msg: "This is a test debug message" ... }
logResponse
Returns:The generated log message or
false
ifconfig.debug
is not enabled.
lambdalog.assert(test, msg[, meta={}])
(Since v1.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.
Argument | Type | Required? | Description |
---|---|---|---|
test |
Any | Yes | Value to test if is falsy. |
msg |
Any | Yes | Message to log. Can be of any type, but string or Error is recommended. |
meta |
Object | No | Optional metadata object to include into the log JSON. |
Example:
const log = ; let results = null;// This log will be displayed since `results` is a falsy value.log;//=> { msg: "No results provided!" ... } // But if they are truthy, the log is ignored:results = 1 2 3;log;//=> false
logResponse
Returns:The generated log message or
false
ifconfig.debug
is not enabled.
lambdalog.LambdaLog([meta={}, tags=[]])
Provides access to uninstantiated LambdaLog class. If you want to customize the logger or build a wrapper around LambdaLog, you have access to the class via lambdalog.LambaLog
.
Argument | Type | Required? | Description |
---|---|---|---|
meta |
Object | No | Optional metadata object to include in every log. |
tags |
Array | No | Optional tags array to include in every log. |
Example:
const LambdaLog = LambdaLog; { super someKey: 'Global metadata' 'custom-tag'; } // overwrite lambdalog.error() to do some custom things { // turn message into Error object (to generate stacktraces automatically) let err = msg; return this; }
Returns: this
Instance of LambdaLog.
logResponse
Type: Object | Boolean
The data returned from any log method. If the using log.debug()
and config.debug
is disabled, the response will be false
.
Default Properties:
_logLevel
(String) - The log level (ex. error, warn, info, debug) Since 1.3.0msg
(String) - The message of the log_tags
(Array[String]) - Array of tags applied to the log
Conditional Properties:
*
(Any) - Any metadata provided to the log as individual propertiesstack
(String) - Stack trace of an error ifError
was provided
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 log data object generated by lambdalog.log()
along with level and metadata. You may control events using all the methods of EventEmitter.
Event Attributes:
level
(String) - The level of the log (error, warn, ...)log
(Object) - The generated log object that containsmsg
,_tags
and any metadatameta
(Object) - Metadata for the log
Example:
const log = ; // ES6 Destructuringlog; log;
Tests
Tests are written and provided as part of the module. It requires mocha to be installed which is included as a devDependency
. You may run the tests by calling:
$ npm run test
Contributing
Feel free to submit a pull request if you find any issues or want to integrate a new feature. Keep in mind, this module should be lightweight and advanced functionality should be published to NPM as a wrapper around this module. Ensure to write and run the tests before submitting a pull request. The code should work without any special flags in Node 6.10.
License
MIT License. See License in the repository.