@lark-apaas/nestjs-logger 0.1.0-alpha.2 → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,320 @@
1
+ # NestJS Logger
2
+
3
+ 基于 Pino 的高性能 NestJS 日志库,支持请求追踪、结构化日志和敏感信息脱敏。
4
+
5
+ ## 功能特性
6
+
7
+ - 基于 Pino 的高性能日志记录
8
+ - 自动 HTTP 请求追踪
9
+ - 请求和响应体日志记录(可配置)
10
+ - 敏感字段自动脱敏
11
+ - 支持多日志级别
12
+ - 独立的 trace 日志文件
13
+ - 请求上下文传递
14
+
15
+ ## 安装
16
+
17
+ ```bash
18
+ npm install @lark-apaas/nestjs-logger
19
+ ```
20
+
21
+ ## 基本使用
22
+
23
+ ### 1. 导入模块
24
+
25
+ ```typescript
26
+ import { Module } from '@nestjs/common';
27
+ import { LoggerModule } from '@lark-apaas/nestjs-logger';
28
+
29
+ @Module({
30
+ imports: [LoggerModule],
31
+ })
32
+ export class AppModule {}
33
+ ```
34
+
35
+ ### 2. 使用 Logger
36
+
37
+ ```typescript
38
+ import { Injectable, Logger } from '@nestjs/common';
39
+
40
+ @Injectable()
41
+ export class MyService {
42
+ private readonly logger = new Logger(MyService.name);
43
+
44
+ doSomething() {
45
+ this.logger.log('This is an info log');
46
+ this.logger.debug('This is a debug log');
47
+ this.logger.warn('This is a warning');
48
+ this.logger.error('This is an error', error.stack);
49
+ }
50
+ }
51
+ ```
52
+
53
+ ## 环境变量配置
54
+
55
+ ### 基础配置
56
+
57
+ ```bash
58
+ # 日志级别: trace, debug, info, warn, error, fatal, silent
59
+ # 注意:HTTP 请求追踪日志使用 verbose 级别(对应 Pino 的 trace)
60
+ # 生产环境默认为 info,不会打印 verbose 级别的日志
61
+ LOGGER_LEVEL=info
62
+
63
+ # 日志目录
64
+ LOG_DIR=logs
65
+
66
+ # Node 环境(默认:开发环境使用 debug,生产环境使用 info)
67
+ NODE_ENV=production
68
+ ```
69
+
70
+ ### 请求/响应体日志配置
71
+
72
+ ```bash
73
+ # 启用请求体日志(默认:false)
74
+ LOG_REQUEST_BODY=true
75
+
76
+ # 启用响应体日志(默认:false)
77
+ # 注意:仅记录 Content-Type 为 JSON 的响应
78
+ LOG_RESPONSE_BODY=true
79
+
80
+ # 注意:即使启用了请求/响应体日志,也需要将日志级别设置为 verbose 才能实际输出
81
+ # 因为 HTTP 请求追踪日志使用的是 verbose 级别
82
+ LOGGER_LEVEL=verbose
83
+
84
+ # 日志体最大长度,超过会截断(默认:不限制)
85
+ # 不设置此环境变量时,不会进行截断
86
+ LOG_MAX_BODY_LENGTH=10000
87
+
88
+ # 敏感字段配置(逗号分隔,默认包含常见敏感字段)
89
+ LOG_SENSITIVE_FIELDS=password,token,secret,authorization,cookie,apiKey,accessToken,refreshToken
90
+ ```
91
+
92
+ ## 请求/响应体日志
93
+
94
+ ### 日志级别说明
95
+
96
+ HTTP 请求追踪日志使用 **`verbose` 级别**(对应 Pino 的 `trace` 级别),这意味着:
97
+
98
+ - **生产环境默认不打印**:生产环境默认日志级别为 `info`,不会输出 verbose 级别的日志
99
+ - **需要显式启用**:要查看 HTTP 请求追踪日志,需要将 `LOGGER_LEVEL` 设置为 `verbose`
100
+ - **细粒度控制**:可以通过日志级别控制是否打印请求追踪,而无需修改 `LOG_REQUEST_BODY` 和 `LOG_RESPONSE_BODY` 配置
101
+
102
+ ### 启用方式
103
+
104
+ 通过环境变量启用:
105
+
106
+ ```bash
107
+ # 方式一:仅启用 HTTP 请求追踪(不包含 body)
108
+ LOGGER_LEVEL=verbose
109
+
110
+ # 方式二:启用 HTTP 请求追踪 + 请求/响应体
111
+ LOGGER_LEVEL=verbose
112
+ LOG_REQUEST_BODY=true
113
+ LOG_RESPONSE_BODY=true
114
+ ```
115
+
116
+ ### 重要说明
117
+
118
+ 1. **仅记录 JSON 响应**:响应体日志只会记录 Content-Type 为 JSON 格式的响应(如 `application/json`、`application/vnd.api+json` 等),其他类型(如文件下载、HTML、图片等)不会被记录。
119
+
120
+ 2. **默认不限制长度**:如果不设置 `LOG_MAX_BODY_LENGTH` 环境变量,日志体不会被截断。建议在生产环境设置合理的限制值。
121
+
122
+ 3. **自动脱敏**:所有敏感字段会自动被替换为 `***MASKED***`。
123
+
124
+ ### 日志输出示例
125
+
126
+ #### 请求日志(包含请求体)
127
+
128
+ ```json
129
+ {
130
+ "level": "info",
131
+ "time": 1234567890,
132
+ "msg": "HTTP request started",
133
+ "method": "POST",
134
+ "path": "/api/users",
135
+ "trace_id": "req-123-456",
136
+ "user_id": "user-001",
137
+ "requestBody": {
138
+ "username": "john_doe",
139
+ "email": "john@example.com",
140
+ "password": "***MASKED***"
141
+ },
142
+ "queryParams": {
143
+ "filter": "active"
144
+ }
145
+ }
146
+ ```
147
+
148
+ #### 响应日志(包含响应体)
149
+
150
+ ```json
151
+ {
152
+ "level": "info",
153
+ "time": 1234567890,
154
+ "msg": "HTTP request completed",
155
+ "method": "POST",
156
+ "path": "/api/users",
157
+ "trace_id": "req-123-456",
158
+ "statusCode": 201,
159
+ "durationMs": 125,
160
+ "responseBody": {
161
+ "id": "user-123",
162
+ "username": "john_doe",
163
+ "email": "john@example.com",
164
+ "accessToken": "***MASKED***"
165
+ }
166
+ }
167
+ ```
168
+
169
+ ## 敏感字段脱敏
170
+
171
+ ### 默认脱敏字段
172
+
173
+ 以下字段会自动脱敏(不区分大小写,支持部分匹配):
174
+
175
+ - password
176
+ - token
177
+ - secret
178
+ - authorization
179
+ - cookie
180
+ - apiKey
181
+ - accessToken
182
+ - refreshToken
183
+
184
+ ### 自定义敏感字段
185
+
186
+ 通过环境变量配置:
187
+
188
+ ```bash
189
+ LOG_SENSITIVE_FIELDS=password,token,secret,myCustomSecret,privateKey
190
+ ```
191
+
192
+ ### 脱敏规则
193
+
194
+ - 字段匹配不区分大小写
195
+ - 支持部分匹配(例如:`accessToken` 会匹配 `token`)
196
+ - 敏感字段值会被替换为 `***MASKED***`
197
+ - 嵌套对象中的敏感字段也会被脱敏
198
+
199
+ ### 示例
200
+
201
+ ```typescript
202
+ // 原始数据
203
+ {
204
+ username: "john",
205
+ password: "secret123",
206
+ userToken: "abc123",
207
+ nested: {
208
+ apiKey: "key123"
209
+ }
210
+ }
211
+
212
+ // 脱敏后
213
+ {
214
+ username: "john",
215
+ password: "***MASKED***",
216
+ userToken: "***MASKED***", // 匹配 'token'
217
+ nested: {
218
+ apiKey: "***MASKED***"
219
+ }
220
+ }
221
+ ```
222
+
223
+ ## 数据截断
224
+
225
+ 默认情况下,不会对日志体进行截断。当设置 `LOG_MAX_BODY_LENGTH` 环境变量后,如果请求/响应体超过指定长度,会自动截断:
226
+
227
+ ```json
228
+ {
229
+ "responseBody": {
230
+ "_truncated": true,
231
+ "_originalLength": 50000,
232
+ "_data": "{ 前 10000 个字符... }..."
233
+ }
234
+ }
235
+ ```
236
+
237
+ **建议**:在生产环境设置合理的限制值(如 10000),避免单条日志过大。
238
+
239
+ ## 日志级别映射
240
+
241
+ NestJS LoggerService 级别到 Pino 级别的映射:
242
+
243
+ - `fatal` → `fatal`
244
+ - `error` → `error`
245
+ - `warn` → `warn`
246
+ - `log` → `info`
247
+ - `debug` → `debug`
248
+ - `verbose` → `trace`
249
+
250
+ ## 日志文件
251
+
252
+ 日志会写入以下文件(默认在 `logs/` 目录):
253
+
254
+ - `app.log` - 应用日志
255
+ - `trace.log` - HTTP 请求追踪日志
256
+
257
+ ## 注意事项
258
+
259
+ ### 安全性
260
+
261
+ 1. **生产环境默认不打印 HTTP 追踪日志**:由于使用 verbose 级别,生产环境(info 级别)默认不会输出
262
+ 2. **按需启用**:需要查看请求追踪时,将 LOGGER_LEVEL 设置为 verbose
263
+ 3. 确保敏感字段配置完整,覆盖所有可能的敏感数据
264
+ 4. 定期审查日志内容,确保没有遗漏的敏感信息
265
+ 5. **仅 JSON 响应会被记录**,文件下载、HTML 等其他类型不会被记录
266
+
267
+ ### 性能
268
+
269
+ 1. verbose 级别会输出所有 HTTP 请求日志,可能影响性能
270
+ 2. 开启请求/响应体日志会增加日志体积和 I/O 开销
271
+ 3. 大对象的序列化和脱敏会影响性能
272
+ 4. 建议在开发/测试环境使用,生产环境按需临时启用
273
+
274
+ ### 存储
275
+
276
+ 1. 注意日志文件大小,建议配置日志轮转
277
+ 2. verbose 级别 + 请求/响应体日志会显著增加日志量
278
+ 3. 建议设置 `LOG_MAX_BODY_LENGTH` 限制单条日志大小(默认不限制)
279
+
280
+ ## 最佳实践
281
+
282
+ ### 开发环境
283
+
284
+ ```bash
285
+ NODE_ENV=development
286
+ # 使用 verbose 级别查看 HTTP 请求追踪
287
+ LOGGER_LEVEL=verbose
288
+ LOG_REQUEST_BODY=true
289
+ LOG_RESPONSE_BODY=true
290
+ # 开发环境可以不限制长度,或设置较大值
291
+ # LOG_MAX_BODY_LENGTH=50000
292
+ ```
293
+
294
+ ### 生产环境
295
+
296
+ ```bash
297
+ NODE_ENV=production
298
+ # 生产环境使用 info 级别,不会打印 HTTP 请求追踪日志
299
+ LOGGER_LEVEL=info
300
+ # 这两个配置可以保留,只有当 LOGGER_LEVEL=verbose 时才会生效
301
+ LOG_REQUEST_BODY=false
302
+ LOG_RESPONSE_BODY=false
303
+ ```
304
+
305
+ ### 故障排查
306
+
307
+ 临时启用详细日志:
308
+
309
+ ```bash
310
+ NODE_ENV=production
311
+ # 临时开启 verbose 级别查看 HTTP 请求追踪
312
+ LOGGER_LEVEL=verbose
313
+ LOG_REQUEST_BODY=true
314
+ LOG_RESPONSE_BODY=true
315
+ LOG_MAX_BODY_LENGTH=10000 # 建议设置限制,避免日志过大
316
+ ```
317
+
318
+ ## License
319
+
320
+ MIT
package/dist/index.cjs CHANGED
@@ -14681,7 +14681,7 @@ __name(sanitizeValue, "sanitizeValue");
14681
14681
  // src/module.ts
