license import { createWriteStream , WriteStream } from 'fs' ; import { IConnection } from 'vscode-languageserver/lib/main' ; import Settings from './settings' ; export class Logger { private readonly connection : IConnection ; private logFile : WriteStream | undefined = undefined ; private readonly logFileFromFlag : WriteStream | undefined ; private settings : Settings | undefined ; private queue : string [ ] = [ ] ; constructor ( options ) { this . connection = options . connection ; if ( options . logToFileFlag !== undefined ) { this . logFileFromFlag = undefined ; try { this . logFileFromFlag = createWriteStream ( options . logToFileFlag , { flags : 'a' } ) ; } catch { } } } async hookupSettings ( settings ) { settings . changeStream . listen ( ( { older , newer } ) => { if ( older . logToFile !== newer . logToFile ) { if ( this . logFile ) { this . logFile . end ( ) ; this . logFile = undefined ; } if ( newer . logToFile ) { try { this . logFile = createWriteStream ( newer . logToFile , { flags : 'a' } ) ; } catch { this . logFile = undefined ; } } } } ) ; await settings . ready ; this . settings = settings ; for ( const queuedMessage of this . queue ) { this . log ( queuedMessage ) ; } this . queue . length = 0 ; } dispose ( ) { if ( this . logFile ) { this . logFile . end ( ) ; this . logFile = undefined ; } } log ( message ) { if ( this . settings ) { if ( this . settings . logToClient ) { this . connection . console . log ( message ) ; } if ( this . logFile !== undefined ) { try { this . logFile . write ( message + '\n' ) ; } catch { } } if ( this . logFileFromFlag !== undefined ) { try { this . logFileFromFlag . write ( message + '\n' ) ; } catch { } } } else { this . queue . push ( message ) ; } } }