forked from D2KLab/music-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.js
75 lines (56 loc) · 2.05 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
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
/* LOGGER */
const fs = require('fs');
const eol = require('os').EOL;
const path = require('path');
const underscore = require('underscore');
const logFile = {};
const logDir = process.env.log_folder || path.resolve(process.cwd(), 'logs');
// FUNCTION TO CHECK IF DIRECTORY EXISTS
function directoryExists(path) {
try {
return fs.statSync(path).isDirectory();
} catch (err) {
return false;
}
}
function getHeader() {
return "timestamp,platform,user,channel,intent,confidence,lang,rawMessage,cleanMessage,response" + eol;
}
function getFileNameByDate() {
const today = new Date();
const year = today.getFullYear().toString();
const month = (today.getMonth() + 1).toString().padStart(2, '0');
return 'doremus_log_' + year + '-' + month + '.csv';
}
// MODULE
module.exports = function() {
logger = {};
if (directoryExists(logDir) == false) {
// init dir and file
fs.mkdirSync(logDir);
}
logger.write = function(platform, user, team, intent, response, cleanMessage, rawMessage, lang, confidence) {
// sanitize
response = response.replace(',','');
rawMessage = rawMessage.replace(',','');
cleanMessage = cleanMessage.replace(',','');
// prepare new line with timestamp and other infos
const timestamp = new Date().toLocaleString();
const data = `${timestamp},${platform},${user},${team},${intent},${confidence},${lang},${rawMessage},${cleanMessage},${response}${eol}`;
// get month file
const fileName = getFileNameByDate();
// append the line to the csv file
logFilePath = path.join(logDir, fileName);
// if file doesn't exist, print header
if (!fs.existsSync(logFilePath)) {
fs.writeFileSync(logFilePath, getHeader());
}
// write (appending to the file)
fs.appendFile(logFilePath, data, (error) => {
if (error) {
console.error(`Write error to ${logFilePath}: ${error.message}`);
}
});
}
return logger;
}