Implement consistent request logging
This commit is contained in:
parent
8102144b85
commit
34be5bbca2
1 changed files with 16 additions and 1 deletions
|
@ -16,12 +16,27 @@ function adaptResponseToReply(response: HttpResponse, reply: FastifyReply): void
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatCombinedLog(request: FastifyRequest, reply: FastifyReply): string {
|
||||||
|
const remoteAddress = [request.socket.remoteAddress, request.socket.remotePort].filter((v) => v != null).join(':')
|
||||||
|
const userAgent = request.headers['user-agent'] || ''
|
||||||
|
const contentType = request.headers['content-type'] || ''
|
||||||
|
return `${remoteAddress} - "${request.method} ${request.url} HTTP/${request.raw.httpVersion}" ${reply.statusCode} "${request.protocol}://${request.hostname}" "${userAgent}" "${contentType}"`
|
||||||
|
}
|
||||||
|
|
||||||
export const serve: HttpAdapter = async (server: HttpServer) => {
|
export const serve: HttpAdapter = async (server: HttpServer) => {
|
||||||
const fastify = Fastify({
|
const fastify = Fastify({
|
||||||
logger: server.debug,
|
logger: false,
|
||||||
serverFactory: server.serverFactory,
|
serverFactory: server.serverFactory,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
fastify.addHook('onResponse', (request: FastifyRequest, reply: FastifyReply) => {
|
||||||
|
if (reply.statusCode >= 400) {
|
||||||
|
server.log?.warn(formatCombinedLog(request, reply))
|
||||||
|
} else if (server.debug) {
|
||||||
|
server.log?.debug(formatCombinedLog(request, reply))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
fastify.addHook('onRequest', (request: FastifyRequest, reply: FastifyReply, next: HookHandlerDoneFunction) => {
|
fastify.addHook('onRequest', (request: FastifyRequest, reply: FastifyReply, next: HookHandlerDoneFunction) => {
|
||||||
const response = server.onRequest()
|
const response = server.onRequest()
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue