* Internal logger layer that wraps Fastify's log calls with * request-lifecycle awareness (disable-check, level selection). * Keeps the surface intentionally small so hot paths stay fast. * * Users can extend this class to customize internal log lines.
| 10 | * Users can extend this class to customize internal log lines. |
| 11 | */ |
| 12 | class LogController { |
| 13 | /** |
| 14 | * @param {object} [options] |
| 15 | * @param {boolean | ((req: object) => boolean)} [options.disableRequestLogging=false] |
| 16 | * When `true` (or a function returning `true`), per-request log lines |
| 17 | * (incoming, completed, errors) are suppressed. |
| 18 | * @param {string} [options.requestIdLogLabel='reqId'] |
| 19 | * The label used for the request identifier when logging the request. |
| 20 | */ |
| 21 | constructor (options) { |
| 22 | const opts = options || {} |
| 23 | this.disableRequestLogging = opts.disableRequestLogging || defaultInitOptions.disableRequestLogging |
| 24 | this.isDisableRequestLoggingFunction = typeof this.disableRequestLogging === 'function' |
| 25 | this.requestIdLogLabel = opts.requestIdLogLabel || defaultInitOptions.requestIdLogLabel |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Checks whether request logging is disabled for the given request. |
| 30 | * |
| 31 | * @param {object} req Raw or Fastify request object. |
| 32 | * @returns {boolean} `true` when logging should be skipped. |
| 33 | */ |
| 34 | isLogDisabled (req) { |
| 35 | return this.isDisableRequestLoggingFunction |
| 36 | ? this.disableRequestLogging(req) |
| 37 | : this.disableRequestLogging |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Logs an incoming request at `info` level. |
| 42 | * |
| 43 | * @param {object} request Fastify request object. |
| 44 | * @param {object} reply Fastify reply object. |
| 45 | * @param {object} [metadata] Extra contextual data (unused). |
| 46 | */ |
| 47 | incomingRequest (request, reply, metadata) { |
| 48 | if (this.isLogDisabled(request)) { return } |
| 49 | |
| 50 | request.log.info({ req: request }, 'incoming request') |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Logs the outcome of a completed request. |
| 55 | * Uses `error` level when an error is present, `info` otherwise. |
| 56 | * |
| 57 | * @param {Error | null} error Error that occurred during the response, if any. |
| 58 | * @param {object} request Fastify request object. |
| 59 | * @param {object} reply Fastify reply object. |
| 60 | * @param {object} [metadata] Extra contextual data (unused). |
| 61 | */ |
| 62 | requestCompleted (error, request, reply, metadata) { |
| 63 | if (this.isLogDisabled(request)) { return } |
| 64 | |
| 65 | if (error) { |
| 66 | reply.log.error({ res: reply, err: error, responseTime: reply.elapsedTime }, 'request errored') |
| 67 | } else { |
| 68 | reply.log.info({ res: reply, responseTime: reply.elapsedTime }, 'request completed') |
| 69 | } |
nothing calls this directly
no outgoing calls
no test coverage detected