Skip to content

Instantly share code, notes, and snippets.

@vanduc1102
Last active July 3, 2021 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanduc1102/92aacca6095f24e8b8838d0bf3e9ca7d to your computer and use it in GitHub Desktop.
Save vanduc1102/92aacca6095f24e8b8838d0bf3e9ca7d to your computer and use it in GitHub Desktop.
Winston3 Logger with custom namespace
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