Last active
March 8, 2024 07:36
-
-
Save arc279/528fe31be8cd2c1c1d28ce852d8229d3 to your computer and use it in GitHub Desktop.
winston.version '3.8.2' の出力に filenname, linenumber を付与
This file contains hidden or 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 winston from "winston"; | |
type LogLevel = keyof typeof winston.config.npm.levels; | |
const levels = Object.keys(winston.config.npm.levels); | |
const DEFAULT_LABEL = "-"; | |
const formatAddLocation = winston.format((info) => { | |
const getLocation = () => { | |
const limitBak = Error.stackTraceLimit; | |
Error.stackTraceLimit = Infinity; | |
const stk = new Error().stack; | |
Error.stackTraceLimit = limitBak; | |
const lines = stk.split("\n"); | |
const msg = lines.slice(4).filter((x) => !x.includes("winston"))[0]; | |
const loc = msg.slice(msg.lastIndexOf("(") + 1, -1).replace("file://", ""); | |
const [filename, linenumber] = loc.split(":"); | |
return [filename, linenumber] as const; | |
}; | |
info.location = getLocation(); | |
return info; | |
})(); | |
export function getLoggerStandard( | |
level: LogLevel, | |
label: string = DEFAULT_LABEL | |
) { | |
const logger = winston.createLogger({ | |
level: level as string, | |
format: winston.format.combine( | |
formatAddLocation, | |
winston.format.label({ label: label }), | |
winston.format.timestamp(), | |
winston.format.colorize(), | |
winston.format.printf( | |
({ level, message, label, timestamp, location }) => | |
`${timestamp} [${label || DEFAULT_LABEL}] ${level}: ${message} @${location[0] | |
}:${location[1]}` | |
) | |
), | |
transports: [ | |
new winston.transports.Console({ | |
stderrLevels: levels, | |
}), | |
], | |
}); | |
return logger; | |
} | |
export function getLoggerAwsLambda( | |
level: LogLevel, | |
label: string = DEFAULT_LABEL | |
) { | |
const logger = winston.createLogger({ | |
level: level as string, | |
format: winston.format.combine( | |
formatAddLocation, | |
winston.format.label({ label: label }), | |
winston.format.timestamp(), | |
winston.format.json() | |
), | |
transports: [new winston.transports.Console()], | |
}); | |
return logger; | |
} | |
const defaultLogger = (() => { | |
const level = (process.env.LOG_LEVEL || "info") as LogLevel; | |
if (process.env.LAMBDA_TASK_ROOT) { | |
return getLoggerAwsLambda(level); | |
} else { | |
return getLoggerStandard(level); | |
} | |
})(); | |
export default defaultLogger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment