1 | const path = require('path');
|
2 | const fs = require('fs-extra');
|
3 |
|
4 | module.exports = function (options) {
|
5 | let config = {
|
6 | path: path.join(process.env.BLAZE_INSTANCE, 'logs'),
|
7 | maxLogSize: 2000000,
|
8 | logInterval: 86400000
|
9 | }
|
10 |
|
11 | Object.assign(config, options);
|
12 |
|
13 | fs.ensureDirSync(config.path);
|
14 |
|
15 | return function (logObject) {
|
16 | logObject.timestamp = Date.now();
|
17 |
|
18 | let upper = Date.now() + config.logInterval;
|
19 | let lower = Date.now() - config.logInterval;
|
20 |
|
21 |
|
22 | let existingLog = fs.readdirSync(config.path)
|
23 | .sort((a, b) => a < b)
|
24 | .find(fileName => {
|
25 | let fileNumber = Number(fileName.replace('.log', ''));
|
26 | if (fileNumber > upper || fileNumber < lower) {
|
27 | return false;
|
28 | }
|
29 | const stats = fs.statSync(path.join(config.path, fileName));
|
30 | return stats.size < config.maxLogSize;
|
31 | });
|
32 |
|
33 | let logName = existingLog || (Date.now() + '.log');
|
34 |
|
35 | let cache = [];
|
36 | let jsLine = JSON.stringify(logObject, function (key, value) {
|
37 | if (typeof value === 'object' && value !== null) {
|
38 | if (cache.indexOf(value) !== -1) {
|
39 |
|
40 | return;
|
41 | }
|
42 |
|
43 | cache.push(value);
|
44 | }
|
45 | return value;
|
46 | }) + ',';
|
47 |
|
48 | if (null == existingLog) {
|
49 | let increment = 1;
|
50 | while (fs.existsSync(path.join(config.path, logName))) {
|
51 | logName = logName.replace('.log', '').split('-')[0] + '-' + increment + '.log';
|
52 | increment++;
|
53 | }
|
54 | fs.writeFileSync(path.join(config.path, logName), jsLine);
|
55 | }
|
56 | fs.appendFile(path.join(config.path, logName), jsLine, error => {
|
57 | if (error) { throw err };
|
58 | });
|
59 | }
|
60 | } |
\ | No newline at end of file |