aboutsummaryrefslogtreecommitdiffstats
path: root/qt-lib/src/logger.ts
blob: fda96f8da0cf7066ed34ce5e2a7d2104f3200d1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only

import * as vscode from 'vscode';
import * as winston from 'winston';
import { LogOutputChannelTransport } from 'winston-transport-vscode';

let logger: winston.Logger | undefined = undefined;

export class Logger {
  constructor(private readonly tag: string) {
    this.tag = tag;
  }

  private log(level: keyof winston.Logger, ...message: string[]) {
    if (logger) {
      (logger[level] as (message: string) => void)(
        `[${this.tag}] ${message.join('')}`
      );
    } else {
      console.error('Logger not initialized');
    }
  }

  error(...message: string[]) {
    this.log('error', ...message);
  }

  warn(...message: string[]) {
    this.log('warn', ...message);
  }

  info(...message: string[]) {
    this.log('info', ...message);
  }

  verbose(...message: string[]) {
    this.log('verbose', ...message);
  }

  debug(...message: string[]) {
    this.log('debug', ...message);
  }
}

export function initLogger(extensionName: string) {
  const outputChannel = vscode.window.createOutputChannel(extensionName, {
    log: true
  });
  logger = winston.createLogger({
    levels: LogOutputChannelTransport.config.levels,
    format: LogOutputChannelTransport.format(),
    transports: [new LogOutputChannelTransport({ outputChannel })]
  });
}

export function createLogger(tag: string) {
  return new Logger(tag);
}