Skip to main content.

Dynamic MetadataAdd data to all your logs dynamically.

2.0.0

Since version 2.0.0, LambdaLog facilitates a concept of dynamically adding metadata to log messages. Dynamic Metadata is generated by the results of calling a function defined in log.options.dynamicMeta for each log message that is generated. This gives the ability to set metadata that may be time-based or changes on a regular basis within your application without needing to manually set the data on each log message.

Note: Dynamic Metadata can only utilize synchronous data. Trying to utilize asynchronous data via the Dynamic Metadata function will not work.

Setting Dynamic Metadata

A Dynamic Metadata function can be set by either passing in as the option dynamicMeta when creating a new instance of LambdaLog or by setting log.options.dynamicMeta on a pre-existing instance of LambdaLog.

1const log = require('lambda-log');
2 
3log.options.dynamicMeta = function() {
4 // ...
5};
1const { LambdaLog } = require('lambda-log');
2const log = new LambdaLog({
3 dynamicMeta() {
4 // ...
5 }
6});

Dynamic Metadata Function

The function signature for Dynamic Metadata is as defined below:

function(msg, options)

For each log message, this function will be called in order to obtain dynamic metadata to include. This function must return an object with dynamic metadata to be added. Any properties returned from this function that already exist in the metadata will be overwritten. To skip adding metadata to the log message, you may return false, null, or an empty object from this function.

ScopeLogMessageThe LogMessage instance for the given log
ParameterTypeDescription
msgLogMessageThe instance of LogMessage for the current log.
optionsObjectThe options object from the LambdaLog instance.

Examples

Add Timestamp to all Log Messages:

1log.options.dynamicMeta = function() {
2 return {
3 timestamp: new Date().toISOString()
4 };
5};

Add UUID to all Error Logs:

1const uuid = require('uuid');
2 
3log.options.dynamicMeta = function(message) {
4 if(message.level === 'error') {
5 return {
6 errorId: uuid.v4()
7 }
8 }
9 
10 return null;
11};

Add a Value from a Global Variable:

1let myGlobal = 'some-value-that-changes';
2 
3log.options.dynamicMeta = function() {
4 return {
5 prop: myGlobal
6 }
7};