'How can I design my Logger class, so that it has some statefulness?

I am writing a Typescript CDK project. If you're unfamiliar with CDK, its mostly constructors, and the resulting Javascript code 'compiles' a .yaml file when run - this is done by calling cdk synth on the command line. I have few months experience writing Typescript, none with Javascript.

I have a small logger class that I like, because after running cdk synth, it shows me a 'summary' of log messages I've chosen to highlight, with printEndMessages():

class MyLogger {
    private tabwidth = 2
    public static summaryStatements: Array<string> = []

    constructor(){}

    public debug(message: string, indent?: number, includeInSummary?: boolean){
        let output = ` `.repeat((indent || 0) * this.tabwidth)
        output = output.concat(output, `=======> DEBUG: ${message}`)
        if(includeInSummary) Logger.summaryStatements.push(output)
        console.log(output)
    }
    public info(message: string, indent?: number, includeInSummary?: boolean){
        let output = ` `.repeat((indent || 0) * this.tabwidth)
        output = output.concat(output, `=======> INFO: ${message}`)
        if(includeInSummary) Logger.summaryStatements.push(output)
        console.log(output)
    }

    public printEndMessages(){
        console.log(`---------------------final notes (${Logger.summaryStatements.length})--------------------`)
        Logger.summaryStatements.forEach(message => console.log(message))
        console.log('--------------------------------------------------------')
    }

}
export const logger = MyLogger()

I simply call printEndMessages() as close to the end of my app.ts as I can, and it gives me a nice block.

So, I was wondering, instead of using import { logger } and then calling logger.info() throughout my code, is there a way I can instead import { MyLogger } instead? I would need every instance of MyLogger to contribute to this 'global' log summary static variable.

This might also be answerable by Javascript, but I don't know enough about either language to confidently act on answers. Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source