Extract logger middleware

This commit is contained in:
Daniel García Aubert 2019-10-01 14:12:14 +02:00
parent 9c79959f88
commit 1a9081135d
3 changed files with 29 additions and 18 deletions

View File

@ -19,7 +19,7 @@ const JobController = require('./job_controller');
const cors = require('../middlewares/cors');
const servedByHostHeader = require('../middlewares/served-by-host-header');
const logger = require('../middlewares/logger');
module.exports = class ApiRouter {
constructor ({ redisPool, metadataBackend, statsClient, dataIngestionLogger }) {
@ -65,6 +65,7 @@ module.exports = class ApiRouter {
route (app) {
const apiRouter = router({ mergeParams: true });
apiRouter.use(logger());
apiRouter.use(cors());
apiRouter.use(servedByHostHeader());

27
app/middlewares/logger.js Normal file
View File

@ -0,0 +1,27 @@
'use strict';
module.exports = function logger () {
if (!global.log4js) {
return function dummyLoggerMiddleware (req, res, next) {
next();
};
}
const options = {
level: 'info',
buffer: true,
// log4js provides a tokens solution as expess but in does not provide the request/response in the callback.
// Thus it is not possible to extract relevant information from them.
// This is a workaround to be able to access request/response.
format: function (req, res, format) {
const defaultFormat = ':remote-addr :method :req[Host]:url :status :response-time ms -> :res[Content-Type]';
const logFormat = global.settings.log_format || defaultFormat;
return format(logFormat);
}
};
const logger = global.log4js.getLogger();
return global.log4js.connectLogger(logger, options);
};

View File

@ -18,7 +18,6 @@
var express = require('express');
var Profiler = require('./stats/profiler-proxy');
var _ = require('underscore');
var fs = require('fs');
var mkdirp = require('mkdirp');
@ -76,22 +75,6 @@ function App(statsClient) {
mkdirp.sync(global.settings.tmpDir);
}
if (global.log4js) {
var loggerOpts = {
buffer: true,
// log4js provides a tokens solution as expess but in does not provide the request/response in the callback.
// Thus it is not possible to extract relevant information from them.
// This is a workaround to be able to access request/response.
format: function(req, res, format) {
var logFormat = global.settings.log_format ||
':remote-addr :method :req[Host]:url :status :response-time ms -> :res[Content-Type]';
return format(logFormat);
}
};
app.use(global.log4js.connectLogger(global.log4js.getLogger(), _.defaults(loggerOpts, {level:'info'})));
}
// Use step-profiler
app.use(function bootstrap$prepareRequestResponse(req, res, next) {
res.locals = res.locals || {};