import * as Express from 'express';
import {ACCESS_TEMPLATE} from './access-logger';
import {
LogConfig,
LogLevel,
LogOptions,
logProvider,
MessageContext,
templateString,
} from '@btilford/ts-base-core';
export type AccessLogOptions = LogOptions & {
useLevel: LogLevel;
name?: string;
}
export function accessLogMiddleware(options: AccessLogOptions): Express.RequestHandler {
let config: LogConfig;
const configDefaults = {
messageTemplate: templateString(ACCESS_TEMPLATE),
};
Iif (options.parent && options.config) {
config = options.parent.config.extend({
...options.config,
...configDefaults
}, true);
} else Eif (options.parent) {
config = options.parent.config.extend(configDefaults, true);
} else {
config = LogConfig.create({
...options.config,
...configDefaults
});
}
const logger = (options?.parent || logProvider()).extend(options.name || 'access', config)
return function accessLog(req: Express.Request, res: Express.Response, next: Express.NextFunction): any {
next();
const errored = logger.write(options.useLevel, new MessageContext('', {
timestamp: new Date().toISOString(),
pid: process.env.pid,
req: {
url: req.originalUrl,
method: req.method,
ip: (req.header('x-fowarded-for') || '').split(',')[0].trim() || '',
userAgent: req.header('user-agent')
},
res: {
status: res.statusCode,
length: res.getHeader('content-length') || 0,
}
}));
Iif (errored) {
process.stderr.write(`ERROR writing access log! ${errored.message} ${errored.stack}`);
}
}
}
|