|
| 1 | +/*! |
| 2 | + * Copyright 2018 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import onFinished = require('on-finished'); |
| 18 | +import {getOrInjectContext} from '../context'; |
| 19 | +// Types-only import. |
| 20 | +import * as express from 'express'; |
| 21 | +import { makeHttpRequestData } from './make-http-request'; |
| 22 | + |
| 23 | +const CHILD_LOG_NAME_SUFFIX = 'applog'; |
| 24 | + |
| 25 | +export interface AnnotatedRequestType<LoggerType> extends express.Request { |
| 26 | + log: LoggerType; |
| 27 | +} |
| 28 | + |
| 29 | +export function makeMiddleware<LoggerType>(projectId: string, |
| 30 | + emitRequestLog: (httpRequest: HttpRequest, trace: string) => void, |
| 31 | + makeChildLogger: (childSuffix: string, trace: string) => LoggerType) { |
| 32 | + return (req: express.Request, res: express.Response, next: express.NextFunction) => { |
| 33 | + // TODO(ofrobots): use high-resolution timer. |
| 34 | + const requestStartMs = Date.now(); |
| 35 | + |
| 36 | + const wrapper = { |
| 37 | + setHeader(name: string, value: string) { |
| 38 | + req.headers[name] = value; |
| 39 | + }, |
| 40 | + getHeader(name: string) { |
| 41 | + return req.headers[name]; |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + const spanContext = getOrInjectContext(wrapper); |
| 46 | + const trace = `projects/${projectId}/traces/${spanContext.traceId}`; |
| 47 | + |
| 48 | + // Install a child logger on the request object. |
| 49 | + (req as AnnotatedRequestType<LoggerType>).log = makeChildLogger(CHILD_LOG_NAME_SUFFIX, trace); |
| 50 | + |
| 51 | + // Emit a 'Request Log' on the parent logger. |
| 52 | + onFinished(res, () => { |
| 53 | + const latencyMs = Date.now() - requestStartMs; |
| 54 | + const httpRequest = makeHttpRequestData(req, res, latencyMs); |
| 55 | + emitRequestLog(httpRequest, trace); |
| 56 | + }); |
| 57 | + |
| 58 | + next(); |
| 59 | + }; |
| 60 | +} |
| 61 | + |
| 62 | + |
0 commit comments