-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogto.js
52 lines (47 loc) · 1.42 KB
/
logto.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
const fs = require('fs-extra');
const stackTracey = require('stacktracey');
const path = require('path');
// TODO : allow different logging formats
function logto(options) {
options = Object.assign({
dir: "",
file: "",
mute: true
}, options);
// validate options
check(options);
const outfile = path.join(options.dir, options.file);
fs.ensureFileSync(outfile);
this.logfile = outfile;
this.log = defaultLogger;
this.mute = options.mute;
this.end = logEnd;
// create a new outstream
this.writestream = fs.createWriteStream(outfile, { flags: 'a' });
}
function defaultLogger(...inputs) {
let st = new stackTracey().items[1];
let dt = new Date().toUTCString();
inputs = String(...inputs);
let lgdata = `${dt}| ${inputs} | <${st.beforeParse}`;
if (!(this.mute)) console.log(lgdata);
//append data to log file
this.writestream.write(`${lgdata}\n`);
}
// function to exit log stream
function logEnd() {
this.writestream.write("log end\n");
this.writestream.end();
}
// to check if proper options are passed or not
function check(options) {
if (options.dir.length === 0) {
console.log("logto: cannot have empty directory name in options");
process.exit(1);
};
if (options.file.length === 0) {
console.log("logto: cannot have empty file name in options");
process.exit(1);
}
}
module.exports = logto;