-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcaptureLogs.js
106 lines (93 loc) · 2.57 KB
/
captureLogs.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
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
/*
Copyright 2016 - 2018, Robin de Gruijter ([email protected])
*/
'use strict';
const Homey = require('homey');
const StdOutFixture = require('fixture-stdout');
const fs = require('fs');
// const util = require('util');
class captureLogs {
// Log object to keep logs in memory and in persistent storage
// captures and reroutes Homey's this.log (stdout) and this.err (stderr)
constructor(logName, logLength) {
this.logName = logName || 'log';
this.logLength = logLength || 50;
this.logFile = `/userdata/${this.logName}.json`;
this.logArray = [];
this.getLogs();
this.captureStdOut();
this.captureStdErr();
// Homey.app.log('capture is ready :)');
}
getLogs() {
fs.readFile(this.logFile, 'utf8', (err, data) => {
if (err) {
Homey.app.error('error reading logfile: ', err.message);
return [];
}
try {
this.logArray = JSON.parse(data);
// console.log(this.logArray);
} catch (error) {
Homey.app.error('error parsing logfile: ', error.message);
return [];
}
// Homey.app.log('logs retrieved from module');
return this.logArray;
});
}
saveLogs() {
fs.writeFile(this.logFile, JSON.stringify(this.logArray), (err) => {
if (err) {
Homey.app.error('error writing logfile: ', err.message);
} else {
Homey.app.log('logfile saved');
}
});
}
deleteLogs() {
// this.log('deleting logs from frontend');
this.logArray = [];
fs.unlink(this.logFile, (err) => {
if (err) {
Homey.app.error('error deleting logfile: ', err.message);
return err;
}
Homey.app.log('logfile deleted');
return true;
});
}
captureStdOut() {
// Capture all writes to stdout (e.g. this.log)
this.captureStdout = new StdOutFixture({ stream: process.stdout });
Homey.app.log('capturing stdout');
this.captureStdout.capture((string) => {
if (this.logArray.length >= this.logLength) {
this.logArray.shift();
}
this.logArray.push(string);
// return false; // prevent the write to the original stream
});
// captureStdout.release();
}
captureStdErr() {
// Capture all writes to stderr (e.g. this.error)
this.captureStderr = new StdOutFixture({ stream: process.stderr });
Homey.app.log('capturing stderr');
this.captureStderr.capture((string) => {
if (this.logArray.length >= this.logLength) {
this.logArray.shift();
}
this.logArray.push(string);
// return false; // prevent the write to the original stream
});
// captureStderr.release();
}
releaseStdOut() {
this.captureStdout.release();
}
releaseStdErr() {
this.captureStderr.release();
}
}
module.exports = captureLogs;