forked from lamassu/lamassu-machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.js
63 lines (54 loc) · 1.35 KB
/
logging.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const path = require('path')
const clim = require('clim')
const fs = require('fs')
const uuid = require('uuid')
const dataPath = require('./lib/data-path')
let lastTimestamp = null
let serial = 0
clim.getTime = function () {
return new Date().toISOString()
}
// WARNING: This method has side effects
function getSerial (timestamp) {
if (lastTimestamp === timestamp) {
return ++serial
}
lastTimestamp = timestamp
serial = 0
return serial
}
function diskLog (level, timestamp, msg) {
const line = JSON.stringify({
id: uuid.v4(),
timestamp,
serial: getSerial(timestamp),
level,
msg
}) + '\n'
fs.appendFile(getLogFile(), line, () => {})
}
clim.logWrite = function (level, prefixes, msg) {
const timestamp = clim.getTime()
diskLog(level, timestamp, msg)
var line = timestamp + ' ' + level
if (prefixes.length > 0) line += ' ' + prefixes.join(' ')
line += ' ' + msg
process.stderr.write(line + '\n')
}
/**
* Get file by current date
*
* Returns a file name (full path)
* ending on current ymd in format yy-mm-dd
*
* @name getLogFile
* @function
*
* @returns {string} Log file path ending in yy-mm-dd format
*/
function getLogFile () {
const ymd = new Date().toISOString().slice(0, 10)
return path.resolve(dataPath, 'log', `${ymd}.log`)
}
fs.mkdir(path.resolve(dataPath, 'log'), () => {})
clim(console, true)