Generate req.correlationId
This commit is contained in:
parent
c813407c95
commit
6ae5817529
1
packages/server/@types/express.d.ts
vendored
1
packages/server/@types/express.d.ts
vendored
@ -9,6 +9,7 @@ declare namespace Application {
|
||||
|
||||
declare namespace Express {
|
||||
export interface Request {
|
||||
correlationId: string
|
||||
user?: Application.User
|
||||
logInPromise(user: any): Promise<void>
|
||||
}
|
||||
|
||||
@ -6,7 +6,8 @@ export class ErrorApiHandler implements IMiddleware {
|
||||
constructor(readonly logger: ILogger) {}
|
||||
|
||||
handle: IErrorHandler = (err, req, res, next) => {
|
||||
this.logger.error('An API error occurred: %s', err.stack)
|
||||
this.logger.error('%s An API error occurred: %s',
|
||||
req.correlationId, err.stack)
|
||||
const statusCode = this.getStatus(err)
|
||||
res.status(statusCode)
|
||||
res.end('An error occurred')
|
||||
|
||||
@ -6,7 +6,9 @@ export class ErrorPageHandler implements IMiddleware {
|
||||
constructor(readonly logger: ILogger) {}
|
||||
|
||||
handle: IErrorHandler = (err, req, res, next) => {
|
||||
this.logger.error('An error occurred: %s', err.stack)
|
||||
this.logger.error(
|
||||
'%s An error occurred: %s',
|
||||
req.correlationId, err.stack)
|
||||
// TODO Show an error page!
|
||||
const statusCode = this.getStatus(err)
|
||||
res.status(statusCode)
|
||||
|
||||
@ -1,21 +1,23 @@
|
||||
import {IHandler} from './IHandler'
|
||||
import {ILogger} from '../logger/ILogger'
|
||||
import {IMiddleware} from './IMiddleware'
|
||||
import shortid from 'shortid'
|
||||
|
||||
export class RequestLogger implements IMiddleware {
|
||||
constructor(protected readonly logger: ILogger) {}
|
||||
|
||||
handle: IHandler = (req, res, next) => {
|
||||
const start = Date.now()
|
||||
req.correlationId = shortid.generate()
|
||||
res.on('finish', () => {
|
||||
const { method, originalUrl, user } = req
|
||||
const username = user ? user.username : ''
|
||||
const duration = Date.now() - start
|
||||
this.logger.debug('%s %s [%s] %j',
|
||||
method, originalUrl, username, req.body)
|
||||
this.logger.debug('%s %s %s [%s] %j',
|
||||
req.correlationId, method, originalUrl, username, req.body)
|
||||
const { statusCode } = res
|
||||
this.logger.info('%s %s [%s] %d %sms',
|
||||
method, originalUrl, username, statusCode, duration)
|
||||
this.logger.info('%s %s %s [%s] %d %sms',
|
||||
req.correlationId, method, originalUrl, username, statusCode, duration)
|
||||
})
|
||||
next()
|
||||
}
|
||||
|
||||
@ -14,7 +14,8 @@ export class Transaction implements IMiddleware {
|
||||
ns.bindEmitter(res)
|
||||
|
||||
ns.run(() => {
|
||||
const correlationId = shortid.generate();
|
||||
// use pregenerated request correlationId
|
||||
const correlationId = req.correlationId || shortid.generate();
|
||||
(req as any).correlationId = correlationId
|
||||
ns.set(CORRELATION_ID, correlationId)
|
||||
next()
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user