Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

include default meta in addMeta overwrite method #303

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -657,8 +657,10 @@ For every log:
toLogObj: (args: unknown[], clonesLogObj?: LogObj): unknown => {
// convert the log attributes to a LogObj and return it
},
addMeta: (logObj: any, logLevelId: number, logLevelName: string) => {
addMeta: (logObj: any, logLevelId: number, logLevelName: string, defaultMeta?: IMeta) => {
// add meta information to the LogObj and return it
// defaultMeta is populated with the runtime's default meta if
// `settings.includeDefaultMetaInAddMeta` is set to true, otherwise is undefined
}

},
Expand Down Expand Up @@ -695,6 +697,40 @@ For `JSON` logs (no formatting happens here):
});
```

#### Adding custom values to `_meta`

In many instances it is desireable to add additional information to the `_meta` property, such as a request/correlation id
to help group logs from the one request cycle together.

The `addMeta` overwrite method allows you to either extend the base runtime's default meta, or replace it entirely with your
own meta.

To extend it with your own values, set the `includeDefaultMetaInAddMeta` setting to `true`. Once set to true, the `defaultMeta`
attribute fo the `addMeta` method will include the runtime's meta that you can extend:

```typescript
interface IMetaWithRequest extends IMeta {
requestId: string
};

const logger = new Logger({
includeDefaultMetaInAddMeta: true,
type: 'json',
metaProperty: "_meta",
overwrite: {
addMeta: (logObj: any, logLevelId: number, logLevelName: string, defaultMeta?: IMeta) => {
const meta = (defaultMeta || {}) as IMetaWithRequest;
meta.requestId = "0000-aaaaa-bbbbb-1111";

return {
...logObj,
_meta: meta,
};
}
},
});
```

### Defining and accessing `logObj`
As described in <a href="#life_cycle">"Lifecycle of a log message"</a>, every log message goes through some lifecycle steps and becomes an object representation of the log with the name `logObj`.
A default logObj can be passed to the `tslog` constructor and will be cloned and merged into the log message. This makes `tslog` >= 4 highly configurable and easy to integrate into any 3rd party service.
Expand Down
43 changes: 22 additions & 21 deletions docs/index.html
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tslog - Extensible TypeScript Logger for Node.js and Browser.</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="description" content="Extensible TypeScript Logger for Node.js and Browser.">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/vue.css">
</head>
<body>
<div id="app"></div>
<script>
window.$docsify = {
name: 'tslog',
repo: 'https://github.com/fullstack-build/tslog'
}
</script>
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="description" content="Description">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify@4/lib/themes/vue.css">
</head>
<body>
<div id="app"></div>
<script>
window.$docsify = {
name: '',
repo: ''
}
</script>
<!-- Docsify v4 -->
<script src="//cdn.jsdelivr.net/npm/docsify@4"></script>
</body>
</html>
25 changes: 24 additions & 1 deletion examples/nodejs/index2.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Logger, BaseLogger } from "../../src/index.js";
import { Logger, BaseLogger, ILogObj, ILogObjMeta, IMeta } from "../../src/index.js";

const defaultLogObject: {
name: string;
Expand Down Expand Up @@ -130,3 +130,26 @@ jsonLogger.debug(undefined);
//jsonLogger.debug('*', undefined);
console.log("###############");
logger.debug(new URL("https://www.test.de"));

interface IRequestMeta extends IMeta {
requestId: string;
}

const newLogger = new Logger({
type: "json",
metaProperty: "_meta",
overwrite: {
addMeta: (logObj: ILogObj, logLevelId: number, logLevelName: string, defaultMeta?: IMeta): ILogObj & ILogObjMeta => {
const meta = (defaultMeta || {}) as IRequestMeta;
meta.requestId = "0000-aaaaa-bbbbb-1111";

return {
...logObj,
_meta: meta,
};
},
includeDefaultMetaInAddMeta: true,
},
});

newLogger.info("Testing with metadata");
10 changes: 2 additions & 8 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,6 +1,6 @@
{
"name": "tslog",
"version": "4.9.3",
"version": "4.9.4",
"description": "Extensible TypeScript Logger for Node.js and Browser.",
"author": "Eugene <[email protected]> (https://fullstack.build)",
"license": "MIT",
Expand Down
17 changes: 16 additions & 1 deletion src/BaseLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export class BaseLogger<LogObj> {
mask: settings?.overwrite?.mask,
toLogObj: settings?.overwrite?.toLogObj,
addMeta: settings?.overwrite?.addMeta,
includeDefaultMetaInAddMeta: settings?.overwrite?.includeDefaultMetaInAddMeta ?? false,
addPlaceholders: settings?.overwrite?.addPlaceholders,
formatMeta: settings?.overwrite?.formatMeta,
formatLogObj: settings?.overwrite?.formatLogObj,
Expand Down Expand Up @@ -101,7 +102,21 @@ export class BaseLogger<LogObj> {
this.settings.overwrite?.toLogObj != null ? this.settings.overwrite?.toLogObj(maskedArgs, thisLogObj) : this._toLogObj(maskedArgs, thisLogObj);
const logObjWithMeta: LogObj & ILogObjMeta =
this.settings.overwrite?.addMeta != null
? this.settings.overwrite?.addMeta(logObj, logLevelId, logLevelName)
? this.settings.overwrite?.addMeta(
logObj,
logLevelId,
logLevelName,
this.settings.overwrite?.includeDefaultMetaInAddMeta ?? false
? this.runtime.getMeta(
logLevelId,
logLevelName,
this.stackDepthLevel,
this.settings.hideLogPositionForProduction,
this.settings.name,
this.settings.parentNames
)
: ({} as IMeta)
)
: this._addMetaToLogObj(logObj, logLevelId, logLevelName);

// overwrite no matter what, should work for any type (pretty, json, ...)
Expand Down
3 changes: 2 additions & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export interface ISettingsParam<LogObj> {
addPlaceholders?: (logObjMeta: IMeta, placeholderValues: Record<string, string | number>) => void;
mask?: (args: unknown[]) => unknown[];
toLogObj?: (args: unknown[], clonesLogObj?: LogObj) => LogObj;
addMeta?: (logObj: LogObj, logLevelId: number, logLevelName: string) => LogObj & ILogObjMeta;
addMeta?: (logObj: LogObj, logLevelId: number, logLevelName: string, defaultMeta?: IMeta) => LogObj & ILogObjMeta;
includeDefaultMetaInAddMeta?: boolean;
formatMeta?: (meta?: IMeta) => string;
formatLogObj?: (maskedArgs: unknown[], settings: ISettings<LogObj>) => { args: unknown[]; errors: string[] };
transportFormatted?: (logMetaMarkup: string, logArgs: unknown[], logErrors: string[], settings: ISettings<LogObj>) => void;
Expand Down