mcpField
S
structured-logging-standardizer

structured-logging-standardizer

github.com/patricio0312rev开发63258 次安装41 周前更新
代码仓库

关于 structured-logging-standardizer

用于实现一致、可查询且可关联的日志的开发技能,面向需要统一应用日志规范的团队。它提供日志字段规范、请求 ID 中间件和标准化记录器的实现示例。

主要功能

  1. 01定义结构化日志字段规范
  2. 02生成或沿用请求 ID
  3. 03在响应头中返回请求 ID
  4. 04提供标准化日志记录器
  5. 05采用一致字段名记录上下文

适用场景

  1. 01统一多个服务的日志格式
  2. 02关联请求与对应日志
  3. 03按结构化字段查询日志
  4. 04为日志添加服务和环境信息

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/patricio0312rev/skills --skill structured-logging-standardizer

安装后在 Claude Code 中输入/structured-logging-standardizer确认已加载。

详细介绍

结构化日志标准化

实现一致、可查询且可关联的日志。

日志架构

interface LogEntry {
  timestamp: string; // ISO 8601
  level: "debug" | "info" | "warn" | "error" | "fatal";
  message: string;
  service: string;
  environment: string;

  // Request context
  requestId?: string;
  traceId?: string;
  userId?: string;

  // Additional context
  [key: string]: any;
}

请求 ID 中间件

import { v4 as uuidv4 } from "uuid";

app.use((req, res, next) => {
  // Generate or use existing request ID
  req.id = req.headers["x-request-id"] || uuidv4();

  // Add to response headers
  res.setHeader("x-request-id", req.id);

  // Store in async local storage
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore()?.set("requestId", req.id);
    next();
  });
});

// Logger with request context
const logger = pino({
  mixin() {
    return {
      requestId: asyncLocalStorage.getStore()?.get("requestId"),
    };
  },
});

标准化日志记录器

class StandardLogger {
  private logger = pino();

  info(message: string, context?: Record<string, any>) {
    this.logger.info(
      {
        ...this.getContext(),
        ...context,
      },
      message
    );
  }

  error(message: string, error?: Error, context?: Record<string, any>) {
    this.logger.error(
      {
        ...this.getContext(),
        ...context,
        error: {
          message: error?.message,
          stack: error?.stack,
          name: error?.name,
        },
      },
      message
    );
  }

  private getContext() {
    return {
      requestId: asyncLocalStorage.getStore()?.get("requestId"),
      userId: asyncLocalStorage.getStore()?.get("userId"),
    };
  }
}

最佳实践

// ✅ DO: Structured fields
logger.info({ userId: '123', action: 'purchase', amount: 99.99 }, 'Purchase completed');

// ❌ DON'T: String interpolation
logger.info(\`User 123 purchased for $99.99\`);

// ✅ DO: Consistent field names
logger.info({ duration_ms: 150 }, 'Request completed');

// ❌ DON'T: Inconsistent naming
logger.info({ durationMs: 150 }, 'Request done');

输出检查清单

  • 请求 ID 中间件
  • 结构化日志架构
  • 关联 ID
  • 标准化日志记录器
  • 已记录最佳实践 ENDFILE

评论

支持 Markdown