Skip to content

Commit ca5e7c7

Browse files
committed
feat(INFRA-000): handle more res logging scenarios
1 parent 251ccab commit ca5e7c7

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/telemetry/requestLogger.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { ConfigurationSchema } from '../config/schema.js';
1010
import { getNodeEnv } from '../env.js';
1111

1212
const LOG_PREFS = Symbol('Logging information');
13+
const LOGGED_SEMAPHORE = Symbol('Logged semaphore');
1314

1415
interface LogPrefs {
1516
start: [number, number];
@@ -57,9 +58,13 @@ function finishLog<SLocals extends AnyServiceLocals = ServiceLocals<Configuratio
5758
app: ServiceExpress<SLocals>,
5859
error: Error | undefined,
5960
req: Request,
60-
res: Response,
61+
res: Response & { [LOGGED_SEMAPHORE]?: boolean },
6162
histogram: Histogram,
6263
) {
64+
if (res[LOGGED_SEMAPHORE]) {
65+
return;
66+
}
67+
6368
const prefs = (res.locals as WithLogPrefs)[LOG_PREFS];
6469
if (prefs.logged) {
6570
// This happens when error handler runs, but onEnd hasn't fired yet. We only log the first one.
@@ -74,6 +79,8 @@ function finishLog<SLocals extends AnyServiceLocals = ServiceLocals<Configuratio
7479
const endLog: Record<string, string | string[] | number | undefined> = {
7580
...preInfo,
7681
t: 'req',
82+
// ts warning is known and incorrect—`aborted` is a subset of `destroyed``
83+
r: req.aborted ? 'aborted' : req.destroyed ? 'destroyed' : error ? 'errored' : 'finished',
7784
s: (error as ErrorWithStatus)?.status || res.statusCode || 0,
7885
dur,
7986
};
@@ -124,6 +131,8 @@ function finishLog<SLocals extends AnyServiceLocals = ServiceLocals<Configuratio
124131
} else {
125132
logger.info(endLog, msg);
126133
}
134+
135+
res[LOGGED_SEMAPHORE] = true;
127136
}
128137

129138
export function loggerMiddleware<
@@ -180,8 +189,10 @@ export function loggerMiddleware<
180189
logger.info(preLog, msg);
181190
}
182191

183-
const logWriter = () => finishLog(app, undefined, req, res, histogram);
192+
const logWriter = (err?: Error) => finishLog(app, err, req, res, histogram);
184193
res.on('finish', logWriter);
194+
res.on('close', logWriter);
195+
res.on('error', logWriter);
185196
next();
186197
};
187198
}

0 commit comments

Comments
 (0)