如何使用 "winston" 将服务器收到的每个请求记录到 Loggly

How to use "winston" to log every request that server receive to Loggly

我正在使用 winston with winston-loggly-bulk to log messages to Loggly. I want to log all requests that my server receives. With morgan,我会这样做:

app.use(morgan('dev'));

我们可以用 winston 做类似的事情吗?

为了让它工作,我合并了 winstonmorgan 包。

1.步骤

创建一个 logger,您将在服务器中使用它来将消息记录到 Loggly。为此,您可以使用 winstonwinston-loggly-bulk。您可以创建自定义格式的日志记录,我还添加了部分代码来检查环境是否不是 production,在这种情况下,它也会在控制台中记录消息(开发的良好实践).

const winston = require('winston');
const { Loggly } = require('winston-loggly-bulk');

// Levels: ['error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly']
const logger = winston.createLogger();

logger.add(new Loggly({
  token: process.env.LOGGLY_TOKEN,
  subdomain: process.env.LOGGLY_SUBDOMAIN,
  tags: [process.env.NODE_ENV, process.env.SERVER_INSTANCE],
  json: true
}));

const custom_format = winston.format.printf(({ level, message, timestamp, ...metadata }) => `${level}: ${message}\n${(metadata && Object.keys(metadata).length) ? JSON.stringify(metadata, null, 4) : ''}`);

//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} {...rest}`
//
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: custom_format
  }));
}

module.exports = {
  logger
};

2。步骤

在您将使用 morgan 记录请求的部分代码中导入您的 logger,并将 morgan 消息流式传输到 logger。同样,我检查了环境是否为 production,因为我不想在 development.

中记录请求
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
} else {
  app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :response-time ms', { stream: { write: message => logger.log('info', message.trim(), { tags: ['http'] }) } }));
}