xterm
[VSoRC/.git] / node_modules / xterm / src / common / services / LogService.ts
1 /**
2  * Copyright (c) 2019 The xterm.js authors. All rights reserved.
3  * @license MIT
4  */
5
6 import { ILogService, IOptionsService } from 'common/services/Services';
7
8 type LogType = (message?: any, ...optionalParams: any[]) => void;
9
10 interface IConsole {
11   log: LogType;
12   error: LogType;
13   info: LogType;
14   trace: LogType;
15   warn: LogType;
16 }
17
18 // console is available on both node.js and browser contexts but the common
19 // module doesn't depend on them so we need to explicitly declare it.
20 declare const console: IConsole;
21
22
23 export enum LogLevel {
24   DEBUG = 0,
25   INFO = 1,
26   WARN = 2,
27   ERROR = 3,
28   OFF = 4
29 }
30
31 const optionsKeyToLogLevel: { [key: string]: LogLevel } = {
32   debug: LogLevel.DEBUG,
33   info: LogLevel.INFO,
34   warn: LogLevel.WARN,
35   error: LogLevel.ERROR,
36   off: LogLevel.OFF
37 };
38
39 const LOG_PREFIX = 'xterm.js: ';
40
41 export class LogService implements ILogService {
42   serviceBrand: any;
43
44   private _logLevel!: LogLevel;
45
46   constructor(
47     @IOptionsService private readonly _optionsService: IOptionsService
48   ) {
49     this._updateLogLevel();
50     this._optionsService.onOptionChange(key => {
51       if (key === 'logLevel') {
52         this._updateLogLevel();
53       }
54     });
55   }
56
57   private _updateLogLevel(): void {
58     this._logLevel = optionsKeyToLogLevel[this._optionsService.options.logLevel];
59   }
60
61   private _evalLazyOptionalParams(optionalParams: any[]): void {
62     for (let i = 0; i < optionalParams.length; i++) {
63       if (typeof optionalParams[i] === 'function') {
64         optionalParams[i] = optionalParams[i]();
65       }
66     }
67   }
68
69   private _log(type: LogType, message: string, optionalParams: any[]): void {
70     this._evalLazyOptionalParams(optionalParams);
71     type.call(console, LOG_PREFIX + message, ...optionalParams);
72   }
73
74   debug(message: string, ...optionalParams: any[]): void {
75     if (this._logLevel <= LogLevel.DEBUG) {
76       this._log(console.log, message, optionalParams);
77     }
78   }
79
80   info(message: string, ...optionalParams: any[]): void {
81     if (this._logLevel <= LogLevel.INFO) {
82       this._log(console.info, message, optionalParams);
83     }
84   }
85
86   warn(message: string, ...optionalParams: any[]): void {
87     if (this._logLevel <= LogLevel.WARN) {
88       this._log(console.warn, message, optionalParams);
89     }
90   }
91
92   error(message: string, ...optionalParams: any[]): void {
93     if (this._logLevel <= LogLevel.ERROR) {
94       this._log(console.error, message, optionalParams);
95     }
96   }
97 }