Last active
April 1, 2022 16:27
-
-
Save drewwiens/1c7f10feb4fb35bf9cd2786079f7e580 to your computer and use it in GitHub Desktop.
Better NestJS pino-pretty logger output for local development
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Compact terminal output, colorized, with the following fields highlighted with | |
// brighter text for easier readability: request ID, request method, request URL, | |
// request Authorization header, response status code, and context which is usually | |
// a string passed when creating each logger object e.g. "SomeController". | |
import { Module } from '@nestjs/common'; | |
import { blackBright, inverse } from 'cli-color'; | |
import { pick } from 'lodash'; | |
import { LoggerModule } from 'nestjs-pino'; | |
function highlightValue(json: string, value: string) { | |
return value ? json.replace(value, inverse(value)) : json; | |
} | |
function highlightContext( | |
log: Record<string, any>, // eslint-disable-line @typescript-eslint/no-explicit-any | |
messageKey: string, | |
) { | |
const props = ['req', 'res', 'context']; | |
let json = JSON.stringify(pick(log, ...props)); | |
json = highlightValue(json, log.req?.id); | |
json = highlightValue(json, log.req?.method); | |
json = highlightValue(json, log.req?.url); | |
json = highlightValue(json, log.req?.headers?.authorization); | |
json = highlightValue(json, log.res?.statusCode); | |
json = highlightValue(json, log.context); | |
props.forEach((key) => delete log[key]); | |
return `${log[messageKey]} ${blackBright(json)}`; | |
} | |
@Module({ | |
imports: [ | |
LoggerModule.forRoot({ | |
pinoHttp: [ | |
{ | |
prettyPrint: environment.production | |
? false | |
: { | |
translateTime: 'SYS:HH:MM:ss.l', | |
colorize: true, | |
singleLine: true, | |
ignore: 'pid,hostname', | |
messageFormat: highlightContext, | |
}, | |
}, | |
], | |
}), | |
], | |
}) | |
export class AppModule {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment