-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathlogger.ts
227 lines (182 loc) · 5.96 KB
/
logger.ts
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
216
217
218
219
220
221
222
223
224
225
226
227
import * as log4js from "log4js";
import * as util from "util";
import * as stream from "stream";
import * as marked from "marked";
import { cache } from "../decorators";
import { layout } from "./layouts/cli-layout";
import { LoggerConfigData, LoggerLevel, LoggerAppenders } from "../../constants";
const TerminalRenderer = require("marked-terminal");
const chalk = require("chalk");
export class Logger implements ILogger {
private log4jsLogger: log4js.Logger = null;
private passwordRegex = /(password=).*?(['&,]|$)|(password["']?\s*:\s*["']).*?(["'])/i;
private passwordReplacement = "$1$3*******$2$4";
constructor(private $config: Config.IConfig,
private $options: IOptions) {
}
@cache()
public initialize(opts?: ILoggerOptions): void {
opts = opts || {};
const { appenderOptions: appenderOpts, level } = opts;
const appender: any = {
type: "console",
layout: {
type: "messagePassThrough"
}
};
if (appenderOpts) {
_.merge(appender, appenderOpts);
}
const appenders: IDictionary<log4js.Appender> = {
out: appender
};
const categories: IDictionary<{ appenders: string[]; level: string; }> = {
default: {
appenders: ['out'],
level: level || (this.$config.DEBUG ? "TRACE" : "INFO")
}
};
log4js.configure({ appenders, categories });
this.log4jsLogger = log4js.getLogger();
}
public initializeCliLogger(): void {
log4js.addLayout("cli", layout);
this.initialize({
appenderOptions: { type: LoggerAppenders.cliAppender, layout: { type: "cli" } },
level: <any>this.$options.log
});
}
getLevel(): string {
this.initialize();
return this.log4jsLogger.level.toString();
}
fatal(...args: any[]): void {
this.logMessage(args, LoggerLevel.FATAL);
}
error(...args: any[]): void {
args.push({ [LoggerConfigData.useStderr]: true });
this.logMessage(args, LoggerLevel.ERROR);
}
warn(...args: any[]): void {
this.logMessage(args, LoggerLevel.WARN);
}
info(...args: any[]): void {
this.logMessage(args, LoggerLevel.INFO);
}
debug(...args: any[]): void {
const encodedArgs: string[] = this.getPasswordEncodedArguments(args);
this.logMessage(encodedArgs, LoggerLevel.DEBUG);
}
trace(...args: any[]): void {
const encodedArgs: string[] = this.getPasswordEncodedArguments(args);
this.logMessage(encodedArgs, LoggerLevel.TRACE);
}
prepare(item: any): string {
if (typeof item === "undefined" || item === null) {
return "[no content]";
}
if (typeof item === "string") {
return item;
}
// do not try to read streams, because they may not be rewindable
if (item instanceof stream.Readable) {
return "[ReadableStream]";
}
// There's no point in printing buffers
if (item instanceof Buffer) {
return "[Buffer]";
}
return JSON.stringify(item);
}
public printMarkdown(...args: string[]): void {
const opts = {
unescape: true,
link: chalk.red,
strong: chalk.green.bold,
firstHeading: chalk.blue.bold,
tableOptions: {
chars: { 'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },
style: {
'padding-left': 1,
'padding-right': 1,
head: ['green', 'bold'],
border: ['grey'],
compact: false
}
}
};
marked.setOptions({ renderer: new TerminalRenderer(opts) });
const formattedMessage = marked(util.format.apply(null, args));
this.info(formattedMessage, { [LoggerConfigData.skipNewLine]: true });
}
private logMessage(inputData: any[], logMethod: string): void {
this.initialize();
const logOpts = this.getLogOptionsForMessage(inputData);
const data = logOpts.data;
delete logOpts.data;
for (const prop in logOpts) {
this.log4jsLogger.addContext(prop, logOpts[prop]);
}
(<IDictionary<any>>this.log4jsLogger)[logMethod.toLowerCase()].apply(this.log4jsLogger, data);
for (const prop in logOpts) {
this.log4jsLogger.removeContext(prop);
}
}
private getLogOptionsForMessage(data: any[]): { data: any[], [key: string]: any } {
const opts = _.keys(LoggerConfigData);
const result: any = {};
const cleanedData = _.cloneDeep(data);
// objects created with Object.create(null) do not have `hasOwnProperty` function
const dataToCheck = data.filter(el => typeof el === "object" && el.hasOwnProperty && typeof el.hasOwnProperty === "function");
for (const element of dataToCheck) {
if (opts.length === 0) {
break;
}
const remainingOpts = _.cloneDeep(opts);
for (const prop of remainingOpts) {
const hasProp = element && element.hasOwnProperty(prop);
if (hasProp) {
opts.splice(opts.indexOf(prop), 1);
result[prop] = element[prop];
cleanedData.splice(cleanedData.indexOf(element), 1);
}
}
}
result.data = cleanedData;
return result;
}
private getPasswordEncodedArguments(args: string[]): string[] {
return _.map(args, argument => {
if (typeof argument === 'string' && !!argument.match(/password/i)) {
argument = argument.replace(this.passwordRegex, this.passwordReplacement);
}
return argument;
});
}
/*******************************************************************************************
* Metods below are deprecated. Delete them in 6.0.0 release: *
* Present only for backwards compatibility as some plugins (nativescript-plugin-firebase) *
* use these methods in their hooks *
*******************************************************************************************/
out(...args: any[]): void {
this.info(args);
}
write(...args: any[]): void {
this.info(args, { [LoggerConfigData.skipNewLine]: true });
}
printOnStderr(...args: string[]): void {
this.error(args);
}
printInfoMessageOnSameLine(message: string): void {
this.info(message, { [LoggerConfigData.skipNewLine]: true });
}
printMsgWithTimeout(message: string, timeout: number): Promise<void> {
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
this.printInfoMessageOnSameLine(message);
resolve();
}, timeout);
});
}
}
$injector.register("logger", Logger);