@hestjs/logger 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 aqz236
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,295 @@
1
+ # @hest/logger
2
+
3
+ <div align="center">
4
+
5
+ ![HestJS Logger](https://img.shields.io/badge/HestJS-Logger-blue?style=for-the-badge&logo=typescript)
6
+
7
+ **A powerful, modern logging solution for HestJS framework based on Pino**
8
+
9
+ [![npm version](https://img.shields.io/npm/v/@hest/logger?style=flat-square)](https://www.npmjs.com/package/@hest/logger)
10
+ [![downloads](https://img.shields.io/npm/dm/@hest/logger?style=flat-square)](https://www.npmjs.com/package/@hest/logger)
11
+ [![license](https://img.shields.io/npm/l/@hest/logger?style=flat-square)](https://github.com/aqz236/hest-logger/blob/main/LICENSE)
12
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)](https://www.typescriptlang.org/)
13
+
14
+
15
+ </div>
16
+
17
+
18
+ ## ✨ Features
19
+
20
+ - 🚀 **High Performance** - Built on top of Pino, one of the fastest JSON loggers
21
+ - 🎨 **Beautiful Output** - Clean, readable console logs with customizable formatting
22
+ - 🔧 **TypeScript Native** - Full TypeScript support with comprehensive type definitions
23
+ - 🌍 **Environment Aware** - Different configurations for development, production, and testing
24
+ - 📝 **Structured Logging** - JSON logging with customizable serializers
25
+ - 🎯 **Context Support** - Add request IDs, user IDs, and custom context data
26
+ - 🔄 **Multiple Transports** - Console, file, rotating files, and custom transports
27
+ - 🛡️ **Security First** - Built-in redaction for sensitive information
28
+ - 📦 **Framework Integration** - Seamlessly integrates with HestJS framework
29
+
30
+ ## 📦 Installation
31
+
32
+ ```bash
33
+ # npm
34
+ npm install @hest/logger
35
+
36
+ # yarn
37
+ yarn add @hest/logger
38
+
39
+ # pnpm
40
+ pnpm add @hest/logger
41
+
42
+ # bun
43
+ bun add @hest/logger
44
+ ```
45
+
46
+ ## 🚀 Quick Start
47
+
48
+ ### Basic Usage
49
+
50
+ ```typescript
51
+ import { createLogger, logger } from '@hest/logger';
52
+
53
+ // Use global logger
54
+ logger.info('Hello, World!');
55
+ logger.error('Something went wrong!', { error: 'details' });
56
+
57
+ // Create named logger
58
+ const apiLogger = createLogger('API');
59
+ apiLogger.info('API server started');
60
+ ```
61
+
62
+ ### With HestJS Framework
63
+
64
+ ```typescript
65
+ import { HestFactory, logger } from '@hest/core';
66
+
67
+ async function bootstrap() {
68
+ logger.info('🚀 Starting HestJS application...');
69
+
70
+ const app = await HestFactory.create(AppModule);
71
+
72
+ logger.info('✅ Application ready!');
73
+ }
74
+ ```
75
+
76
+ ### Advanced Configuration
77
+
78
+ ```typescript
79
+ import { createLogger, LogLevel } from '@hest/logger';
80
+
81
+ const customLogger = createLogger('MyService', {
82
+ level: LogLevel.DEBUG,
83
+ transport: {
84
+ target: 'pino-pretty',
85
+ options: {
86
+ colorize: true,
87
+ translateTime: 'yyyy-mm-dd HH:MM:ss.l',
88
+ }
89
+ }
90
+ });
91
+
92
+ customLogger.debug('Debug information');
93
+ customLogger.info('Service initialized');
94
+ customLogger.warn('Warning message');
95
+ customLogger.error('Error occurred');
96
+ ```
97
+
98
+ ## 📖 API Reference
99
+
100
+ ### Core Functions
101
+
102
+ #### `createLogger(name?, config?)`
103
+
104
+ Creates a new logger instance with optional name and configuration.
105
+
106
+ ```typescript
107
+ const logger = createLogger('ServiceName', {
108
+ level: LogLevel.INFO,
109
+ // ... other options
110
+ });
111
+ ```
112
+
113
+ #### `logger` (Global Logger)
114
+
115
+ Pre-configured global logger instance.
116
+
117
+ ```typescript
118
+ import { logger } from '@hest/logger';
119
+
120
+ logger.info('Global log message');
121
+ ```
122
+
123
+ ### Logger Methods
124
+
125
+ ```typescript
126
+ logger.fatal('Fatal error');
127
+ logger.error('Error message');
128
+ logger.warn('Warning message');
129
+ logger.info('Info message');
130
+ logger.debug('Debug message');
131
+ logger.trace('Trace message');
132
+ ```
133
+
134
+ ### Context Support
135
+
136
+ ```typescript
137
+ // Set context for all subsequent logs
138
+ logger.setContext({ requestId: '123', userId: 'user456' });
139
+ logger.info('User action performed');
140
+
141
+ // Create child logger with context
142
+ const childLogger = logger.child({ module: 'auth' });
143
+ childLogger.info('Authentication successful');
144
+ ```
145
+
146
+ ## ⚙️ Configuration
147
+
148
+ ### Environment-based Configuration
149
+
150
+ The logger automatically adapts based on `NODE_ENV`:
151
+
152
+ - **Development**: Pretty-printed colored output
153
+ - **Production**: JSON format optimized for log aggregation
154
+ - **Test**: Minimal logging to reduce noise
155
+
156
+ ### Custom Configuration
157
+
158
+ ```typescript
159
+ import { createLogger, LogLevel } from '@hest/logger';
160
+
161
+ const logger = createLogger('MyApp', {
162
+ level: LogLevel.INFO,
163
+ redact: ['password', 'token'], // Hide sensitive fields
164
+ formatters: {
165
+ level: (label, number) => ({ level: number }),
166
+ bindings: (bindings) => ({ service: 'MyApp', ...bindings })
167
+ },
168
+ serializers: {
169
+ req: (req) => ({ method: req.method, url: req.url }),
170
+ res: (res) => ({ statusCode: res.statusCode })
171
+ }
172
+ });
173
+ ```
174
+
175
+ ## 🎨 Output Examples
176
+
177
+ ### Development Output
178
+ ```
179
+ [2025-07-27 14:08:19.149] INFO (MyService): User login successful
180
+ [2025-07-27 14:08:19.150] ERROR (Auth): Invalid credentials provided
181
+ error: "Invalid username or password"
182
+ requestId: "req_123456"
183
+ ```
184
+
185
+ ### Production Output
186
+ ```json
187
+ {"level":30,"time":1643299699149,"name":"MyService","msg":"User login successful","requestId":"req_123456"}
188
+ {"level":50,"time":1643299699150,"name":"Auth","msg":"Invalid credentials provided","err":{"type":"AuthError","message":"Invalid username or password"}}
189
+ ```
190
+
191
+ ## 🔧 Transports
192
+
193
+ ### Console Transport
194
+ ```typescript
195
+ import { createConsoleTransport } from '@hest/logger';
196
+
197
+ const transport = createConsoleTransport({
198
+ colorize: true,
199
+ translateTime: 'yyyy-mm-dd HH:MM:ss.l'
200
+ });
201
+ ```
202
+
203
+ ### File Transport
204
+ ```typescript
205
+ import { createFileTransport } from '@hest/logger';
206
+
207
+ const transport = createFileTransport({
208
+ destination: './logs/app.log',
209
+ mkdir: true
210
+ });
211
+ ```
212
+
213
+ ### Rotating Files
214
+ ```typescript
215
+ import { createRotatingFileTransport } from '@hest/logger';
216
+
217
+ const transport = createRotatingFileTransport({
218
+ filename: './logs/app-%DATE%.log',
219
+ frequency: 'daily',
220
+ maxSize: '10M',
221
+ maxFiles: '7'
222
+ });
223
+ ```
224
+
225
+ ## 🛡️ Security Features
226
+
227
+ ### Automatic Redaction
228
+ ```typescript
229
+ const logger = createLogger('SecureApp', {
230
+ redact: ['password', 'token', 'authorization', 'cookie']
231
+ });
232
+
233
+ // This will automatically redact sensitive fields
234
+ logger.info('User data', {
235
+ username: 'john_doe',
236
+ password: 'secret123' // This will be redacted
237
+ });
238
+ ```
239
+
240
+ ### Safe Serialization
241
+ All serializers include error handling to prevent logging failures from crashing your application.
242
+
243
+ ## 🧪 Testing
244
+
245
+ ```typescript
246
+ import { createLogger, LogLevel } from '@hest/logger';
247
+
248
+ // Create test logger with minimal output
249
+ const testLogger = createLogger('Test', {
250
+ level: LogLevel.WARN // Only log warnings and errors in tests
251
+ });
252
+ ```
253
+
254
+
255
+ ## 📊 Star History
256
+
257
+ [![Star History Chart](https://api.star-history.com/svg?repos=aqz236/hest-logger&type=Date)](https://star-history.com/#aqz236/hest-logger&Date)
258
+
259
+ ## 📊 Performance
260
+
261
+ - **Zero-cost abstractions** when logging is disabled
262
+ - **Fast serialization** with Pino's optimized JSON stringification
263
+ - **Minimal memory footprint** with streaming architecture
264
+ - **Benchmark**: Up to 35,000 logs/second in production mode
265
+
266
+ ## 🤝 Contributing
267
+
268
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
269
+
270
+ 1. Fork the repository
271
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
272
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
273
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
274
+ 5. Open a Pull Request
275
+
276
+ ## 📄 License
277
+
278
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
279
+
280
+ ## 🔗 Links
281
+
282
+ - [HestJS Framework](https://github.com/aqz236/hest)
283
+ - [Pino Logger](https://github.com/pinojs/pino)
284
+ - [Documentation](https://github.com/aqz236/hest-logger/wiki)
285
+ - [Issues](https://github.com/aqz236/hest-logger/issues)
286
+
287
+ ---
288
+
289
+ <div align="center">
290
+
291
+ **Built with ❤️ for the HestJS ecosystem**
292
+
293
+ [⭐ Star us on GitHub](https://github.com/aqz236/hest-logger) • [📝 Report Bug](https://github.com/aqz236/hest-logger/issues) • [💡 Request Feature](https://github.com/aqz236/hest-logger/issues)
294
+
295
+ </div>
@@ -0,0 +1,30 @@
1
+ import { LoggerConfig } from "./types";
2
+ /**
3
+ * 默认日志配置
4
+ */
5
+ export declare const DEFAULT_CONFIG: LoggerConfig;
6
+ /**
7
+ * 开发环境配置
8
+ */
9
+ export declare const DEVELOPMENT_CONFIG: Partial<LoggerConfig>;
10
+ /**
11
+ * 生产环境配置
12
+ */
13
+ export declare const PRODUCTION_CONFIG: Partial<LoggerConfig>;
14
+ /**
15
+ * 测试环境配置
16
+ */
17
+ export declare const TEST_CONFIG: Partial<LoggerConfig>;
18
+ /**
19
+ * 根据环境获取配置
20
+ */
21
+ export declare function getEnvironmentConfig(env?: string): Partial<LoggerConfig>;
22
+ /**
23
+ * 从环境变量创建配置
24
+ */
25
+ export declare function createConfigFromEnv(): Partial<LoggerConfig>;
26
+ /**
27
+ * 合并配置
28
+ */
29
+ export declare function mergeConfig(...configs: Partial<LoggerConfig>[]): LoggerConfig;
30
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA+B,MAAM,SAAS,CAAC;AAEpE;;GAEG;AACH,eAAO,MAAM,cAAc,EAAE,YAU5B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kBAAkB,EAAE,OAAO,CAAC,YAAY,CAGpD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAE,OAAO,CAAC,YAAY,CAGnD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,EAAE,OAAO,CAAC,YAAY,CAE7C,CAAC;AAEF;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAexE;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,OAAO,CAAC,YAAY,CAAC,CAa3D;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,GAAG,YAAY,CAI7E"}
package/dist/config.js ADDED
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEST_CONFIG = exports.PRODUCTION_CONFIG = exports.DEVELOPMENT_CONFIG = exports.DEFAULT_CONFIG = void 0;
4
+ exports.getEnvironmentConfig = getEnvironmentConfig;
5
+ exports.createConfigFromEnv = createConfigFromEnv;
6
+ exports.mergeConfig = mergeConfig;
7
+ const types_1 = require("./types");
8
+ /**
9
+ * 默认日志配置
10
+ */
11
+ exports.DEFAULT_CONFIG = {
12
+ level: types_1.LogLevel.INFO,
13
+ timestamp: true,
14
+ name: "HestJS",
15
+ messageKey: "msg",
16
+ errorKey: "err",
17
+ base: {
18
+ pid: process.pid,
19
+ hostname: require("os").hostname(),
20
+ },
21
+ };
22
+ /**
23
+ * 开发环境配置
24
+ */
25
+ exports.DEVELOPMENT_CONFIG = {
26
+ level: types_1.LogLevel.DEBUG,
27
+ // 不在这里设置 transport,让 factory 使用 transports.ts 中的配置
28
+ };
29
+ /**
30
+ * 生产环境配置
31
+ */
32
+ exports.PRODUCTION_CONFIG = {
33
+ level: types_1.LogLevel.INFO,
34
+ redact: ["password", "token", "authorization", "cookie"],
35
+ };
36
+ /**
37
+ * 测试环境配置
38
+ */
39
+ exports.TEST_CONFIG = {
40
+ level: types_1.LogLevel.WARN,
41
+ };
42
+ /**
43
+ * 根据环境获取配置
44
+ */
45
+ function getEnvironmentConfig(env) {
46
+ const environment = env || process.env.NODE_ENV || "development";
47
+ switch (environment) {
48
+ case "production":
49
+ case "prod":
50
+ return exports.PRODUCTION_CONFIG;
51
+ case "test":
52
+ case "testing":
53
+ return exports.TEST_CONFIG;
54
+ case "development":
55
+ case "dev":
56
+ default:
57
+ return exports.DEVELOPMENT_CONFIG;
58
+ }
59
+ }
60
+ /**
61
+ * 从环境变量创建配置
62
+ */
63
+ function createConfigFromEnv() {
64
+ const env = process.env;
65
+ const config = {};
66
+ if (env.LOG_LEVEL) {
67
+ config.level = env.LOG_LEVEL;
68
+ }
69
+ if (env.LOG_NAME) {
70
+ config.name = env.LOG_NAME;
71
+ }
72
+ return config;
73
+ }
74
+ /**
75
+ * 合并配置
76
+ */
77
+ function mergeConfig(...configs) {
78
+ return configs.reduce((merged, config) => ({ ...merged, ...config }), {
79
+ ...exports.DEFAULT_CONFIG,
80
+ });
81
+ }
82
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":";;;AA2CA,oDAeC;AAKD,kDAaC;AAKD,kCAIC;AArFD,mCAAoE;AAEpE;;GAEG;AACU,QAAA,cAAc,GAAiB;IAC1C,KAAK,EAAE,gBAAQ,CAAC,IAAI;IACpB,SAAS,EAAE,IAAI;IACf,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,KAAK;IACjB,QAAQ,EAAE,KAAK;IACf,IAAI,EAAE;QACJ,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE;KACnC;CACF,CAAC;AAEF;;GAEG;AACU,QAAA,kBAAkB,GAA0B;IACvD,KAAK,EAAE,gBAAQ,CAAC,KAAK;IACrB,mDAAmD;CACpD,CAAC;AAEF;;GAEG;AACU,QAAA,iBAAiB,GAA0B;IACtD,KAAK,EAAE,gBAAQ,CAAC,IAAI;IACpB,MAAM,EAAE,CAAC,UAAU,EAAE,OAAO,EAAE,eAAe,EAAE,QAAQ,CAAC;CACzD,CAAC;AAEF;;GAEG;AACU,QAAA,WAAW,GAA0B;IAChD,KAAK,EAAE,gBAAQ,CAAC,IAAI;CACrB,CAAC;AAEF;;GAEG;AACH,SAAgB,oBAAoB,CAAC,GAAY;IAC/C,MAAM,WAAW,GAAG,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,aAAa,CAAC;IAEjE,QAAQ,WAAW,EAAE,CAAC;QACpB,KAAK,YAAY,CAAC;QAClB,KAAK,MAAM;YACT,OAAO,yBAAiB,CAAC;QAC3B,KAAK,MAAM,CAAC;QACZ,KAAK,SAAS;YACZ,OAAO,mBAAW,CAAC;QACrB,KAAK,aAAa,CAAC;QACnB,KAAK,KAAK,CAAC;QACX;YACE,OAAO,0BAAkB,CAAC;IAC9B,CAAC;AACH,CAAC;AAED;;GAEG;AACH,SAAgB,mBAAmB;IACjC,MAAM,GAAG,GAAsB,OAAO,CAAC,GAAG,CAAC;IAC3C,MAAM,MAAM,GAA0B,EAAE,CAAC;IAEzC,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClB,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,SAAqB,CAAC;IAC3C,CAAC;IAED,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;QACjB,MAAM,CAAC,IAAI,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC7B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACH,SAAgB,WAAW,CAAC,GAAG,OAAgC;IAC7D,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,EAAE;QACpE,GAAG,sBAAc;KAClB,CAAiB,CAAC;AACrB,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { Logger, LoggerConfig } from './types';
2
+ /**
3
+ * 创建 Logger 实例
4
+ */
5
+ export declare function createLogger(name?: string, config?: Partial<LoggerConfig>): Logger;
6
+ /**
7
+ * 创建带有上下文的 Logger
8
+ */
9
+ export declare function createLoggerWithContext(name: string, context: Record<string, any>, config?: Partial<LoggerConfig>): Logger;
10
+ /**
11
+ * 创建子 Logger
12
+ */
13
+ export declare function createChildLogger(parent: Logger, bindings: Record<string, any>): Logger;
14
+ //# sourceMappingURL=factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEpD;;GAEG;AACH,wBAAgB,YAAY,CAC1B,IAAI,CAAC,EAAE,MAAM,EACb,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAC7B,MAAM,CA0CR;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC5B,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAC7B,MAAM,CAGR;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC5B,MAAM,CAER"}
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createLogger = createLogger;
7
+ exports.createLoggerWithContext = createLoggerWithContext;
8
+ exports.createChildLogger = createChildLogger;
9
+ const pino_1 = __importDefault(require("pino"));
10
+ const logger_1 = require("./logger");
11
+ const config_1 = require("./config");
12
+ const serializers_1 = require("./serializers");
13
+ const formatters_1 = require("./formatters");
14
+ const transports_1 = require("./transports");
15
+ /**
16
+ * 创建 Logger 实例
17
+ */
18
+ function createLogger(name, config) {
19
+ // 合并配置:默认配置 -> 环境配置 -> 环境变量配置 -> 用户配置
20
+ const envConfig = (0, config_1.getEnvironmentConfig)();
21
+ const envVarConfig = (0, config_1.createConfigFromEnv)();
22
+ const userConfig = config || {};
23
+ // 如果提供了名称,添加到配置中
24
+ if (name) {
25
+ userConfig.name = name;
26
+ }
27
+ const finalConfig = (0, config_1.mergeConfig)(envConfig, envVarConfig, userConfig);
28
+ // 设置默认序列化器和格式化器
29
+ if (!finalConfig.serializers) {
30
+ finalConfig.serializers = (0, serializers_1.getDefaultSerializers)();
31
+ }
32
+ if (!finalConfig.formatters) {
33
+ finalConfig.formatters = (0, formatters_1.getDefaultFormatters)();
34
+ }
35
+ // 设置传输
36
+ if (!finalConfig.transport) {
37
+ const transport = (0, transports_1.getEnvironmentTransport)();
38
+ if (transport) {
39
+ finalConfig.transport = transport;
40
+ }
41
+ }
42
+ // 创建 Pino Logger
43
+ const pinoLogger = (0, pino_1.default)(finalConfig);
44
+ // 如果有 name,创建一个 child logger 来包含 name
45
+ const loggerWithName = name ? pinoLogger.child({ name }) : pinoLogger;
46
+ // 返回 HestLogger 实例
47
+ return new logger_1.HestLogger(loggerWithName);
48
+ }
49
+ /**
50
+ * 创建带有上下文的 Logger
51
+ */
52
+ function createLoggerWithContext(name, context, config) {
53
+ const logger = createLogger(name, config);
54
+ return logger.setContext(context);
55
+ }
56
+ /**
57
+ * 创建子 Logger
58
+ */
59
+ function createChildLogger(parent, bindings) {
60
+ return parent.child(bindings);
61
+ }
62
+ //# sourceMappingURL=factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory.js","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":";;;;;AAWA,oCA6CC;AAKD,0DAOC;AAKD,8CAKC;AA9ED,gDAAwB;AACxB,qCAAsC;AACtC,qCAAkF;AAClF,+CAAsD;AACtD,6CAAoD;AACpD,6CAAuD;AAGvD;;GAEG;AACH,SAAgB,YAAY,CAC1B,IAAa,EACb,MAA8B;IAE9B,sCAAsC;IACtC,MAAM,SAAS,GAAG,IAAA,6BAAoB,GAAE,CAAC;IACzC,MAAM,YAAY,GAAG,IAAA,4BAAmB,GAAE,CAAC;IAC3C,MAAM,UAAU,GAAG,MAAM,IAAI,EAAE,CAAC;IAEhC,iBAAiB;IACjB,IAAI,IAAI,EAAE,CAAC;QACT,UAAU,CAAC,IAAI,GAAG,IAAI,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简洁版本,只保留数字级别
3
+ */
4
+ export declare const levelFormatter: (_label: string, number: number) => {
5
+ level: number;
6
+ };
7
+ /**
8
+ * 时间戳格式化器
9
+ */
10
+ export declare const timestampFormatter: () => {
11
+ timestamp: string;
12
+ };
13
+ /**
14
+ * 绑定数据格式化器 - 默认返回空对象,保持简洁
15
+ */
16
+ export declare const bindingsFormatter: (_bindings: Record<string, any>) => {};
17
+ /**
18
+ * 日志对象格式化器 - 标准化日志结构
19
+ */
20
+ export declare const logFormatter: (object: Record<string, any>) => {
21
+ "@timestamp": any;
22
+ level: any;
23
+ message: any;
24
+ };
25
+ /**
26
+ * 错误格式化器 - 专门处理错误对象
27
+ */
28
+ export declare const errorFormatter: (object: Record<string, any>) => Record<string, any>;
29
+ /**
30
+ * 获取默认格式化器
31
+ */
32
+ export declare function getDefaultFormatters(): {
33
+ level: (_label: string, number: number) => {
34
+ level: number;
35
+ };
36
+ bindings: (_bindings: Record<string, any>) => {};
37
+ log: (object: Record<string, any>) => Record<string, any>;
38
+ };
39
+ /**
40
+ * 创建自定义格式化器
41
+ */
42
+ export declare function createFormatter<T = Record<string, any>>(fn: (object: T) => T): (object: T) => T;
43
+ //# sourceMappingURL=formatters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatters.d.ts","sourceRoot":"","sources":["../src/formatters.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,cAAc,GAAI,QAAQ,MAAM,EAAE,QAAQ,MAAM;;CAS5D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kBAAkB;;CAI9B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,GAAI,WAAW,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,OAa/D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;;;;CAUvD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,wBAezD,CAAC;AAEF;;GAEG;AACH,wBAAgB,oBAAoB;oBA5EG,MAAM,UAAU,MAAM;;;0BAuBhB,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;kBAyD9C,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;EAMpC;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACrD,EAAE,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GACnB,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAalB"}
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorFormatter = exports.logFormatter = exports.bindingsFormatter = exports.timestampFormatter = exports.levelFormatter = void 0;
4
+ exports.getDefaultFormatters = getDefaultFormatters;
5
+ exports.createFormatter = createFormatter;
6
+ /**
7
+ * 日志级别格式化器 - 简洁版本,只保留数字级别
8
+ */
9
+ const levelFormatter = (_label, number) => {
10
+ return {
11
+ level: number,
12
+ };
13
+ // return {
14
+ // level: number,
15
+ // levelLabel: label.toUpperCase(),
16
+ // };
17
+ };
18
+ exports.levelFormatter = levelFormatter;
19
+ /**
20
+ * 时间戳格式化器
21
+ */
22
+ const timestampFormatter = () => {
23
+ return {
24
+ timestamp: new Date().toISOString(),
25
+ };
26
+ };
27
+ exports.timestampFormatter = timestampFormatter;
28
+ /**
29
+ * 绑定数据格式化器 - 默认返回空对象,保持简洁
30
+ */
31
+ const bindingsFormatter = (_bindings) => {
32
+ // 默认不添加任何额外信息,保持日志简洁
33
+ return {};
34
+ // const { pid, hostname, ...rest } = bindings;
35
+ // return {
36
+ // service: 'HestJS',
37
+ // version: process.env.npm_package_version || '0.1.0',
38
+ // environment: process.env.NODE_ENV || 'development',
39
+ // pid,
40
+ // hostname,
41
+ // ...rest,
42
+ // };
43
+ };
44
+ exports.bindingsFormatter = bindingsFormatter;
45
+ /**
46
+ * 日志对象格式化器 - 标准化日志结构
47
+ */
48
+ const logFormatter = (object) => {
49
+ const { level, time, msg, ...rest } = object;
50
+ // 重组日志结构,确保关键字段在前
51
+ return {
52
+ "@timestamp": time,
53
+ level,
54
+ message: msg,
55
+ ...rest,
56
+ };
57
+ };
58
+ exports.logFormatter = logFormatter;
59
+ /**
60
+ * 错误格式化器 - 专门处理错误对象
61
+ */
62
+ const errorFormatter = (object) => {
63
+ if (object.err || object.error) {
64
+ const error = object.err || object.error;
65
+ return {
66
+ ...object,
67
+ error: {
68
+ name: error.name,
69
+ message: error.message,
70
+ stack: error.stack,
71
+ ...(error.status && { status: error.status }),
72
+ ...(error.statusCode && { statusCode: error.statusCode }),
73
+ },
74
+ };
75
+ }
76
+ return object;
77
+ };
78
+ exports.errorFormatter = errorFormatter;
79
+ /**
80
+ * 获取默认格式化器
81
+ */
82
+ function getDefaultFormatters() {
83
+ return {
84
+ level: exports.levelFormatter,
85
+ bindings: exports.bindingsFormatter,
86
+ log: (object) => {
87
+ // 组合多个格式化器
88
+ const formatted = (0, exports.logFormatter)(object);
89
+ return (0, exports.errorFormatter)(formatted);
90
+ },
91
+ };
92
+ }
93
+ /**
94
+ * 创建自定义格式化器
95
+ */
96
+ function createFormatter(fn) {
97
+ return (object) => {
98
+ try {
99
+ return fn(object);
100
+ }
101
+ catch (error) {
102
+ // 如果格式化失败,返回原始对象并添加错误信息
103
+ return {
104
+ ...object,
105
+ formatError: error instanceof Error ? error.message : "Unknown formatting error",
106
+ };
107
+ }
108
+ };
109
+ }
110
+ //# sourceMappingURL=formatters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatters.js","sourceRoot":"","sources":["../src/formatters.ts"],"names":[],"mappings":";;;AA+EA,oDAUC;AAKD,0CAeC;AA7GD;;GAEG;AACI,MAAM,cAAc,GAAG,CAAC,MAAc,EAAE,MAAc,EAAE,EAAE;IAC/D,OAAO;QACL,KAAK,EAAE,MA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