Skip to content

Commit 22d71fd

Browse files
committed
feat(middleware): add logger in request namespace
1 parent 8069cce commit 22d71fd

3 files changed

Lines changed: 11 additions & 12 deletions

File tree

src/config.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
import { ServerConfig } from './types/server';
2626
import { Env } from './utils/env.utils';
2727
import { uuid } from './utils/id.utils';
28-
import { LoggerLevels } from './utils/logger.utils';
28+
import { Logger, LoggerLevels } from './utils/logger.utils';
2929
import { deepObjMerge } from './utils/obj.utils';
3030

3131
/**
@@ -37,6 +37,10 @@ declare global {
3737
interface Request {
3838
/** Unique request identifier (set by middleware) */
3939
id?: string;
40+
/** Logger instance for the request (set by middleware) */
41+
logger?: Logger;
42+
/** User information (set by authentication middleware) */
43+
user?: any;
4044
}
4145
}
4246
}

src/utils/logger.utils.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -292,17 +292,10 @@ export function getLogger(): PinoLogger {
292292
}
293293

294294
/**
295-
* Alias for the current logger instance.
296-
* - Returns a request-scoped logger from AsyncLocalStorage if available
297-
* - Falls back to the global (singleton) logger
298-
* - Initializes the global logger if not created yet
299-
*/
300-
export const logger = getLogger;
301-
302-
/**
303-
* Global logger instance.
295+
* Logger instance for the global context.
296+
* This logger is used for logging messages that are not tied to a specific request.
304297
*/
305-
export const globalLogger = getLogger();
298+
export const logger = getLogger();
306299

307300
/**
308301
* Creates a child logger with additional context.

src/utils/middleware.utils.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,13 @@ export function setupRequestContext(options: { headerName?: string; autoLog?: bo
155155
url: req.originalUrl || req.url
156156
});
157157

158+
req.logger = childLogger;
159+
158160
// Store logger in context
159161
ContextStore.set(StoreKeys.LOGGER, childLogger);
160162

161163
if (autoLog) {
162-
childLogger.info('Request context initialized');
164+
req.logger.info('Request context initialized');
163165
}
164166

165167
next();

0 commit comments

Comments
 (0)