14682
14682
  var import_common5 = require("@nestjs/common");
14683
14683
  var import_core = require("@nestjs/core");
14684
- var import_config2 = __toESM(require_config2(), 1);
14684
+ var import_config3 = __toESM(require_config2(), 1);
14685
14685
 
14686
14686
  // src/config/logger.config.ts
14687
14687
  var import_config = __toESM(require_config2(), 1);
@@ -14703,14 +14703,21 @@ function normalizeLevel(level) {
14703
14703
  __name(normalizeLevel, "normalizeLevel");
14704
14704
  var logger_config_default = (0, import_config.registerAs)("logger", () => {
14705
14705
  const level = normalizeLevel(process.env.LOGGER_LEVEL || (process.env.NODE_ENV === "production" ? "info" : "debug"));
14706
+ const maxBodyLengthEnv = process.env.LOG_MAX_BODY_LENGTH;
14707
+ const maxBodyLength = maxBodyLengthEnv ? Number(maxBodyLengthEnv) : null;
14706
14708
  return {
14707
14709
  level,
14708
- logDir: process.env.LOG_DIR || "logs"
14710
+ logDir: process.env.LOG_DIR || "logs",
14711
+ logRequestBody: process.env.LOG_REQUEST_BODY === "true",
14712
+ logResponseBody: process.env.LOG_RESPONSE_BODY === "true",
14713
+ maxBodyLength,
14714
+ sensitiveFields: (process.env.LOG_SENSITIVE_FIELDS || "password,token,secret,authorization,cookie,apiKey,accessToken,refreshToken").split(",").map((f) => f.trim())
14709
14715
  };
14710
14716
  });
14711
14717
 
14712
14718
  // src/interceptor/logging.interceptor.ts
14713
14719
  var import_common3 = require("@nestjs/common");
14720
+ var import_config2 = __toESM(require_config2(), 1);
14714
14721
  var import_operators = __toESM(require_operators(), 1);
14715
14722
  function _ts_decorate3(decorators, target, key, desc) {
14716
14723
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -14735,9 +14742,11 @@ var LoggingInterceptor = class {
14735
14742
  }
14736
14743
  traceLogger;
14737
14744
  requestContext;
14738
- constructor(traceLogger, requestContext) {
14745
+ config;
14746
+ constructor(traceLogger, requestContext, config) {
14739
14747
  this.traceLogger = traceLogger;
14740
14748
  this.requestContext = requestContext;
14749
+ this.config = config;
14741
14750
  }
14742
14751
  intercept(context, next) {
14743
14752
  if (context.getType() !== "http") {
@@ -14756,7 +14765,6 @@ var LoggingInterceptor = class {
14756
14765
  const baseMeta = {
14757
14766
  method,
14758
14767
  path: url,
14759
- requestId: req.requestId ?? req.id,
14760
14768
  trace_id: req.requestId ?? req.id,
14761
14769
  user_id: req.userContext?.userId ?? null,
14762
14770
  tenant_id: req.userContext?.tenantId ?? null,
@@ -14764,15 +14772,32 @@ var LoggingInterceptor = class {
14764
14772
  ip: req.ip ?? null,
14765
14773
  pid: process.pid
14766
14774
  };
14767
- this.traceLogger.log("HTTP request started", baseMeta, "HTTP");
14768
- return next.handle().pipe((0, import_operators.tap)(() => {
14775
+ const requestMeta = {
14776
+ ...baseMeta
14777
+ };
14778
+ if (this.config.logRequestBody && req.body) {
14779
+ requestMeta["requestBody"] = this.sanitizeAndTruncate(req.body);
14780
+ }
14781
+ if (this.config.logRequestBody && Object.keys(req.query || {}).length > 0) {
14782
+ requestMeta["queryParams"] = this.sanitizeAndTruncate(req.query);
14783
+ }
14784
+ this.traceLogger.verbose?.("HTTP request started", requestMeta, "HTTP");
14785
+ return next.handle().pipe((0, import_operators.tap)((responseData) => {
14769
14786
  const durationMs = Date.now() - startedAt;
14770
14787
  const statusCode = res.statusCode;
14771
- this.traceLogger.log("HTTP request completed", {
14788
+ const responseMeta = {
14772
14789
  ...baseMeta,
14773
14790
  statusCode,
14774
14791
  durationMs
14775
- }, "HTTP");
14792
+ };
14793
+ if (this.config.logResponseBody && responseData !== void 0) {
14794
+ const contentType = res.getHeader("content-type");
14795
+ const isJsonResponse = this.isJsonContentType(contentType);
14796
+ if (isJsonResponse) {
14797
+ responseMeta["responseBody"] = this.sanitizeAndTruncate(responseData);
14798
+ }
14799
+ }
14800
+ this.traceLogger.verbose?.("HTTP request completed", responseMeta, "HTTP");
14776
14801
  }), (0, import_operators.catchError)((error) => {
14777
14802
  const durationMs = Date.now() - startedAt;
14778
14803
  const statusCode = res.statusCode >= 400 ? res.statusCode : 500;
@@ -14789,14 +14814,78 @@ var LoggingInterceptor = class {
14789
14814
  throw error;
14790
14815
  }));
14791
14816
  }
14817
+ /**
14818
+ * 对数据进行脱敏和截断处理
14819
+ */
14820
+ sanitizeAndTruncate(data) {
14821
+ try {
14822
+ const sanitized = this.maskSensitiveFields(data);
14823
+ if (this.config.maxBodyLength === null) {
14824
+ return sanitized;
14825
+ }
14826
+ const jsonStr = JSON.stringify(sanitized);
14827
+ if (jsonStr.length > this.config.maxBodyLength) {
14828
+ return {
14829
+ _truncated: true,
14830
+ _originalLength: jsonStr.length,
14831
+ _data: jsonStr.substring(0, this.config.maxBodyLength) + "..."
14832
+ };
14833
+ }
14834
+ return sanitized;
14835
+ } catch (error) {
14836
+ return {
14837
+ _error: "Failed to serialize data",
14838
+ _message: error instanceof Error ? error.message : String(error)
14839
+ };
14840
+ }
14841
+ }
14842
+ /**
14843
+ * 判断是否是 JSON 响应类型
14844
+ */
14845
+ isJsonContentType(contentType) {
14846
+ if (typeof contentType !== "string") {
14847
+ return false;
14848
+ }
14849
+ const contentTypeLower = contentType.toLowerCase();
14850
+ return contentTypeLower.includes("application/json") || contentTypeLower.includes("application/vnd.api+json") || contentTypeLower.includes("+json");
14851
+ }
14852
+ /**
14853
+ * 脱敏敏感字段
14854
+ */
14855
+ maskSensitiveFields(data) {
14856
+ if (data === null || data === void 0) {
14857
+ return data;
14858
+ }
14859
+ if (Array.isArray(data)) {
14860
+ return data.map((item) => this.maskSensitiveFields(item));
14861
+ }
14862
+ if (typeof data === "object") {
14863
+ const result = {};
14864
+ for (const [key, value] of Object.entries(data)) {
14865
+ const lowerKey = key.toLowerCase();
14866
+ const isSensitive = this.config.sensitiveFields.some((field) => lowerKey.includes(field.toLowerCase()));
14867
+ if (isSensitive) {
14868
+ result[key] = "***MASKED***";
14869
+ } else if (typeof value === "object" && value !== null) {
14870
+ result[key] = this.maskSensitiveFields(value);
14871
+ } else {
14872
+ result[key] = value;
14873
+ }
14874
+ }
14875
+ return result;
14876
+ }
14877
+ return data;
14878
+ }
14792
14879
  };
14793
14880
  LoggingInterceptor = _ts_decorate3([
14794
14881
  (0, import_common3.Injectable)(),
14795
14882
  _ts_param2(0, (0, import_common3.Inject)(TRACE_LOGGER)),
14883
+ _ts_param2(2, (0, import_common3.Inject)(logger_config_default.KEY)),
14796
14884
  _ts_metadata2("design:type", Function),
14797
14885
  _ts_metadata2("design:paramtypes", [
14798
14886
  typeof import_common3.LoggerService === "undefined" ? Object : import_common3.LoggerService,
14799
- typeof RequestContextService === "undefined" ? Object : RequestContextService
14887
+ typeof RequestContextService === "undefined" ? Object : RequestContextService,
14888
+ typeof import_config2.ConfigType === "undefined" ? Object : import_config2.ConfigType
14800
14889
  ])
14801
14890
  ], LoggingInterceptor);
14802
14891
 
@@ -14914,7 +15003,7 @@ LoggerModule = _ts_decorate5([
14914
15003
  (0, import_common5.Global)(),
14915
15004
  (0, import_common5.Module)({
14916
15005
  imports: [
14917
- import_config2.ConfigModule.forFeature(logger_config_default)
15006
+ import_config3.ConfigModule.forFeature(logger_config_default)
14918
15007
  ],
14919
15008
  providers: [
14920
15009
  RequestContextService,