Skip to content

Commit

Permalink
fix request logging middleware status code reporting (medplum#3316)
Browse files Browse the repository at this point in the history
Co-authored-by: dillon streator <[email protected]>
  • Loading branch information
dillonstreator and dillon streator committed Nov 14, 2023
1 parent 701dac7 commit be16119
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions packages/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,22 +214,26 @@ export async function shutdownApp(): Promise<void> {
const loggingMiddleware = (req: Request, res: Response, next: NextFunction): void => {
const ctx = getRequestContext();
const start = new Date();
next();
const afterNext = new Date().getTime(); // Record the time after next() completes
const totalTime = afterNext - start.getTime(); // Calculate the time taken including the time spent in next()
let userProfile: string | undefined;
if (ctx instanceof AuthenticatedRequestContext) {
userProfile = ctx.profile.reference;
}

ctx.logger.info('Request served', {
receivedAt: start,
requestMethod: req.method,
path: req.path,
duration: `${totalTime} ms`,
ip: req.ip,
status: res.statusCode,
ua: req.get('User-Agent'),
profile: userProfile,
res.on('finish', () => {
const duration = new Date().getTime() - start.getTime();

let userProfile: string | undefined;
if (ctx instanceof AuthenticatedRequestContext) {
userProfile = ctx.profile.reference;
}

ctx.logger.info('Request served', {
duration: `${duration} ms`,
ip: req.ip,
method: req.method,
path: req.path,
profile: userProfile,
receivedAt: start,
status: res.statusCode,
ua: req.get('User-Agent'),
});
});

next();
};

0 comments on commit be16119

Please sign in to comment.