1- import { appendFile , ensureFile } from "fs-extra" ;
1+ import { ensureFile } from "fs-extra" ;
2+ import { open } from "node:fs/promises" ;
3+ import type { FileHandle } from "node:fs/promises" ;
24import { isAbsolute } from "path" ;
35import { getErrorMessage } from "../helpers-pure" ;
46import type { Logger , LogOptions } from "./logger" ;
7+ import type { Disposable } from "../disposable-object" ;
58
69/**
710 * An implementation of {@link Logger} that sends the output both to another {@link Logger}
@@ -10,9 +13,10 @@ import type { Logger, LogOptions } from "./logger";
1013 * The first time a message is written, an additional banner is written to the underlying logger
1114 * pointing the user to the "side log" file.
1215 */
13- export class TeeLogger implements Logger {
16+ export class TeeLogger implements Logger , Disposable {
1417 private emittedRedirectMessage = false ;
1518 private error = false ;
19+ private fileHandle : FileHandle | undefined = undefined ;
1620
1721 public constructor (
1822 private readonly logger : Logger ,
@@ -37,11 +41,15 @@ export class TeeLogger implements Logger {
3741
3842 if ( ! this . error ) {
3943 try {
44+ if ( ! this . fileHandle ) {
45+ await ensureFile ( this . location ) ;
46+
47+ this . fileHandle = await open ( this . location , "a" ) ;
48+ }
49+
4050 const trailingNewline = options . trailingNewline ?? true ;
41- await ensureFile ( this . location ) ;
4251
43- await appendFile (
44- this . location ,
52+ await this . fileHandle . appendFile (
4553 message + ( trailingNewline ? "\n" : "" ) ,
4654 {
4755 encoding : "utf8" ,
@@ -50,6 +58,14 @@ export class TeeLogger implements Logger {
5058 } catch ( e ) {
5159 // Write an error message to the primary log, and stop trying to write to the side log.
5260 this . error = true ;
61+ try {
62+ await this . fileHandle ?. close ( ) ;
63+ } catch ( e ) {
64+ void this . logger . log (
65+ `Failed to close file handle: ${ getErrorMessage ( e ) } ` ,
66+ ) ;
67+ }
68+ this . fileHandle = undefined ;
5369 const errorMessage = getErrorMessage ( e ) ;
5470 await this . logger . log (
5571 `Error writing to additional log file: ${ errorMessage } ` ,
@@ -65,4 +81,15 @@ export class TeeLogger implements Logger {
6581 show ( preserveFocus ?: boolean ) : void {
6682 this . logger . show ( preserveFocus ) ;
6783 }
84+
85+ dispose ( ) : void {
86+ try {
87+ void this . fileHandle ?. close ( ) ;
88+ } catch ( e ) {
89+ void this . logger . log (
90+ `Failed to close file handle: ${ getErrorMessage ( e ) } ` ,
91+ ) ;
92+ }
93+ this . fileHandle = undefined ;
94+ }
6895}
0 commit comments