@@ -2,6 +2,7 @@ import { pino } from 'pino';
22import * as process from 'process' ;
33import type { LoggingConfig } from '../config/index.js' ;
44import appConfig from '../config/index.js' ;
5+ import { getCurrentReqId } from './reqId.context.js' ;
56
67const loggerConfig = process . env [ 'NODE_ENV' ] === 'production'
78 ? { }
@@ -16,11 +17,19 @@ const loggerConfig = process.env['NODE_ENV'] === 'production'
1617
1718const rootLogger = pino ( loggerConfig ) ;
1819
20+ const loggerCache = new Map < keyof LoggingConfig , pino . Logger > ( ) ;
21+
1922/**
2023 * Creates child logger and returns it.
2124 * @param moduleName - name of the module that is logging
2225 */
2326export function getLogger ( moduleName : keyof LoggingConfig ) : pino . Logger {
27+ const cachedLogger = loggerCache . get ( moduleName ) ;
28+
29+ if ( cachedLogger ) {
30+ return cachedLogger ;
31+ }
32+
2433 const childLogger = rootLogger . child ( {
2534 module : moduleName ,
2635 } ) ;
@@ -33,9 +42,29 @@ export function getLogger(moduleName: keyof LoggingConfig): pino.Logger {
3342
3443 childLogger . level = logLevel ;
3544
45+ loggerCache . set ( moduleName , childLogger ) ;
46+
3647 return childLogger ;
3748}
3849
50+ /**
51+ * Creates a request-scoped logger that includes the request ID
52+ * @param moduleName - name of the module that is logging
53+ * @returns Logger instance with request ID context
54+ */
55+ export function getRequestLogger ( moduleName : keyof LoggingConfig ) : pino . Logger {
56+ const baseLogger = getLogger ( moduleName ) ;
57+ const reqId = getCurrentReqId ( ) ;
58+
59+ if ( reqId != null && reqId !== '' ) {
60+ return baseLogger . child ( {
61+ reqId,
62+ } ) ;
63+ }
64+
65+ return baseLogger ;
66+ }
67+
3968const logger = getLogger ( 'global' ) ;
4069
4170export default logger ;
0 commit comments