Js-log/使用 morgan 和 winston

我们使用 morgan来记录表达式转换:

var morgan  = require('morgan');
morgan('combined');
// a format string
morgan(':remote-addr :method :url :uuid');
// a custom function
morgan(function (req, res) {
return req.method + ' ' + req.url + ' ' + req.uuid;
})

另外,我们使用 winston来记录其他日志记录:

var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'info' }),
new (winston.transports.File)({ filename: '/var/log/log-file.log' })
]
});

有没有办法把两个伐木工人合并在一起?现在的情况是,当 winston写入 /var/log/log-file.log时,morgan写入我的标准输出。

我希望日志记录器文件将组合从表达转换信息,并从其他信息我想(logger.info())。.

95666 次浏览

对于您想要做的事情,本文做得非常好。

Http://tostring.it/2014/06/23/advanced-logging-with-nodejs/

For your specific code you probably need something like this:

var logger = new winston.Logger({
transports: [
new winston.transports.File({
level: 'info',
filename: './logs/all-logs.log',
handleExceptions: true,
json: true,
maxsize: 5242880, //5MB
maxFiles: 5,
colorize: false
}),
new winston.transports.Console({
level: 'debug',
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false
});


logger.stream = {
write: function(message, encoding){
logger.info(message);
}
};


app.use(require("morgan")("combined", { "stream": logger.stream }));

这将设置 Winston 向控制台写入一个日志以及一个文件。然后可以使用最后一个表达式将 Morgan 中间件的输出传递给 Winston。

Update the last line to remove warning

app.use(require("morgan")("combined", { stream: logger.stream }));

打字稿:

let logger = new (winston.Logger)({
exitOnError: false,
level: 'info',
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'app.log'})
]
})


class MyStream {
write(text: string) {
logger.info(text)
}
}
let myStream = new MyStream()
app.use(morgan('tiny', { stream: myStream }));

Morgan 有个坏习惯,在信息结尾写 \n以便让事情井然有序,所以在写给 Winston 之前,你可能想把它删掉。

这可以通过许多不同的方式来完成,比如在 Winston 的格式方面,或者通过更新您的流来不编写 \n

class MyStream {
write(text: string) {
logger.info(text.replace(/\n$/, ''));
}
}
let myStream = new MyStream()
app.use(morgan('tiny', { stream: myStream }));

而不需要创建类的另一种方法是

let logger = new (winston.Logger)({
exitOnError: false,
level: 'info',
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'app.log'})
]
})


const myStream = {
write: (text: string) => {
logger.info(text)
}
}


app.use(morgan('combined', { stream: myStream }));

这个解决方案是从这个 Github 页面 https://github.com/winstonjs/winston/issues/1385分离出来的。然而,需要注意的是,我们的代码之间存在细微的差异。而不是:

app.use(morgan('combined', { myStream }));

I use:

app.use(morgan('combined', { stream: myStream }));

这帮助了我,因为我不太擅长创建类。

将数据记录到 nodejs 后端文件中的最简单的 方法 @ grdon/logger

这里有个例子

 const logger = require('@grdon/logger')({
defaultLogDirectory : __dirname + "/myLogDir",
})
// ...


logger(arg1, 'logfile1.log')
logger([arg1, arg2 ,...], 'lofgfile2.log')

受到这个问题的启发,这是我的易于定制的日志记录器。

import * as winston from "winston";
import * as morgan from "morgan";


export const logger = winston.createLogger({
transports: [
new winston.transports.Console({
level: 'debug',
handleExceptions: true,
format: winston.format.combine(
winston.format.timestamp({ format: 'HH:mm:ss:ms' }),
winston.format.colorize(),
winston.format.printf(
(info) => `${info.timestamp} ${info.level}: ${info.message}`,
),
//  winston.format.simple(),
),
}),
],
exitOnError: false,
});


if (process.env.NODE_ENV === "dev") {
logger.add(
new winston.transports.File({
level: 'info',
filename: './logs/all-logs.log',
handleExceptions: true,
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss',
}),
winston.format.errors({ stack: true }),
winston.format.printf(
(info) => `${info.timestamp} ${info.level}: ${info.message}`,
),
// winston.format.splat(),
// winston.format.json()
),
maxsize: 5242880, //5MB
maxFiles: 5,
}));
}
logger.info("logging started");


app.use(morgan(function (tokens, req, res) {
const msg = [
tokens.method(req, res),
tokens.url(req, res),
tokens.status(req, res),
tokens.res(req, res, 'content-length'), '-',
tokens['response-time'](req, res), 'ms',
].join(' ');
logger.http(msg);
return null;
// return msg;
})
);

样本输出

# console
16:32:30:3230 http: GET /users/614daca689f8773a247af93d 200 417 - 1087.858 ms


# file
2021-09-24 16:40:08 http: GET /users/614daca689f8773a247af93d 200 417 - 856.263 ms