Skip to content

Commit d0c1551

Browse files
committed
feat(logger): 优化日志前缀和上下文字符串的解析逻辑
1 parent 62c715e commit d0c1551

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Change
22

3+
## 3.6.10
4+
5+
- feat(logger): 优化日志前缀和上下文字符串的解析逻辑
6+
37
## 3.6.9
48

59
- feat(logger): 优化 WinstonLogger 初始化逻辑,避免重复创建 logger 实例

packages/core/src/common/logger/abstract-logger.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,24 @@ export abstract class AbstractLogger implements Logger {
1717
this.context = context;
1818
}
1919

20+
protected resolveContextString(context?: string): string {
21+
if (this.context) {
22+
return context ? `[${this.context}] [${context}] ` : `[${this.context}] `;
23+
}
24+
return context ? `[${context}] ` : '';
25+
}
26+
27+
protected resolvePrefix(context?: string): string {
28+
const time = new Date().toISOString();
29+
return `${time} [${this.level}]`;
30+
}
31+
2032
protected log(message: any, context?: string, logFn: (...args: any[]) => void = console.info): void {
2133
context = context ?? this.context;
22-
const time = new Date().toISOString();
2334
const traceId = this.traceIdProvider?.provide();
2435
const traceStr = traceId ? ` [trace: ${traceId}]` : '';
25-
const contextStr = this.context ? ` [${this.context}]` : '';
26-
logFn(`${time} [${this.level}]${traceStr}${contextStr} ${message}`);
36+
const contextStr = this.resolveContextString(context);
37+
logFn(`${this.resolvePrefix(context)}${traceStr}${contextStr} ${message}`);
2738
onLogEmitter.fire({
2839
level: this.level,
2940
traceId,
@@ -41,7 +52,7 @@ export abstract class AbstractLogger implements Logger {
4152
if (start !== undefined) {
4253
const duration = Date.now() - start;
4354
this.timeRecords.delete(label);
44-
this.log(`${label}: ${duration}ms`, context);
55+
this.log(`${label} [${duration}ms]`, context);
4556
return duration;
4657
} else {
4758
this.log(`No such label: ${label} for timeEnd`, context);

packages/logger/src/common/winston-logger.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ export class WinstonLogger extends AbstractLogger {
5858
this.log(message, context, this.logger.debug.bind(this.logger));
5959
}
6060

61+
protected override resolvePrefix(context?: string): string {
62+
return '';
63+
}
64+
6165
protected override log(message: any, context?: string, logFn?: (...args: any[]) => void): void {
6266
super.log(message, context, logFn ?? this.logger.info.bind(this.logger));
6367
}

0 commit comments

Comments
 (0)