如何为日志添加上下文信息(如 request-id、user-id)以便追踪?

解读

在国内高并发、微服务盛行的场景下,一条 SQL 日志如果只有“select * from user where id = ?”,一旦接口超时或订单异常,几乎无法定位是哪一次请求、哪位用户触发的。面试官问“如何为 MikroORM 日志添加上下文”,考察的并不是“会写 logger.info”,而是:

  1. 是否了解 MikroORM 的日志钩子与事件系统;
  2. 是否能把 Node.js 的异步上下文(AsyncLocalStorage)与 ORM 生命周期打通,做到“一次请求、一个 traceId、全链路穿透”;
  3. 是否能在不污染业务代码的前提下,把 userId、tenantId 等动态字段注入到每条日志里;
  4. 是否知道生产环境如何落盘、采样、脱敏,满足国内等保与审计要求。

知识点

  1. MikroORM 日志接口

    • logger 配置项:可注入自定义 Logger,接收 message: string, level: 'query'|'info'|'warning'|'error', 以及 QueryData(sql、params、duration、connection 等)。
    • LoggerNamespace:支持按 namespace 过滤,方便把 SQL 与业务日志分开。
  2. Node.js 异步上下文

    • AsyncLocalStorage(ALS)是官方推荐的“请求级上下文”方案,比 domain 更轻量,比 cls-hooked 更稳定。
    • 在 Nestjs/Express 中间件里把 traceId、userId 写入 ALS,后续任何地方(包括 ORM 钩子)均可同步取出。
  3. 日志格式与链路追踪

    • 国内主流:阿里云 SLS、腾讯云 CLS、ELK、Loki,均要求 JSON 格式且字段固定(@timestamp, traceId, userId, sql, cost)。
    • 需避免把密码、身份证写入 params,要做脱敏。
  4. 事务与连接池

    • MikroORM 的 Unit of Work 在一次事务里可能产生数十条 SQL,需要保证这数十条日志拥有相同的 traceId。
    • 连接池复用会导致 connection.id 变化,不能把它当 traceId,只能当辅助字段。
  5. 性能与采样

    • 高并发场景下全量打印 SQL 会打爆日志系统,需按“错误必留、慢查询必留、正常查询按 1% 采样”策略落地。

答案

下面给出可直接落地的“三步法”,基于 AsyncLocalStorage + MikroORM 自定义 Logger,不改动任何业务 SQL,即可在每条日志里自动输出 traceId 与 userId。

第一步:创建请求上下文工具(request-context.ts)

import { AsyncLocalStorage } from 'async_hooks';

export interface IRequestContext {
  traceId: string;
  userId?: string;
  tenantId?: string;
}

const als = new AsyncLocalStorage<IRequestContext>();

export const runWithContext = (ctx: IRequestContext, fn: () => void) => {
  als.run(ctx, fn);
};

export const getContext = (): IRequestContext | undefined => {
  return als.getStore();
};

第二步:实现 MikroORM 自定义 Logger(mikro-logger.ts)

import { Logger, LoggerNamespace, QueryData } from '@mikro-orm/core';
import { getContext } from './request-context';
import { createLogger, format, transports } from 'winston';

const winston = createLogger({
  format: format.combine(
    format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
    format.json()
  ),
  transports: [new transports.Console()],
});

export class ContextLogger implements Logger {
  static logger = winston;

  log(namespace: LoggerNamespace, message: string, data?: QueryData) {
    const ctx = getContext() || {};
    const { traceId = '-', userId = '-' } = ctx;

    // 脱敏:如果 SQL 包含密码、身份证字段,把 params 掩码
    const safeParams = data?.params?.map((p: any) =>
      typeof p === 'string' && p.length > 32 ? p.slice(0, 8) + '***' : p
    );

    ContextLogger.logger.info({
      traceId,
      userId,
      namespace,
      sql: data?.sql || message,
      params: safeParams,
      duration: data?.duration,
      connection: data?.connection?.id,
    });
  }

  error(namespace: LoggerNamespace, message: string, data?: QueryData) {
    const ctx = getContext() || {};
    ContextLogger.logger.error({
      traceId: ctx.traceId || '-',
      userId: ctx.userId || '-',
      namespace,
      sql: data?.sql || message,
      params: data?.params,
      duration: data?.duration,
    });
  }

  warn(namespace: LoggerNamespace, message: string, data?: QueryData) {
    this.log(namespace, message, data);
  }
}

第三步:在 Nestjs 中间件里绑定上下文(app.module.ts 或 main.ts)

import { MikroORM, Options } from '@mikro-orm/core';
import { ContextLogger } from './mikro-logger';
import { runWithContext } from './request-context';
import { randomUUID } from 'crypto';

// 1. 把自定义 logger 注入 ORM
export const ormConfig: Options = {
  type: 'mysql',
  dbName: 'test',
  entities: [__dirname + '/**/*.entity.js'],
  logger: (msg) => new ContextLogger(),
};

// 2. 在请求入口写入 ALS
app.use((req, res, next) => {
  const traceId = req.headers['x-trace-id'] || randomUUID();
  const userId = req.headers['x-user-id'] as string; // 从网关或 JWT 解析
  runWithContext({ traceId, userId }, () => next());
});

验证:
发起一次 GET /order/123,日志输出示例

{"timestamp":"2024-06-01 14:23:45.678","traceId":"a9b8c7d6","userId":"10086","namespace":"query","sql":"select * from `order` where `id` = ?","params":[123],"duration":12,"connection":42}

整条链路(控制器 → 服务 → ORM → SQL)全部带 traceId,再接入 SkyWalking/Zipkin 即可实现分布式追踪。

拓展思考

  1. 多租户场景下,租户 ID 往往存在 JWT 里,如何在 ORM 日志之外再打印“当前库名”或“schema”?
    答:在 ContextLogger 里把 tenantId 一并取出,同时把 data.connection.getConnection().getDatabaseName() 作为字段写入,方便按租户过滤慢 SQL。

  2. 国内金融级合规要求“敏感字段脱敏”,但参数是二进制流怎么办?
    答:在 ContextLogger 里对 data.sql 做正则白名单,只有 select|insert|update|delete 才打印,参数统一输出 <binary>,避免泄露。

  3. 日志量太大,如何按“错误 100%、慢查询 100%、正常查询 1%”采样?
    答:在 ContextLogger.log 里先判断 data.duration > 500 或 namespace === 'error',否则 Math.random() < 0.01 才落盘,同时把采样率作为字段 sampleRate: 0.01 写入,方便后续加权统计。

  4. 使用 MongoDB 驱动时,MikroORM 日志里没有 connection.id,如何区分副本集节点?
    答:在 ContextLogger 构造函数里注入 orm 实例,通过 orm.em.getConnection().getClient().topology.s.options.replicaSet 拿到副本集名称,作为 replicaSet 字段写入日志。

  5. 想在日志里再增加“业务链路码”如 orderNo,但只在下单方法里才有,怎么办?
    答:把 AsyncLocalStorage 的上下文设计成可写:

    export const appendContext = (extra: Partial<IRequestContext>) => {
      const old = getContext() || {};
      als.enterWith({ ...old, ...extra });
    };
    

    在下单服务里 appendContext({ orderNo: 'DD2024060112345' }),ContextLogger 自动透出,无需修改 SQL 代码。