|
| 1 | +/* @flow */ |
| 2 | +import * as vscode from 'vscode'; |
| 3 | + |
| 4 | +const LOG_LEVEL = Object.freeze({ |
| 5 | + error: 3, |
| 6 | + warn: 2, |
| 7 | + info: 1, |
| 8 | + trace: 0, |
| 9 | + debug: 0, |
| 10 | +}); |
| 11 | + |
| 12 | +export type LogLevel = $Keys<typeof LOG_LEVEL>; |
| 13 | + |
| 14 | +// max of keys LOG_LEVEL |
| 15 | +const MAX_LEVEL_LENGTH = Object.keys(LOG_LEVEL).reduce((maxLength, level) => { |
| 16 | + if (level.length > maxLength) { |
| 17 | + return level.length; |
| 18 | + } |
| 19 | + return maxLength; |
| 20 | +}, 0); |
| 21 | + |
| 22 | +export default class Logger { |
| 23 | + _outputChannel: vscode.OutputChannel; |
| 24 | + _level: LogLevel; |
| 25 | + _context: string; |
| 26 | + |
| 27 | + constructor( |
| 28 | + context: string, |
| 29 | + outputChannel: vscode.OutputChannel, |
| 30 | + level: LogLevel, |
| 31 | + ) { |
| 32 | + this._outputChannel = outputChannel; |
| 33 | + this._level = level; |
| 34 | + this._context = context; |
| 35 | + } |
| 36 | + |
| 37 | + error(message: string, data?: mixed) { |
| 38 | + if (this._getLevelVal() <= LOG_LEVEL.error) { |
| 39 | + this._write('Error', message, data); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + warn(message: string, data?: mixed) { |
| 44 | + if (this._getLevelVal() <= LOG_LEVEL.warn) { |
| 45 | + this._write('Warn', message, data); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + info(message: string, data?: mixed) { |
| 50 | + if (this._getLevelVal() <= LOG_LEVEL.info) { |
| 51 | + this._write('Info', message, data); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + debug(message: string, data?: mixed) { |
| 56 | + if (this._getLevelVal() <= LOG_LEVEL.debug) { |
| 57 | + this._write('Debug', message, data); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + trace(message: string, data?: mixed) { |
| 62 | + if (this._getLevelVal() <= LOG_LEVEL.trace) { |
| 63 | + this._write('Trace', message, data); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + _getLevelVal() { |
| 68 | + return LOG_LEVEL[this._level]; |
| 69 | + } |
| 70 | + |
| 71 | + _write(level: string, message: string, data?: mixed) { |
| 72 | + const levelStr = level.padEnd(MAX_LEVEL_LENGTH); |
| 73 | + const tag = [ |
| 74 | + levelStr, |
| 75 | + new Date().toLocaleTimeString(), |
| 76 | + this._context ? this._context : null, |
| 77 | + ] |
| 78 | + .filter(Boolean) |
| 79 | + .join(' - '); |
| 80 | + |
| 81 | + let output = `[${tag}] ${message}`; |
| 82 | + if (data) { |
| 83 | + output += ' ${JSON.stringify(data)'; |
| 84 | + } |
| 85 | + |
| 86 | + this._outputChannel.appendLine(output); |
| 87 | + } |
| 88 | +} |
0 commit comments