Ts.ED 项目中的日志系统详解

Ts.ED 项目中的日志系统详解

tsed :triangular_ruler: Ts.ED is a Node.js and TypeScript framework on top of Express to write your application with TypeScript (or ES6). It provides a lot of decorators and guideline to make your code more readable and less error-prone. ⭐️ Star to support our work! tsed 项目地址: https://gitcode.com/gh_mirrors/ts/tsed

前言

在现代Web应用开发中,日志系统是不可或缺的基础设施。Ts.ED作为一个优秀的Node.js框架,提供了强大而灵活的日志功能。本文将深入解析Ts.ED的日志系统,帮助开发者更好地理解和使用它。

日志系统概述

Ts.ED内置了一个功能完善的日志系统,基于@tsed/logger包实现。这个日志系统不仅支持基本的日志记录功能,还针对生产环境进行了优化,具有以下特点:

  • 支持多级别日志输出
  • 提供请求上下文日志记录
  • 支持多种日志格式和输出目标
  • 生产环境优化,减少性能开销

安装与基本配置

安装

首先需要安装日志模块:

npm install --save @tsed/logger

基本配置

在Ts.ED项目中,可以通过@Configuration装饰器来配置日志系统:

@Configuration({
  logger: {
    level: "info",  // 日志级别:debug, info, warn, error
    logRequest: true,  // 是否记录请求日志
    requestFields: ["reqId", "method", "url"],  // 请求日志包含的字段
    disableRoutesSummary: false  // 是否禁用路由表显示
  }
})
export class Server {}

日志级别与生产环境建议

Ts.ED支持以下日志级别:

  1. trace - 最详细的日志信息
  2. debug - 调试信息
  3. info - 常规信息
  4. warn - 警告信息
  5. error - 错误信息
  6. fatal - 严重错误信息

生产环境建议

  • 将日志级别设置为info或更高
  • 考虑禁用logRequest以减少性能开销
  • 使用JSON格式的日志输出,便于日志分析工具处理

日志布局与输出目标

日志布局(Layouts)

布局决定了日志的显示格式。Ts.ED支持多种布局:

  1. 基础布局:包含时间戳、级别、类别和日志内容
  2. 彩色布局:在基础布局上添加颜色区分
  3. JSON布局:以JSON格式输出日志,适合生产环境
  4. 模式布局:自定义格式的日志输出

输出目标(Appenders)

Appenders决定了日志的输出目标:

  1. 控制台输出:开发环境常用
  2. 文件输出:支持按大小或日期滚动
  3. 网络服务:支持LogStash、Loggly等日志服务
  4. 消息系统:支持RabbitMQ等消息队列
  5. 通知系统:支持Slack、邮件通知等

在代码中使用日志

服务中注入日志

在服务类中可以通过依赖注入使用日志:

import {Injectable, Inject} from "@tsed/di";
import {Logger} from "@tsed/logger";

@Injectable()
export class MyService {
  @Inject()
  logger: Logger;

  doSomething() {
    this.logger.info("执行操作");
    try {
      // 业务逻辑
    } catch (error) {
      this.logger.error("操作失败", error);
    }
  }
}

请求上下文日志

在处理HTTP请求时,推荐使用请求上下文日志:

import {Controller, Context} from "@tsed/common";
import {Get} from "@tsed/schema";

@Controller("/users")
export class UserController {
  @Get("/")
  getUsers(@Context() ctx: Context) {
    ctx.logger.info("获取用户列表");
    // 业务逻辑
    return users;
  }
}

请求上下文日志的优势

  • 自动关联请求ID,便于追踪
  • 生产环境下会缓存日志直到响应完成
  • 可以记录请求的详细信息

高级配置

生产环境JSON日志配置

import {Env} from "@tsed/core";
import {$log} from "@tsed/logger";

const isProduction = process.env.NODE_ENV === Env.PROD;

if (isProduction) {
  $log.appenders.set("stdout", {
    type: "stdout",
    levels: ["info", "debug"],
    layout: {type: "json"}
  });
  
  $log.appenders.set("stderr", {
    type: "stderr",
    levels: ["error", "warn", "fatal"],
    layout: {type: "json"}
  });
}

自定义日志中间件

可以覆盖默认的日志中间件实现自定义日志格式:

import {OverrideProvider} from "@tsed/di";
import {PlatformLogMiddleware} from "@tsed/common";

@OverrideProvider(PlatformLogMiddleware)
export class CustomLogMiddleware extends PlatformLogMiddleware {
  protected requestToObject(ctx: Context) {
    const request = ctx.getRequest();
    return {
      method: request.method,
      url: request.url,
      ip: request.ip,
      // 其他自定义字段
    };
  }
}

日志敏感信息处理

在生产环境中,需要注意保护敏感信息:

@OverrideProvider(PlatformLogMiddleware)
export class SecureLogMiddleware extends PlatformLogMiddleware {
  private redactSensitiveData(data: any) {
    const sensitiveFields = ["password", "token", "creditCard"];
    // 实现敏感信息过滤逻辑
    return processedData;
  }

  protected requestToObject(ctx: Context) {
    const request = ctx.getRequest();
    return {
      ...super.requestToObject(ctx),
      body: this.redactSensitiveData(request.body)
    };
  }
}

日志系统关闭

在应用退出时,应该正确关闭日志系统:

import {$log} from "@tsed/logger";

process.on("SIGINT", async () => {
  await $log.shutdown();
  process.exit(0);
});

总结

Ts.ED的日志系统提供了从开发到生产环境所需的全套功能。通过合理配置和使用,可以:

  1. 在开发阶段获得详细的调试信息
  2. 在生产环境保持高性能的同时记录关键信息
  3. 方便地与各种日志分析系统集成
  4. 保证敏感信息的安全性

掌握这些日志功能,将大大提升应用的可靠性和可维护性。

tsed :triangular_ruler: Ts.ED is a Node.js and TypeScript framework on top of Express to write your application with TypeScript (or ES6). It provides a lot of decorators and guideline to make your code more readable and less error-prone. ⭐️ Star to support our work! tsed 项目地址: https://gitcode.com/gh_mirrors/ts/tsed

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尤瑾竹Emery

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值