-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
logger.ts
110 lines (88 loc) 路 2.41 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
import * as fs from 'fs'
interface LoggerConfig {
DEBUG_MODE: boolean
}
interface LogMessage {
funcName?: string
logData: object | string
message: string
time: string
type: TypeLog
}
enum TypeLog {
ERROR = 'ERROR',
LOG = 'LOG'
}
class Logger {
private DEBUG: boolean = false
private LogFile: LogMessage[] = []
constructor(config: LoggerConfig) {
this.DEBUG = config.DEBUG_MODE
}
public log(message: string, logData: object | string, funcName?: string) {
this._addLogItem(TypeLog.LOG, message, logData, funcName)
}
public error(message: string, logData: object | string, funcName?: string) {
this._addLogItem(TypeLog.ERROR, message, logData, funcName)
}
public saveLogToFile() {
const nameOfFile = `log-${new Date().toISOString()}.txt`
const file = fs.createWriteStream(nameOfFile)
file.on('error', (err: Error) => {
console.error('ERROR: Failed to write log file!', err)
console.error('LOG File will be output in console!')
console.info('----- LOG ------')
this.LogFile.forEach(item => console.info(this._printLog(item)))
console.info('-- END OF LOG --')
})
file.on('finish', () => {
console.log(`Wrote log to file "${nameOfFile}"`)
})
this.LogFile.forEach(item => {
file.write(this._printLog(item) + '\n')
})
file.end()
}
private _addLogItem(type: TypeLog, message: string, logData: object | string, funcName?: string) {
if (!this.DEBUG) {
return
}
let cnsl: Console['error'] | Console['log'] | Console['info']
switch (type) {
case TypeLog.ERROR:
cnsl = console.error
break
case TypeLog.LOG:
cnsl = console.info
break
default:
cnsl = console.log
break
}
this.LogFile.push({
funcName,
logData,
message,
time: new Date().toISOString(),
type
})
if (funcName) {
cnsl(`# [${new Date().toISOString()}] #`)
cnsl('FUNCTION:', funcName)
cnsl(type, message)
cnsl(logData)
cnsl('### ### ###\n')
return
}
cnsl(`# [${new Date().toISOString()}] #`)
cnsl(type, message)
cnsl(logData)
cnsl('### ### ###\n')
}
private _printLog(item: LogMessage) {
return `[${item.time}] ${item.type}${item.funcName ? ' "' + item.funcName + '": ' : ''} ${
item.message
} - ${JSON.stringify(item.logData, null, 2)}`
}
}
export default Logger