NodeJS 如何用winston做关联Id?

1tu0hz3e  于 2023-02-18  发布在  Node.js
关注(0)|答案(3)|浏览(147)

我在nodejs应用程序中使用Winston。

const winston = require('winston');
const logger = winston.createLogger({
    transports: [
        new winston.transports.Console()
    ]
});

logger.info('What rolls down stairs');

我想添加到日志关联ID,但不想每次都写入

logger.info('What rolls down stairs', correlationId);

我希望Winston能做到这一点。对于每个日志,我都希望获得correlationId作为函数的结果,这样我就可以将correlationId发送给用户(而不仅仅是输出到控制台)。

const correlationId = logger.info('blabla')

有可能和温斯顿一起做吗?

imzjd6km

imzjd6km1#

如果这是Express应用程序,请按照以下步骤操作。

  • 安装中间件(可以安装此npm package
  • 在日志文件中,添加以下代码:
const correlator = require('express-correlation-id');

// winston format
winston.format((info) => {
  info.correlationId = correlator.getId();
  return info;
})()

它应该是这样的:

const winston = require('winston');
const correlator = require('express-correlation-id');

const logger = winston.createLogger({
    format: winston.format.combine(
        winston.format((info) => {
            info.correlationId = correlator.getId();
            return info;
        })(),
        winston.format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss',
        }),
        winston.format.errors({ stack: true }),
        winston.format.splat(),
        winston.format.json()
    ),
    exitOnError: false,
    defaultMeta: {
      // add configuration (https://github.com/winstonjs/winston)
    },
    transports: [
        new winston.transports.File({
            // for the errors (https://github.com/winstonjs/winston)
        }),
        new winston.transports.File({
            // everything else (https://github.com/winstonjs/winston)
        }),
    ],
});
t1rydlwq

t1rydlwq2#

要在Winston中创建correlationId并默认设置每个日志,您需要使用defaultMeta

var correlationId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
const winston = require('winston');
const logger = winston.createLogger({
defaultMeta: { correlationId },
    transports: [
        new winston.transports.Console()
    ]
});

logger.info('What rolls down stairs');
z9smfwbn

z9smfwbn3#

import { v4 as uuidv4 } from "uuid";

export async function withCorrelationId(message:string) {
    const id = uuidv4()

    logger.info({
        message,
        id,
    });

    return id
}

相关问题