forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathindex.ts
More file actions
215 lines (186 loc) · 6.83 KB
/
index.ts
File metadata and controls
215 lines (186 loc) · 6.83 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createWriteStream } from 'fs-extra';
import { isPromise } from 'rxjs/internal-compatibility';
import { Disposable } from 'vscode';
import { StopWatch } from '../common/utils/stopWatch';
import { sendTelemetryEvent } from '../telemetry';
import { EventName } from '../telemetry/constants';
import { FileLogger } from './fileLogger';
import { Arguments, ILogging, LogLevel, TraceDecoratorType, TraceOptions } from './types';
import { argsToLogString, returnValueToLogString } from './util';
const DEFAULT_OPTS: TraceOptions = TraceOptions.Arguments | TraceOptions.ReturnValue;
let loggers: ILogging[] = [];
export function registerLogger(logger: ILogging): Disposable {
loggers.push(logger);
return {
dispose: () => {
loggers = loggers.filter((l) => l !== logger);
},
};
}
export function initializeFileLogging(disposables: Disposable[]): void {
if (process.env.VSC_PYTHON_LOG_FILE) {
const fileLogger = new FileLogger(createWriteStream(process.env.VSC_PYTHON_LOG_FILE));
disposables.push(fileLogger);
disposables.push(registerLogger(fileLogger));
}
}
export function traceLog(...args: Arguments): void {
loggers.forEach((l) => l.traceLog(...args));
}
export function traceError(...args: Arguments): void {
loggers.forEach((l) => l.traceError(...args));
}
export function traceWarn(...args: Arguments): void {
loggers.forEach((l) => l.traceWarn(...args));
}
export function traceInfo(...args: Arguments): void {
loggers.forEach((l) => l.traceInfo(...args));
}
export function traceVerbose(...args: Arguments): void {
loggers.forEach((l) => l.traceVerbose(...args));
}
/** Logging Decorators go here */
export function traceDecoratorVerbose(message: string, opts: TraceOptions = DEFAULT_OPTS): TraceDecoratorType {
return createTracingDecorator({ message, opts, level: LogLevel.Debug });
}
export function traceDecoratorError(message: string): TraceDecoratorType {
return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: LogLevel.Error });
}
export function traceDecoratorInfo(message: string): TraceDecoratorType {
return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: LogLevel.Info });
}
export function traceDecoratorWarn(message: string): TraceDecoratorType {
return createTracingDecorator({ message, opts: DEFAULT_OPTS, level: LogLevel.Warning });
}
// Information about a function/method call.
type CallInfo = {
kind: string; // "Class", etc.
name: string;
args: unknown[];
};
// Information about a traced function/method call.
type TraceInfo = {
elapsed: number; // milliseconds
// Either returnValue or err will be set.
returnValue?: any;
err?: Error;
};
type LogInfo = {
opts: TraceOptions;
message: string;
level?: LogLevel;
};
// Return a decorator that traces the decorated function.
function traceDecorator(log: (c: CallInfo, t: TraceInfo) => void): TraceDecoratorType {
return function (_: Object, __: string, descriptor: TypedPropertyDescriptor<any>) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: unknown[]) {
const call = {
kind: 'Class',
name: _ && _.constructor ? _.constructor.name : '',
args,
};
// eslint-disable-next-line @typescript-eslint/no-this-alias
const scope = this;
return tracing(
// "log()"
(t) => log(call, t),
// "run()"
() => originalMethod.apply(scope, args),
);
};
return descriptor;
};
}
// Call run(), call log() with the trace info, and return the result.
function tracing<T>(log: (t: TraceInfo) => void, run: () => T): T {
const timer = new StopWatch();
try {
const result = run();
// If method being wrapped returns a promise then wait for it.
if (isPromise(result)) {
((result as unknown) as Promise<void>)
.then((data) => {
log({ elapsed: timer.elapsedTime, returnValue: data });
return data;
})
.catch((ex) => {
log({ elapsed: timer.elapsedTime, err: ex });
// TODO(GH-11645) Re-throw the error like we do
// in the non-Promise case.
});
} else {
log({ elapsed: timer.elapsedTime, returnValue: result });
}
return result;
} catch (ex) {
log({ elapsed: timer.elapsedTime, err: ex as Error | undefined });
throw ex;
}
}
function createTracingDecorator(logInfo: LogInfo): TraceDecoratorType {
return traceDecorator((call, traced) => logResult(logInfo, traced, call));
}
function normalizeCall(call: CallInfo): CallInfo {
let { kind, name, args } = call;
if (!kind || kind === '') {
kind = 'Function';
}
if (!name || name === '') {
name = '<anon>';
}
if (!args) {
args = [];
}
return { kind, name, args };
}
function formatMessages(logInfo: LogInfo, traced: TraceInfo, call?: CallInfo): string {
call = normalizeCall(call!);
const messages = [logInfo.message];
messages.push(
`${call.kind} name = ${call.name}`.trim(),
`completed in ${traced.elapsed}ms`,
`has a ${traced.returnValue ? 'truthy' : 'falsy'} return value`,
);
if ((logInfo.opts & TraceOptions.Arguments) === TraceOptions.Arguments) {
messages.push(argsToLogString(call.args));
}
if ((logInfo.opts & TraceOptions.ReturnValue) === TraceOptions.ReturnValue) {
messages.push(returnValueToLogString(traced.returnValue));
}
return messages.join(', ');
}
function logResult(logInfo: LogInfo, traced: TraceInfo, call?: CallInfo) {
const formatted = formatMessages(logInfo, traced, call);
if (traced.err === undefined) {
// The call did not fail.
if (!logInfo.level || logInfo.level > LogLevel.Error) {
logTo(LogLevel.Info, [formatted]);
}
} else {
logTo(LogLevel.Error, [formatted, traced.err]);
sendTelemetryEvent(('ERROR' as unknown) as EventName, undefined, undefined, traced.err);
}
}
export function logTo(logLevel: LogLevel, ...args: Arguments): void {
switch (logLevel) {
case LogLevel.Error:
traceError(...args);
break;
case LogLevel.Warning:
traceWarn(...args);
break;
case LogLevel.Info:
traceInfo(...args);
break;
case LogLevel.Debug:
traceVerbose(...args);
break;
default:
break;
}
}