@@ -82,13 +82,24 @@ function valueToAttribute(key: string, value: unknown): LogAttribute {
8282 }
8383}
8484
85+ let hasRegisteredFlushHook = false ;
86+
8587function addToLogBuffer ( client : Client , log : Log , scope : Scope ) : void {
8688 function sendLogs ( flushedLogs : Log [ ] ) : void {
8789 const envelope = createLogEnvelope ( flushedLogs , client , scope ) ;
8890 // eslint-disable-next-line @typescript-eslint/no-floating-promises
8991 void client . sendEnvelope ( envelope ) ;
9092 }
9193
94+ // Only register the hook once
95+ if ( ! hasRegisteredFlushHook ) {
96+ client . on ( 'flush' , ( ) => {
97+ sendLogs ( GLOBAL_LOG_BUFFER ) ;
98+ GLOBAL_LOG_BUFFER = [ ] ;
99+ } ) ;
100+ hasRegisteredFlushHook = true ;
101+ }
102+
92103 if ( GLOBAL_LOG_BUFFER . length >= LOG_BUFFER_MAX_LENGTH ) {
93104 sendLogs ( GLOBAL_LOG_BUFFER ) ;
94105 GLOBAL_LOG_BUFFER = [ ] ;
@@ -99,12 +110,17 @@ function addToLogBuffer(client: Client, log: Log, scope: Scope): void {
99110 // this is the first time logs have been enabled, let's kick off an interval to flush them
100111 // we should only do this once.
101112 if ( ! isFlushingLogs ) {
102- setInterval ( ( ) => {
113+ const flushTimer = setInterval ( ( ) => {
103114 if ( GLOBAL_LOG_BUFFER . length > 0 ) {
104115 sendLogs ( GLOBAL_LOG_BUFFER ) ;
105116 GLOBAL_LOG_BUFFER = [ ] ;
106117 }
107118 } , 5000 ) ;
119+
120+ // We need to unref the timer in node.js, otherwise the node process never exit.
121+ if ( typeof flushTimer !== 'number' && flushTimer . unref ) {
122+ flushTimer . unref ( ) ;
123+ }
108124 }
109125 isFlushingLogs = true ;
110126}
0 commit comments