@buka/nestjs-kit 4.0.0 → 4.1.2

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/docs/logger.md ADDED
@@ -0,0 +1,289 @@
1
+ # LoggerModule — 日志模块
2
+
3
+ ## 概述
4
+
5
+ `LoggerModule` 提供统一的日志方案,基于 [nestjs-pino](https://github.com/iamolegga/nestjs-pino) 和 [pino](https://github.com/pinojs/pino) 构建。预配置 Grafana/Loki 友好的 JSON 日志格式,自动注入服务元数据(服务名、环境、版本号)。
6
+
7
+ 模块核心能力:
8
+
9
+ - 开箱即用的 JSON 日志,无缝对接 Grafana/Loki
10
+ - 自动注入 `service`、`environment`、`version` 元数据
11
+ - 开发模式 `pino-pretty` 彩色输出
12
+ - `@InjectLogger()` 装饰器,自动以类名为日志上下文
13
+ - 支持同步和异步两种注册方式
14
+ - 可配合 `@buka/nestjs-config` 使用
15
+
16
+ ```typescript
17
+ import { LoggerModule, Logger, InjectLogger } from '@buka/nestjs-kit'
18
+ ```
19
+
20
+ ## 模块配置
21
+
22
+ ### register(同步注册)
23
+
24
+ 直接传入配置对象:
25
+
26
+ ```typescript
27
+ import { Module } from '@nestjs/common'
28
+ import { LoggerModule } from '@buka/nestjs-kit'
29
+
30
+ @Module({
31
+ imports: [
32
+ LoggerModule.register({
33
+ serviceName: 'my-service',
34
+ environment: 'production',
35
+ version: '1.0.0',
36
+ level: 'info',
37
+ }),
38
+ ],
39
+ })
40
+ export class AppModule {}
41
+ ```
42
+
43
+ ### registerAsync(异步注册)
44
+
45
+ 从其他配置源(如 `@buka/nestjs-config`)获取配置:
46
+
47
+ ```typescript
48
+ import { Module } from '@nestjs/common'
49
+ import { LoggerModule } from '@buka/nestjs-kit'
50
+ import { ConfigModule, PinoConfig } from '@buka/nestjs-config'
51
+
52
+ @Module({
53
+ imports: [
54
+ ConfigModule.inject(PinoConfig, LoggerModule, (config) => ({
55
+ serviceName: config.serviceName,
56
+ level: config.level,
57
+ pretty: config.pretty,
58
+ })),
59
+ ],
60
+ })
61
+ export class AppModule {}
62
+ ```
63
+
64
+ 也可以使用标准的 `useFactory` 模式:
65
+
66
+ ```typescript
67
+ @Module({
68
+ imports: [
69
+ LoggerModule.registerAsync({
70
+ inject: [MyConfigService],
71
+ useFactory: (config: MyConfigService) => ({
72
+ serviceName: config.name,
73
+ level: config.logLevel,
74
+ }),
75
+ }),
76
+ ],
77
+ })
78
+ export class AppModule {}
79
+ ```
80
+
81
+ > `LoggerModule` 是 `@Global()` 全局模块,只需在 AppModule 中注册一次,所有模块均可使用。
82
+
83
+ ## 配置选项
84
+
85
+ | 选项 | 类型 | 必填 | 默认值 | 说明 |
86
+ |------|------|------|--------|------|
87
+ | `serviceName` | `string` | 否 | `'unknown'` | 服务名称,Grafana/Loki 中按服务过滤日志 |
88
+ | `environment` | `string` | 否 | `NODE_ENV` 或 `'development'` | 运行环境 |
89
+ | `version` | `string` | 否 | `npm_package_version` 或 `'0.0.0'` | 服务版本号,生产环境由 CI/CD 注入 |
90
+ | `level` | `string` | 否 | `'info'` | 日志级别:`'fatal'`、`'error'`、`'warn'`、`'info'`、`'debug'`、`'trace'` |
91
+ | `pretty` | `boolean` | 否 | `false` | 开发模式——启用 `pino-pretty` 彩色输出,生产环境设为 `false` 输出原生 JSON |
92
+
93
+ ## 日志输出格式
94
+
95
+ ### 生产环境(`pretty: false`,默认)
96
+
97
+ 原生 JSON 格式,每行一条 JSON 日志,Grafana/Loki 可直接索引:
98
+
99
+ ```json
100
+ {
101
+ "level": "info",
102
+ "time": "2025-05-10T08:30:00.000Z",
103
+ "reqId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
104
+ "service": "my-service",
105
+ "environment": "production",
106
+ "version": "1.0.0",
107
+ "msg": "request completed",
108
+ "req": { "method": "GET", "url": "/api/users" },
109
+ "res": { "statusCode": 200 },
110
+ "responseTime": 42
111
+ }
112
+ ```
113
+
114
+ ### 开发环境(`pretty: true`)
115
+
116
+ 启用 `pino-pretty` 传输,彩色人性化输出。
117
+
118
+ ## HTTP 自动日志
119
+
120
+ 模块自动记录每个 HTTP 请求的完成日志,包含:
121
+
122
+ - 请求方法、URL
123
+ - 响应状态码
124
+ - 响应耗时(`responseTime`,毫秒)
125
+ - 请求 ID(优先上游 `X-Request-Id` 头,否则自动生成 UUID)
126
+
127
+ 健康检查端点 `/api/v1/health` 的请求会被自动忽略,避免日志噪音。
128
+
129
+ ## @InjectLogger 装饰器
130
+
131
+ 在构造函数中注入 `Logger`,自动以当前类名为日志上下文:
132
+
133
+ ```typescript
134
+ import { Injectable } from '@nestjs/common'
135
+ import { InjectLogger } from '@buka/nestjs-kit'
136
+ import { Logger } from '@buka/nestjs-kit'
137
+
138
+ @Injectable()
139
+ export class UserService {
140
+ constructor(
141
+ @InjectLogger()
142
+ private readonly logger: Logger,
143
+ ) {}
144
+
145
+ async findOne(id: string) {
146
+ this.logger.info('查询用户', { userId: id })
147
+ // 日志上下文自动为 "UserService"
148
+ }
149
+ }
150
+ ```
151
+
152
+ 如需自定义上下文名称:
153
+
154
+ ```typescript
155
+ @InjectLogger('CustomContext')
156
+ private readonly logger: Logger
157
+ ```
158
+
159
+ > `@InjectLogger()` 等价于 `@InjectPinoLogger(UserService.name)`,省去手动填写类名。
160
+
161
+ ## LoggerConfig 配置基类
162
+
163
+ `LoggerConfig` 是配合 `@buka/nestjs-config` 使用的配置基类,字段与 `LoggerModuleOptions` 一一对应:
164
+
165
+ ```typescript
166
+ import { Configuration } from '@buka/nestjs-config'
167
+ import { LoggerConfig } from '@buka/nestjs-kit'
168
+
169
+ @Configuration('LOG')
170
+ export class AppLoggerConfig extends LoggerConfig {
171
+ // 继承以下字段,可通过环境变量覆盖:
172
+ // LOG_SERVICE_NAME
173
+ // LOG_ENVIRONMENT
174
+ // LOG_VERSION
175
+ // LOG_LEVEL
176
+ // LOG_PRETTY
177
+ }
178
+ ```
179
+
180
+ 然后通过 `ConfigModule.inject` 注入:
181
+
182
+ ```typescript
183
+ ConfigModule.inject(AppLoggerConfig, LoggerModule, (config) => ({
184
+ serviceName: config.serviceName,
185
+ level: config.level,
186
+ pretty: config.pretty,
187
+ }))
188
+ ```
189
+
190
+ ### 配置字段
191
+
192
+ | 字段 | 类型 | 默认值 | 环境变量示例 |
193
+ |------|------|--------|-------------|
194
+ | `serviceName` | `string` | `'unknown'` | `LOG_SERVICE_NAME=my-service` |
195
+ | `environment` | `string` | `NODE_ENV` 或 `'development'` | `LOG_ENVIRONMENT=production` |
196
+ | `version` | `string` | `npm_package_version` 或 `'0.0.0'` | `LOG_VERSION=1.0.0` |
197
+ | `level` | `'fatal' \| 'error' \| 'warn' \| 'info' \| 'debug' \| 'trace'` | `'info'` | `LOG_LEVEL=debug` |
198
+ | `pretty` | `boolean` | `false` | `LOG_PRETTY=true` |
199
+
200
+ ## LoggerErrorInterceptor
201
+
202
+ 模块自动注册 `LoggerErrorInterceptor`,在异常抛出时自动记录错误日志,包含请求上下文和错误堆栈。
203
+
204
+ ## 模块依赖关系
205
+
206
+ ```
207
+ LoggerModule ──依赖──▶ nestjs-pino (pino)
208
+ ```
209
+
210
+ > `LoggerModule` 仅依赖 `nestjs-pino`(peer dependency),不依赖 `@buka/nestjs-kit` 中的其他模块。
211
+
212
+ ## 完整使用示例
213
+
214
+ ### 1. 注册模块
215
+
216
+ ```typescript
217
+ import { Module } from '@nestjs/common'
218
+ import { LoggerModule } from '@buka/nestjs-kit'
219
+
220
+ @Module({
221
+ imports: [
222
+ LoggerModule.register({
223
+ serviceName: 'user-service',
224
+ level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
225
+ pretty: process.env.NODE_ENV !== 'production',
226
+ }),
227
+ ],
228
+ })
229
+ export class AppModule {}
230
+ ```
231
+
232
+ ### 2. 在 Service 中使用
233
+
234
+ ```typescript
235
+ import { Injectable } from '@nestjs/common'
236
+ import { InjectLogger } from '@buka/nestjs-kit'
237
+ import { Logger } from '@buka/nestjs-kit'
238
+
239
+ @Injectable()
240
+ export class OrderService {
241
+ constructor(
242
+ @InjectLogger()
243
+ private readonly logger: Logger,
244
+ ) {}
245
+
246
+ async createOrder(data: CreateOrderDto) {
247
+ this.logger.info('开始创建订单', { userId: data.userId })
248
+
249
+ try {
250
+ const order = await this.save(data)
251
+ this.logger.info('订单创建成功', { orderId: order.id })
252
+ return order
253
+ } catch (error) {
254
+ this.logger.error('订单创建失败', { error, userId: data.userId })
255
+ throw error
256
+ }
257
+ }
258
+ }
259
+ ```
260
+
261
+ ### 3. 在 Controller 中使用
262
+
263
+ ```typescript
264
+ import { Controller, Get, Param } from '@nestjs/common'
265
+ import { InjectLogger } from '@buka/nestjs-kit'
266
+ import { Logger } from '@buka/nestjs-kit'
267
+
268
+ @Controller('users')
269
+ export class UserController {
270
+ constructor(
271
+ @InjectLogger()
272
+ private readonly logger: Logger,
273
+ ) {}
274
+
275
+ @Get(':id')
276
+ async findOne(@Param('id') id: string) {
277
+ this.logger.debug('收到查询用户请求', { userId: id })
278
+ return this.userService.findOne(id)
279
+ }
280
+ }
281
+ ```
282
+
283
+ ## 注意事项
284
+
285
+ > `LoggerModule` 是全局模块,应在 AppModule 中只注册一次。重复注册会导致 nestjs-pino 初始化冲突。
286
+
287
+ > 生产环境建议将 `pretty` 设为 `false`(默认值),输出原生 JSON 以获得最优的 Loki 写入性能和索引效率。
288
+
289
+ > `LoggerErrorInterceptor` 由模块自动注册。如需自定义错误拦截器,可以在 providers 中覆盖。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buka/nestjs-kit",
3
- "version": "4.0.0",
3
+ "version": "4.1.2",
4
4
  "description": "Buka Nestjs Kit",
5
5
  "packageManager": "pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800",
6
6
  "types": "dist/index.d.ts",
@@ -37,13 +37,13 @@
37
37
  ],
38
38
  "author": "Val.istar.Guo <val.istar.guo@gmail.com>",
39
39
  "license": "MIT",
40
- "homepage": "https://github.com/buka-inc/npm.nestjs-kit#readme",
40
+ "homepage": "https://github.com/buka-ltd/npm.nestjs-kit#readme",
41
41
  "bugs": {
42
- "url": "https://github.com/buka-inc/npm.nestjs-kit/issues"
42
+ "url": "https://github.com/buka-ltd/npm.nestjs-kit/issues"
43
43
  },
44
44
  "repository": {
45
45
  "type": "git",
46
- "url": "https://github.com/buka-inc/npm.nestjs-kit"
46
+ "url": "https://github.com/buka-ltd/npm.nestjs-kit"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@buka/class-transformer-extra": "^2.1.4",
@@ -92,6 +92,8 @@
92
92
  "bcryptjs": "^3.0.3",
93
93
  "jsonschema": "^1.5.0",
94
94
  "keq": "5.0.0-beta.1",
95
+ "nestjs-pino": "^4.4.1",
96
+ "pino": "^10.3.1",
95
97
  "ramda": "^0.32.0",
96
98
  "type-fest": "^5.6.0",
97
99
  "uuid": "^14.0.0"