Created
June 22, 2023 18:39
-
-
Save iczero/f1e5878ac31f03e5f2a1b1defaea74f5 to your computer and use it in GitHub Desktop.
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
import { formatWithOptions } from 'util'; | |
import winston, { Logform, format, transports } from 'winston'; | |
import chalk, { ChalkInstance } from 'chalk'; | |
import moment from 'moment'; | |
const FORMAT_OPTIONS = { | |
depth: null, | |
maxArrayLength: null, | |
breakLength: 120, | |
colors: process.stdout.isTTY | |
}; | |
export const LOG_LEVELS = { | |
error: 0, | |
warn: 1, | |
notice: 2, | |
info: 3, | |
debug: 4, | |
trace: 5 | |
}; | |
export const LOG_COLORS: Record<keyof typeof LOG_LEVELS, ChalkInstance> = { | |
error: chalk.red, | |
warn: chalk.yellow, | |
notice: chalk.blue, | |
info: chalk.green, | |
debug: chalk.cyan, | |
trace: chalk.magenta | |
}; | |
let logLevel = process.env.LOG_LEVEL ?? 'info'; | |
let complainLogLevel = false; | |
if (!(logLevel in LOG_LEVELS)) { | |
logLevel = 'info'; | |
complainLogLevel = true; | |
} | |
const formatTimestamp = () => moment().format('YYYY-MM-DD hh:mm:ss').trim(); | |
export let logger = winston.createLogger({ | |
levels: LOG_LEVELS, | |
level: logLevel, | |
transports: [ | |
new transports.Console() | |
], | |
format: format.combine( | |
format.printf((info: Logform.TransformableInfo) => { | |
// @ts-ignore typescript pls | |
let splat = info[Symbol.for('splat')]; | |
let formattedMessage = splat | |
? formatWithOptions(FORMAT_OPTIONS, info.message, ...splat) | |
: formatWithOptions(FORMAT_OPTIONS, info.message); | |
let moduleName = info.module ?? 'unknown'; | |
let level: string; | |
if (info.level in LOG_LEVELS) { | |
level = LOG_COLORS[<keyof typeof LOG_COLORS> info.level](info.level); | |
} else { | |
level = 'INVALID LOG LEVEL:' + info.level; | |
} | |
return `${formatTimestamp()} [${moduleName}/${level}] ${formattedMessage}`; | |
}) | |
) | |
}); | |
if (complainLogLevel) { | |
forModule('logger').error('provided log level', process.env.LOG_LEVEL, 'is not valid, defaulting to', logLevel); | |
} | |
export function forModule(name: string) { | |
return logger.child({ module: name }); | |
} | |
export default forModule; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment