From 33deb62684a5b46e52e38c73af865ed30006a470 Mon Sep 17 00:00:00 2001
From: Michael Shimmins <1013281+shimms@users.noreply.github.com>
Date: Wed, 14 Aug 2024 20:55:39 +1000
Subject: [PATCH] include default meta in `addMeta` overwrite method
---
docs/README.md | 38 +++++++++++++++++++++++++++++++++-
docs/index.html | 43 ++++++++++++++++++++-------------------
examples/nodejs/index2.ts | 25 ++++++++++++++++++++++-
package-lock.json | 10 ++-------
package.json | 2 +-
src/BaseLogger.ts | 17 +++++++++++++++-
src/interfaces.ts | 3 ++-
7 files changed, 104 insertions(+), 34 deletions(-)
diff --git a/docs/README.md b/docs/README.md
index c63af52..c5e2566 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -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
}
},
@@ -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 "Lifecycle of a log message", 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.
diff --git a/docs/index.html b/docs/index.html
index f63d662..04dd4a7 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -1,21 +1,22 @@
-
-
-