"use strict";
/*!
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const onFinished = require("on-finished");
const context_1 = require("../context");
const make_http_request_1 = require("./make-http-request");
/**
* Generates an express middleware that installs a request-specific logger on
* the `request` object. It optionally can do HttpRequest timing that can be
* used for generating request logs. This can be used to integrate with logging
* libraries such as winston and bunyan.
*
* @param projectId Generated traceIds will be associated with this project.
* @param makeChildLogger A function that generates logger instances that will
* be installed onto `req` as `req.log`. The logger should include the trace in
* each log entry's metadata (associated with the LOGGING_TRACE_KEY property.
* @param emitRequestLog Optional. A function that will emit a parent request
* log. While some environments like GAE and GCF emit parent request logs
* automatically, other environments do not. When provided this function will be
* called with a populated `StackdriverHttpRequest` which can be emitted as
* request log.
*/
function makeMiddleware(projectId, makeChildLogger, emitRequestLog) {
return (req, res, next) => {
// TODO(ofrobots): use high-resolution timer.
const requestStartMs = Date.now();
const wrapper = context_1.makeHeaderWrapper(req);
const spanContext = context_1.getOrInjectContext(wrapper);
const trace = `projects/${projectId}/traces/${spanContext.traceId}`;
// Install a child logger on the request object.
req.log = makeChildLogger(trace);
if (emitRequestLog) {
// Emit a 'Request Log' on the parent logger.
onFinished(res, () => {
const latencyMs = Date.now() - requestStartMs;
const httpRequest = make_http_request_1.makeHttpRequestData(req, res, latencyMs);
emitRequestLog(httpRequest, trace);
});
}
next();
};
}
exports.makeMiddleware = makeMiddleware;
//# sourceMappingURL=make-middleware.js.map