@@ -13,19 +13,20 @@ const logLevels = {
1313 TRACE : 'trace'
1414} as const ;
1515
16- export const TRACE_ID = Symbol ( 'TraceID' ) ;
17- export const TRACE_T0 = Symbol ( 'TraceT0' ) ;
16+ export const TRACE_CTX = Symbol ( 'TraceCtx' ) ;
17+ export interface TraceCtx {
18+ id ?: string ;
19+ t0 ?: Date ;
20+ }
1821export interface TraceableInterface {
19- [ TRACE_ID ] ?: string ;
20- [ TRACE_T0 ] ?: Date ;
22+ [ TRACE_CTX ] ?: TraceCtx ;
2123}
2224
2325export const tracerHook = createHook ( {
2426 init ( _asyncId , _type , _triggerAsyncId , resource : TraceableInterface ) {
2527 const currentResource : TraceableInterface = executionAsyncResource ( ) ;
26- if ( currentResource ?. [ TRACE_ID ] ) {
27- resource [ TRACE_ID ] = currentResource [ TRACE_ID ] ;
28- resource [ TRACE_T0 ] = currentResource [ TRACE_T0 ] ;
28+ if ( currentResource ?. [ TRACE_CTX ] ) {
29+ resource [ TRACE_CTX ] = currentResource [ TRACE_CTX ] ;
2930 }
3031 }
3132} ) ;
@@ -34,10 +35,19 @@ export function setupTraceId(traceId?: string, t0?: Date) {
3435 tracerHook . enable ( ) ;
3536 const currentResource : TraceableInterface = executionAsyncResource ( ) ;
3637 if ( currentResource ) {
37- currentResource [ TRACE_ID ] = traceId || randomUUID ( ) ;
38- currentResource [ TRACE_T0 ] = t0 || new Date ( ) ;
39-
40- return currentResource [ TRACE_ID ] ;
38+
39+ if ( ! currentResource [ TRACE_CTX ] ) {
40+ currentResource [ TRACE_CTX ] = {
41+ id : traceId || randomUUID ( ) ,
42+ t0 : t0 || new Date ( )
43+ } ;
44+ } else {
45+ const ctx = currentResource [ TRACE_CTX ] ! ;
46+ ctx . id = traceId || randomUUID ( ) ;
47+ ctx . t0 = t0 || new Date ( ) ;
48+ }
49+
50+ return currentResource [ TRACE_CTX ] ;
4151 }
4252
4353 return undefined ;
@@ -46,7 +56,7 @@ export function setupTraceId(traceId?: string, t0?: Date) {
4656export function getTraceId ( ) {
4757 const currentResource : TraceableInterface = executionAsyncResource ( ) ;
4858
49- return currentResource ?. [ TRACE_ID ] ;
59+ return currentResource ?. [ TRACE_CTX ] ?. id ;
5060}
5161
5262export abstract class AbstractLogger extends AsyncService {
@@ -86,10 +96,10 @@ export abstract class AbstractLogger extends AsyncService {
8696 }
8797
8898 const resource : TraceableInterface = executionAsyncResource ( ) ;
89- if ( resource ?. [ TRACE_ID ] ) {
99+ if ( resource ?. [ TRACE_CTX ] ) {
90100 objects . push ( {
91- traceId : resource [ TRACE_ID ] ,
92- traceDt : Date . now ( ) - resource [ TRACE_T0 ] ! . getTime ( )
101+ traceId : resource [ TRACE_CTX ] . id ,
102+ traceDt : Date . now ( ) - resource [ TRACE_CTX ] . t0 ! . getTime ( )
93103 } ) ;
94104 }
95105
0 commit comments