-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathinternalLogger.ts
More file actions
179 lines (147 loc) · 5.37 KB
/
internalLogger.ts
File metadata and controls
179 lines (147 loc) · 5.37 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import * as path from 'path';
import * as mkdirp from 'mkdirp';
import { LogLevel, ILogCallback, trimLastNewline, LogOutputEvent, IInternalLoggerOptions, IInternalLogger } from './logger';
/**
* Manages logging, whether to console.log, file, or VS Code console.
* Encapsulates the state specific to each logging session
*/
export class InternalLogger implements IInternalLogger {
private _minLogLevel: LogLevel;
private _logToConsole: boolean;
/** Log info that meets minLogLevel is sent to this callback. */
private _logCallback: ILogCallback;
/** Write steam for log file */
private _logFileStream: fs.WriteStream;
/** Dispose and allow exit to continue normally */
private beforeExitCallback = () => this.dispose();
/** Dispose and exit */
private disposeCallback;
/** Whether to add a timestamp to messages in the logfile */
private _prependTimestamp: boolean;
constructor(logCallback: ILogCallback, isServer?: boolean) {
this._logCallback = logCallback;
this._logToConsole = isServer;
this._minLogLevel = LogLevel.Warn;
this.disposeCallback = (signal: string, code: number) => {
this.dispose();
// Exit with 128 + value of the signal code.
// https://nodejs.org/api/process.html#process_exit_codes
code = code || 2; // SIGINT
code += 128;
process.exit(code);
};
}
public async setup(options: IInternalLoggerOptions): Promise<void> {
this._minLogLevel = options.consoleMinLogLevel;
this._prependTimestamp = options.prependTimestamp;
// Open a log file in the specified location. Overwritten on each run.
if (options.logFilePath) {
if (!path.isAbsolute(options.logFilePath)) {
this.log(`logFilePath must be an absolute path: ${options.logFilePath}`, LogLevel.Error);
} else {
const handleError = err => this.sendLog(`Error creating log file at path: ${options.logFilePath}. Error: ${err.toString()}\n`, LogLevel.Error);
try {
await mkdirp(path.dirname(options.logFilePath));
this.log(`Verbose logs are written to:\n`, LogLevel.Warn);
this.log(options.logFilePath + '\n', LogLevel.Warn);
this._logFileStream = fs.createWriteStream(options.logFilePath);
this.logDateTime();
this.setupShutdownListeners();
this._logFileStream.on('error', err => {
handleError(err);
});
} catch (err) {
handleError(err);
}
}
}
}
private logDateTime(): void {
let d = new Date();
let dateString = d.getUTCFullYear() + '-' + `${d.getUTCMonth() + 1}` + '-' + d.getUTCDate();
const timeAndDateStamp = dateString + ', ' + getFormattedTimeString();
this.log(timeAndDateStamp + '\n', LogLevel.Verbose, false);
}
private setupShutdownListeners(): void {
process.addListener('beforeExit', this.beforeExitCallback);
process.addListener('SIGTERM', this.disposeCallback);
process.addListener('SIGINT', this.disposeCallback);
}
private removeShutdownListeners(): void {
process.removeListener('beforeExit', this.beforeExitCallback);
process.removeListener('SIGTERM', this.disposeCallback);
process.removeListener('SIGINT', this.disposeCallback);
}
public dispose(): Promise<void> {
return new Promise(resolve => {
this.removeShutdownListeners();
if (this._logFileStream) {
this._logFileStream.end(resolve);
this._logFileStream = null;
} else {
resolve();
}
});
}
public log(msg: string, level: LogLevel, prependTimestamp = true): void {
if (this._minLogLevel === LogLevel.Stop) {
return;
}
if (level >= this._minLogLevel) {
this.sendLog(msg, level);
}
if (this._logToConsole) {
const logFn =
level === LogLevel.Error ? console.error :
level === LogLevel.Warn ? console.warn :
null;
if (logFn) {
logFn(trimLastNewline(msg));
}
}
// If an error, prepend with '[Error]'
if (level === LogLevel.Error) {
msg = `[${LogLevel[level]}] ${msg}`;
}
if (this._prependTimestamp && prependTimestamp) {
msg = '[' + getFormattedTimeString() + '] ' + msg;
}
if (this._logFileStream) {
this._logFileStream.write(msg);
}
}
private sendLog(msg: string, level: LogLevel): void {
// Truncate long messages, they can hang VS Code
if (msg.length > 1500) {
const endsInNewline = !!msg.match(/(\n|\r\n)$/);
msg = msg.substr(0, 1500) + '[...]';
if (endsInNewline) {
msg = msg + '\n';
}
}
if (this._logCallback) {
const event = new LogOutputEvent(msg, level);
this._logCallback(event);
}
}
}
function getFormattedTimeString(): string {
let d = new Date();
let hourString = _padZeroes(2, String(d.getUTCHours()));
let minuteString = _padZeroes(2, String(d.getUTCMinutes()));
let secondString = _padZeroes(2, String(d.getUTCSeconds()));
let millisecondString = _padZeroes(3, String(d.getUTCMilliseconds()));
return hourString + ':' + minuteString + ':' + secondString + '.' + millisecondString + ' UTC';
}
function _padZeroes(minDesiredLength: number, numberToPad: string): string {
if (numberToPad.length >= minDesiredLength) {
return numberToPad;
} else {
return String('0'.repeat(minDesiredLength) + numberToPad).slice(-minDesiredLength);
}
}