Last active
July 3, 2021 05:56
-
-
Save vanduc1102/92aacca6095f24e8b8838d0bf3e9ca7d to your computer and use it in GitHub Desktop.
Winston3 Logger with custom namespace
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
const { LOG_LEVEL, APP_ENV } = process.env; | |
const logFormatter = APP_ENV === 'dev' | |
? format.combine( | |
winston.format.timestamp(), | |
winston.format.colorize(), | |
winston.format.printf((meta: any) => { | |
const { level, message, timestamp, namespace, stack, ...restMeta } = meta; | |
const displayNamespace = namespace ? `[${namespace}] -` : ''; | |
const stackMessage = stack ? `\n${stack}` : ''; | |
const otherMetaMessage = Object.keys(restMeta).length > 0 ? `\n${JSON.stringify(restMeta)}` : ''; | |
return `${timestamp} ${displayNamespace} ${level}: ${message} ${otherMetaMessage}${stackMessage}`; | |
}) | |
) | |
: format.combine(winston.format.timestamp(), winston.format.json()); | |
const logger = winston.createLogger({ | |
level: LOG_LEVEL || 'debug', | |
format: logFormatter, | |
transports: [ | |
new winston.transports.Console({ | |
silent: APP_ENV === 'test', | |
}), | |
], | |
}); | |
export const Logger = (namespace?: string) => { | |
if (namespace) { | |
return logger.child({ namespace }); | |
} | |
return logger; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment