如何使用打字稿在 winston 中设置自定义日志级别?
How to set custom loglevel in winston using typescript?
我在 enum
中声明了 LogLevel
,winston 抛出错误。那么 levels
的类型应该是什么?
logger.ts
enum LogLevel {
trace,
debug,
info,
warn,
error
}
const logConfig = {
format: _format.json(),
levels: LogLevel,
transports: [
new _transports.Console()
]
const logger = createLogger(logConfig);
错误
Argument of type '{ format: Format; levels: typeof LogLevel; level: string; transports: _transports.ConsoleTransportInstance[]; }' is not assignable to parameter of type 'LoggerOptions'.
Types of property 'levels' are incompatible.
Type 'typeof LogLevel' is not assignable to type 'AbstractConfigSetLevels'.
Index signatures are incompatible.
Type 'string' is not assignable to type 'number'.ts(2345)
解决方案
不是将枚举直接传递给级别,而是在键值对中定义一个常量,如 _logLevel
所示。
enum LogLevel {
trace,
debug,
info,
warn,
error
}
const _logLevel = {
error: LogLevel.Error,
warn: LogLevel.Warn,
info: LogLevel.Info,
debug: LogLevel.Debug,
trace: LogLevel.Trace
};
const logConfig = {
format: _format.json(),
levels: _logLevel,
transports: [
new _transports.Console()
]
const logger = createLogger(logConfig);
我在 enum
中声明了 LogLevel
,winston 抛出错误。那么 levels
的类型应该是什么?
logger.ts
enum LogLevel {
trace,
debug,
info,
warn,
error
}
const logConfig = {
format: _format.json(),
levels: LogLevel,
transports: [
new _transports.Console()
]
const logger = createLogger(logConfig);
错误
Argument of type '{ format: Format; levels: typeof LogLevel; level: string; transports: _transports.ConsoleTransportInstance[]; }' is not assignable to parameter of type 'LoggerOptions'.
Types of property 'levels' are incompatible.
Type 'typeof LogLevel' is not assignable to type 'AbstractConfigSetLevels'.
Index signatures are incompatible.
Type 'string' is not assignable to type 'number'.ts(2345)
解决方案
不是将枚举直接传递给级别,而是在键值对中定义一个常量,如 _logLevel
所示。
enum LogLevel {
trace,
debug,
info,
warn,
error
}
const _logLevel = {
error: LogLevel.Error,
warn: LogLevel.Warn,
info: LogLevel.Info,
debug: LogLevel.Debug,
trace: LogLevel.Trace
};
const logConfig = {
format: _format.json(),
levels: _logLevel,
transports: [
new _transports.Console()
]
const logger = createLogger(logConfig);