import * as vscode from "vscode" ; import { LogLevel , getFormattedDatetimeString } from "./logHelper" ; const channels = { } ; export class OutputChannelLogger { public static MAIN_CHANNEL_NAME : string = "Cordova Tools" ; private outputChannel : vscode . OutputChannel ; private logTimestamps : boolean ; constructor ( public readonly channelName , lazy = false , private preserveFocus = false , logTimestamps = false ) { this . logTimestamps = logTimestamps ; if ( ! lazy ) { this . channel = vscode . window . createOutputChannel ( this . channelName ) ; this . channel . show ( this . preserveFocus ) ; } } public static disposeChannel ( channelName ) { if ( channels [ channelName ] ) { channels [ channelName ] . getOutputChannel ( ) . dispose ( ) ; delete channels [ channelName ] ; } } public static getMainChannel ( ) { return this . getChannel ( this . MAIN_CHANNEL_NAME , true ) ; } public static getChannel ( channelName , lazy ? , preserveFocus ? , logTimestamps ? ) { if ( ! channels [ channelName ] ) { channels [ channelName ] = new OutputChannelLogger ( channelName , lazy , preserveFocus , logTimestamps ) ; } return channels [ channelName ] ; } private static purify ( message ) { return message . toString ( ) . replace ( /\u001b/g , "" ) . replace ( /\[2K\[G/g , "" ) . replace ( /\[\d+m/g , "" ) ; } public log ( message ) { this . channel . appendLine ( OutputChannelLogger . purify ( message ) ) ; } public logWithCustomTag ( tag , message , level ) { if ( level === LogLevel . Custom ) { message = this . getFormattedMessage ( message , tag , this . logTimestamps ) ; this . channel . appendLine ( message ) ; } } public append ( message ) { this . channel . append ( OutputChannelLogger . purify ( message ) ) ; } public getOutputChannel ( ) { return this . channel ; } public clear ( ) { this . channel . clear ( ) ; } private get channel ( ) : vscode . OutputChannel { if ( this . outputChannel ) { return this . outputChannel ; } else { this . outputChannel = vscode . window . createOutputChannel ( this . channelName ) ; this . outputChannel . show ( this . preserveFocus ) ; return this . outputChannel ; } } private set channel ( channel ) { this . outputChannel = channel ; } private getFormattedMessage ( message , tag , prependTimestamp = false ) { let formattedMessage = `[${ tag }] ${ message }\n` ; if ( prependTimestamp ) { formattedMessage = `[${ getFormattedDatetimeString ( new Date ( ) ) }] ${ formattedMessage }` ; } return formattedMessage ; } }