Skip to content

Commit

Permalink
feat(): add support for one-time enrichment; add back comments in bui…
Browse files Browse the repository at this point in the history
…ld so they are visible for library users
  • Loading branch information
mikaelvesavuori committed Feb 14, 2023
1 parent 0af59a7 commit 3018b49
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 13 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,28 @@ headers['X-Log-Sampled'] ? logger.setDebugSamplingRate(100) : logger.setDebugSam

## Metadata

### One-time root-level enrichment

If you want a one-time root-level enrichment, you can do:

```typescript
const logger = MikroLog.start();
logger.enrichNext({ someId: '123456789abcdefghi' });
logger.info('Ping!'); // Enrichment is present on log
logger.info('Ping!'); // Enrichment is longer present
```

This works just as well on nested object:

```typescript
const logger = MikroLog.start();
logger.enrichNext({ myObject: { myValue: 'Something here', otherValue: 'Something else' } });
logger.info('Ping!'); // Enrichment is present on log
logger.info('Ping!'); // Enrichment is longer present
```

Note that only object input is allowed for this method.

### Static metadata

_Static metadata_ is the metadata that you may provide at the time of instantiation. These fields will then be used automatically in all subsequent logs.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "mikrolog",
"description": "The JSON logger you always wanted for Lambda.",
"version": "2.1.12",
"version": "2.1.13",
"author": "Mikael Vesavuori",
"license": "MIT",
"main": "./lib/index.js",
Expand Down
36 changes: 27 additions & 9 deletions src/entities/MikroLog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export class MikroLog {
private static debugSamplingLevel: number;
private static isDebugLogSampled: boolean;
private static isColdStart = true;
private nextLogEnrichment: Record<string, any>;

private constructor() {
MikroLog.metadataConfig = {};
Expand All @@ -50,6 +51,7 @@ export class MikroLog {
MikroLog.correlationId = '';
MikroLog.debugSamplingLevel = this.initDebugSampleLevel();
MikroLog.isDebugLogSampled = true;
this.nextLogEnrichment = {};
}

/**
Expand Down Expand Up @@ -105,6 +107,13 @@ export class MikroLog {
MikroLog.correlationId = input?.correlationId || this.correlationId || '';
}

/**
* @description TODO
*/
public enrichNext(input: Record<string, any>) {
this.nextLogEnrichment = input;
}

/**
* @description Set correlation ID manually, for example for use in cross-boundary calls.
*
Expand Down Expand Up @@ -295,15 +304,24 @@ export class MikroLog {

const dynamicMetadata = this.produceDynamicMetadata();

const logOutput = {
...dynamicMetadata,
...staticMetadata,
message: log.message,
error: log.level === 'ERROR',
level: log.level,
httpStatusCode: log.httpStatusCode,
isColdStart: MikroLog.context.isColdStart
};
const logOutput = (() => {
const output = {
...dynamicMetadata,
...staticMetadata,
message: log.message,
error: log.level === 'ERROR',
level: log.level,
httpStatusCode: log.httpStatusCode,
isColdStart: MikroLog.context.isColdStart
};

if (this.nextLogEnrichment && JSON.stringify(this.nextLogEnrichment) !== '{}')
return Object.assign(output, this.nextLogEnrichment);

return output;
})();

this.nextLogEnrichment = {};

const filteredOutput = this.filterOutput(logOutput, redactedKeys, maskedValues);
return this.sortOutput(filteredOutput);
Expand Down
34 changes: 34 additions & 0 deletions tests/MikroLog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -570,3 +570,37 @@ test.serial('It should be able to enrich with correlation ID', (t) => {

t.deepEqual(cleanedResponse, cleanedExpected);
});

test.serial(
'It should enrich a single-level log with a one-time root item and ensure it is not present in later calls',
(t) => {
MikroLog.reset();
const message = 'Hello World';

const logger = MikroLog.start();
logger.enrichNext({ myValue: 'abc123' });

const responseFirst: Record<string, any> = logger.info(message);
const responseSecond: Record<string, any> = logger.info(message);

t.is(responseFirst.hasOwnProperty('myValue'), true);
t.is(responseSecond.hasOwnProperty('myValue'), false);
}
);

test.serial(
'It should enrich a multi-level log with a one-time root item and ensure it is not present in later calls',
(t) => {
MikroLog.reset();
const message = 'Hello World';

const logger = MikroLog.start();
logger.enrichNext({ dd: { trace_id: 'abc123' } });

const responseFirst: Record<string, any> = logger.info(message);
const responseSecond: Record<string, any> = logger.info(message);

t.is(responseFirst['dd']['trace_id'], 'abc123');
t.is(responseSecond.hasOwnProperty('dd'), false);
}
);
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": true,
"removeComments": false,
"resolveJsonModule": true,
"sourceMap": true,
"strict": true,
Expand Down

0 comments on commit 3018b49

Please sign in to comment.