-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Logger.js
39 lines (30 loc) · 1.08 KB
/
Logger.js
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
const fs = require('fs')
const path = require('path')
let { inspect } = require('util')
let utils
function getTimestamp() {
return utils.now().format()
}
module.exports = class Logger {
constructor(outputFile, name) {
if (!utils) utils = require('./utils')
let folderName = path.dirname(outputFile)
fs.mkdirSync(folderName, { recursive: true })
this.stream = fs.createWriteStream(outputFile, { flags: 'a' })
this.name = name
}
format(text) {
return `[${this.name}] [${getTimestamp()}]: ${text}`
}
level(level, objects) {
let text = objects.map(object => (typeof object === 'string') ? object : inspect(object, { depth: null })).join(' ')
let logData = text.split('\n').map(line => `${level} ${this.format(line)}`).join('\n')
this.stream.write(logData + '\n')
console.log(logData)
}
log(...objects) { this.level('LOG', objects) }
info(...objects) { this.level('INFO', objects) }
err(...objects) { this.level('ERROR', objects) }
warn(...objects) { this.level('WARN', objects) }
debug(...objects) { this.level('DEBUG', objects) }
}