| 1 | import { customAlphabet } from 'nanoid' |
| 2 | import { PinoLogger } from 'nestjs-pino' |
| 3 | import { storage, Store } from 'nestjs-pino/storage' |
| 4 | |
| 5 | const idGenerator = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 21) |
| 6 | |
| 7 | export function WithLoggerContext( |
| 8 | extraFields?: Record<string, unknown>, |
| 9 | ): MethodDecorator { |
| 10 | return (_target, propertyKey, descriptor: PropertyDescriptor) => { |
| 11 | const original = descriptor.value as (...args: unknown[]) => unknown |
| 12 | |
| 13 | descriptor.value = function (...args: unknown[]): unknown { |
| 14 | const bindings: Record<string, unknown> = { |
| 15 | executionId: idGenerator(), |
| 16 | method: propertyKey, |
| 17 | ...extraFields, |
| 18 | } |
| 19 | |
| 20 | const logger = PinoLogger.root.child(bindings) |
| 21 | const store = new Store(logger) |
| 22 | return storage.run(store, () => original.apply(this, args)) |
| 23 | } |
| 24 | |
| 25 | return descriptor |
| 26 | } |
| 27 | } |
| 28 |