typescript - Typescript - Morgan 和 logger.stream 导致 lint 错误
问题描述
我尝试使用记录器流功能附加Morgan
日志。Winston
但是,一旦我尝试附加logger.stream
使用 morgan 中间件时,它就会失败并显示以下消息:
Argument of type '"combined"' is not assignable to parameter of type 'FormatFn'.
这是我的温斯顿初始化代码:
import * as appRoot from 'app-root-path';
import * as winston from 'winston';
import { Logger } from 'winston';
import * as fs from 'fs';
import * as stream from 'stream';
const dirLogs = `${appRoot}/logs`;
// It's call during initialization, we can block the thread
if (!fs.existsSync(dirLogs)) {
fs.mkdirSync(dirLogs);
}
// define the custom settings for each transport (file, console)
const options = {
file: {
level: 'info',
filename: `${dirLogs}/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// Keep it simple to focus on the need first
// I think Logger should send logs to a logger service
const logger = new Logger({
level: 'info',
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
// If I don't use the stream.Duplex, it cause another lint error.
logger.stream = (options?: any) => new stream.Duplex({
write: function (message: string, encoding: any) {
logger.info(message.trim());
}
});
export default logger;
然后,我尝试使用 Morgan 的代码。
// ... All import
import logger from './logger/index';
// ... Then later the code
this.expressApp.use(morgan('combined', { stream: logger.stream }));
我不确定为什么会出现此错误:/
解决方案
好的,所以我深入研究了代码和打字稿文件,以了解它真正需要做什么。
我改变了我的logger.stream
声明
// If I don't use the stream.Duplex, it cause another lint error.
logger.stream = (options?: any) => new stream.Duplex({
write: function (message: string, encoding: any) {
logger.info(message.trim());
}
});
至
// Don't forget this import
import { Options } from 'morgan';
// And the code
export const morganOption: Options = {
stream: {
write: function (message: string) {
logger.info(message.trim());
},
},
};
然后我导入morganOptions
并将其设置为morgan
// My import
import { logger, morganOption } from './logger/index';
// ... Then later, the new code
this.expressApp.use(morgan('combined', morganOption));
希望它可以帮助别人:)
推荐阅读
- python-3.x - 如何将 SSLContext 与 Python 请求库一起使用?
- python - 如何使用 Python 将特定列的每周数据转换为每日数据
- pandas - 轴未显示在绘图栏中 kind=bar in pandas
- python - 我已经安装了 IPython,但仍然“没有名为 'IPython' 的模块”
- java - 是否可以运行多个 main 而不会收到异常“正在使用的地址:JVM_Bind”
- javascript - 如何在输入文本上添加“第二个占位符”
- haskell - 过滤来自使用 forkIO 创建的线程的标准输出
- java - Java Spring REST 全部捕获子 URL
- mps - 重建项目时出现 MPS 错误:“x@descriptor 没有输出位置”
- android - ar.js 示例不适用于三星浏览器