dcp-worker 3.2.30-8 → 3.2.30-9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,42 +3,65 @@
3
3
  * @author Eddie Roosenmaallen <eddie@kingsds.network>
4
4
  * @date August 2022
5
5
  *
6
- * This logger module redirects logs to the Windows event-log, writing all
7
- * console logs to it.
6
+ * This logger module emits events to the Windows event-log, writing all
7
+ * console logs to it. Most worker events are passed through to be handled
8
+ * by the console logger.
9
+ *
10
+ * @TODO: This could likely be improved by handling worker events directly
11
+ * and emitting events to the event log more deliberately than just
12
+ * redirecting the base console output. ~ER20220831
8
13
  */
9
- 'use strict';
10
14
 
11
- const os = require('os');
12
- if (os.platform() !== 'win32')
13
- throw new Error(`Windows Event Log module is not supported on ${os.platform()}`);
15
+ require('./common-types');
16
+ const consoleLogger = require('./console');
14
17
 
15
18
  const { EventLog } = require('node-eventlog');
16
19
 
17
20
  // Copy the original global console object's properties onto a backup
18
21
  const _console = Object.assign({}, console);
19
22
 
20
- /**
21
- * Initialize the eventlog worker logger
22
- *
23
- * @param {object} options Options for logger behaviour (passed
24
- * through to consoleLogger)
25
- */
26
- exports.init = function eventLog$$init(options)
27
- {
28
- exports._processName = require('path').basename(process.mainModule.filename || process.argv0);
29
- const source = options.source || exports._processName || 'dcp-worker';
30
- exports._eventLog = new EventLog(source);
31
- require('../startWorkerLogger').inspectOptions.colors = false;
32
- exports.at = log;
33
- }
34
23
 
35
- /**
36
- * @param {string} level The node log level to log at
37
- * @param {[string]} items An array of strings to log as a single message
38
- */
39
- function log(level, ...items)
40
- {
41
- {
24
+ const eventlogLogger = {
25
+ /**
26
+ * Initialize the eventlog worker logger
27
+ *
28
+ * @param {Worker} worker DCP Worker object to log
29
+ * @param {object} options Options for logger behaviour (passed
30
+ * through to consoleLogger)
31
+ */
32
+ init(worker, options) {
33
+ consoleLogger.init(worker, options);
34
+
35
+ this._processName = require('path').basename(process.mainModule.filename || process.argv0);
36
+ const source = options.source || this._processName || 'dcp-worker';
37
+ // _console.log(`036: creating new EventLog(${source}) client...`);
38
+ this._eventLog = new EventLog(source);
39
+
40
+ ['debug','error','info','log','warn'].forEach(level => {
41
+ console[level] = (...args) => this._log(level, ...args);
42
+ });
43
+ },
44
+
45
+ _log(level, ...items) {
46
+ const strBuilder = [`${this._processName}[${process.pid}]:`];
47
+
48
+ items.forEach(i => {
49
+ try {
50
+ switch (typeof i) {
51
+ case 'object':
52
+ strBuilder.push(JSON.stringify(i));
53
+ break;
54
+ default:
55
+ strBuilder.push(String(i));
56
+ }
57
+ }
58
+ catch (e) {
59
+ if (e instanceof TypeError) {
60
+ strBuilder.push('[encoding error: ' + e.message + ']');
61
+ }
62
+ }
63
+ });
64
+
42
65
  // Use the string log-level to look up the severity number:
43
66
  let severity = {
44
67
  error: 'error',
@@ -48,9 +71,18 @@ function log(level, ...items)
48
71
  debug: 'info',
49
72
  }[level];
50
73
 
51
- return exports._eventLog.log(items.join(' '), severity).catch(error => {
74
+ // _console.debug(`074: about to actually log a line:`, strBuilder, severity);
75
+ return this._eventLog.log(strBuilder.join(' '), severity).catch(error => {
52
76
  if (error)
53
77
  _console.error('255: Unexpected error writing to event log:', error);
54
78
  });
55
79
  }
80
+ };
81
+
82
+ // necessary to keep `this` pointing at the correct thing when we call
83
+ for (const [prop, value] of Object.entries(consoleLogger))
84
+ {
85
+ if (typeof value === 'function')
86
+ exports[prop] = value.bind(consoleLogger);
56
87
  }
88
+ Object.assign(exports, eventlogLogger);
@@ -4,96 +4,122 @@
4
4
  * @date August 2022
5
5
  *
6
6
  * This logger module maintains a log file, writing all console logs to it.
7
+ * Most worker events are passed through to the console logger.
7
8
  */
8
- 'use strict';
9
+
10
+ require('./common-types');
11
+ const consoleLogger = require('./console');
9
12
 
10
13
  // Copy the original global console object's properties onto a backup
11
14
  const _console = Object.assign({}, console);
12
15
 
13
- /**
14
- * Initialize the logfile worker logger
15
- *
16
- * @param {object} options Options for logger behaviour
17
- * @param {string} options.filepath Path to worker file; default: ./dcp-worker.log
18
- * @param {boolean} options.truncate If true, logfile will be cleared at worker startup
19
- */
20
- exports.init = function init(options)
21
- {
22
- delete exports.init; // singleton
23
- options.verbose >= 3 && _console.debug('050: constructing LogfileConsole', options.logfile, options);
24
- getLogFile(options);
25
- require('../startWorkerLogger').inspectOptions.colors = Boolean(process.env.FORCE_COLOR);
26
-
27
- // on SIGHUP, close the output stream and open a new one
28
- process.on('SIGHUP', () => {
29
- getLogFile(options);
30
- });
31
-
32
- exports.at = log;
33
- }
16
+ const logfileLogger = {
17
+ /**
18
+ * Initialize the logfile worker logger
19
+ *
20
+ * @param {Worker} worker DCP Worker object to log
21
+ * @param {object} options Options for logger behaviour
22
+ * @param {string} options.filepath Path to worker file; default: ./dcp-worker.log
23
+ * @param {boolean} options.truncate If true, logfile will be cleared at worker startup
24
+ */
25
+ init(worker, options) {
26
+ consoleLogger.init(worker, options);
27
+
28
+ this._filepath = options.filepath || './dcp-worker.log';
29
+ this.options = options;
30
+
31
+ options.verbose >= 3 && console.debug('050: constructing LogfileConsole', this._filepath, options);
32
+
33
+ this._getLogFile();
34
+
35
+ // on SIGHUP, close the output stream and open a new one
36
+ process.on('SIGHUP', () => {
37
+ this._getLogFile(true);
38
+ });
34
39
 
35
- /**
36
- * Return a handle to the WritableStream for this logger, creating one if
37
- * necessary.
38
- *
39
- * @return {fs.WriteStream}
40
- */
41
- function getLogFile(options)
42
- {
43
- {
40
+ ['debug','error','info','log','warn'].forEach(level => {
41
+ console[level] = (...args) => this._log(level, ...args);
42
+ });
43
+ },
44
+
45
+ /**
46
+ * Return a handle to the WritableStream for this logger, creating one if
47
+ * necessary.
48
+ *
49
+ * @param {boolean} forceNew If truthy, close any existing stream and open
50
+ * a new one
51
+ * @return {fs.WriteStream}
52
+ */
53
+ _getLogFile(forceNew = false) {
44
54
  const fs = require('fs');
45
55
 
46
- if (getLogFile._file)
56
+ if (this._file)
47
57
  {
58
+ if (!forceNew)
59
+ return this._file;
60
+
48
61
  try
49
62
  {
50
- getLogFile._file.end();
63
+ this._file.end();
51
64
  }
52
65
  catch (err)
53
66
  {
54
67
  console.error('061: failed to close old log file:', err);
55
68
  }
56
- getLogFile._file = false;
69
+ this._file = false;
57
70
  }
58
71
 
59
- const fileOptions = {
60
- flags: options.truncate ? 'w' : 'a', // NYI: cli --truncate
72
+ const options = {
73
+ flags: this.options.truncate ? 'w' : 'a', // NYI: cli --truncate
61
74
  }
62
75
 
63
- const file = getLogFile._file = fs.createWriteStream(options.logfile, fileOptions);
76
+ const file = this._file = fs.createWriteStream(this._filepath, options);
64
77
 
65
78
  // On error, close & recreate the log file
66
79
  file.on('error', err => {
67
80
  _console.error('082: console-patch::LogFileConsole write error:', err);
68
81
 
69
- getLogFile(options);
82
+ this._getLogFile(true);
70
83
  });
71
84
 
72
85
  return file;
73
- }
74
- }
75
-
76
- /** Write a log line to the output file.
77
- *
78
- * current outputStream.
79
- * @param {string} level Log level.
80
- * @param {any} ...items Items to log.
81
- */
82
- function log(level, ...items)
83
- {
84
- {
85
- const logPrefix = [
86
+ },
87
+
88
+ /** Write a log line to the output file. Items will be converted to strings as
89
+ * possible and concatenated after the log-level and timestamp, then written to the
90
+ * current outputStream.
91
+ * @param {string} level Log level.
92
+ * @param {any} ...items Items to log.
93
+ */
94
+ _log(level = 'none', ...items) {
95
+ const strBuilder = [
86
96
  (new Date()).toISOString(),
87
97
  level,
88
98
  ];
89
-
90
- const logElements = logPrefix.concat(items);
91
-
99
+
100
+ items.forEach(i => {
101
+ try {
102
+ switch (typeof i) {
103
+ case 'object':
104
+ strBuilder.push(JSON.stringify(i));
105
+ default:
106
+ strBuilder.push(String(i));
107
+ }
108
+ }
109
+ catch (e) {
110
+ if (e instanceof TypeError) {
111
+ strBuilder.push('[encoding error: ' + e.message + ']');
112
+ }
113
+ }
114
+ });
115
+
92
116
  try {
93
- getLogFile._file.write(logElements.join(' ') + '\n');
117
+ this._file.write(strBuilder.join(' ') + '\n');
94
118
  }
95
119
  catch (error) {
96
120
  _console.error('131: Unexpected error writing to log file:', error);
97
121
  }
98
- }
99
- }
122
+ },
123
+ };
124
+
125
+ Object.assign(exports, consoleLogger, logfileLogger);
@@ -4,45 +4,66 @@
4
4
  * @date August 2022
5
5
  *
6
6
  * This logger module emits log lines to a remote syslogd, writing all
7
- * console logs to it.
7
+ * console logs to it. Most worker events are passed through to be handled
8
+ * by the console logger.
9
+ *
10
+ * @TODO: This could likely be improved by handling worker events directly
11
+ * and emitting events to the event log more deliberately than just
12
+ * redirecting the base console output. ~ER20220831
8
13
  */
9
- 'use strict';
10
14
 
11
- const os = require('os');
12
- const syslog = require('syslog-client');
13
- const process = require('process');
15
+ require('./common-types');
16
+ const consoleLogger = require('./console');
17
+
18
+ const syslog = require('syslog-client');
14
19
 
15
20
  // Copy the original global console object's properties onto a backup
16
21
  const _console = Object.assign({}, console);
17
- var syslogClient;
18
- var processName;
19
22
 
20
- /**
21
- * Initialize the syslog worker logger
22
- *
23
- * @param {object} cliArgs Options for logger behaviour (passed
24
- * through to consoleLogger)
25
- */
26
- exports.init = function syslog$$init(cliArgs)
27
- {
28
- {
23
+
24
+ const eventlogLogger = {
25
+ /**
26
+ * Initialize the syslog worker logger
27
+ *
28
+ * @param {Worker} worker DCP Worker object to log
29
+ * @param {object} options Options for logger behaviour (passed
30
+ * through to consoleLogger)
31
+ */
32
+ init(worker, options) {
33
+ consoleLogger.init(worker, options);
34
+
35
+ this.options = Object.assign({}, options);
29
36
  const syslogOptions = {
30
- syslogHostname: os.hostname(),
31
- transport: cliArgs.syslogTransport || 'udp', // tcp, udp, unix, tls
32
- port: cliArgs.syslogPort,
33
- facility: syslog.Facility[cliArgs.syslogFacility[0].toUpperCase() + cliArgs.syslogFacility.slice(1)],
37
+ transport: options.syslogTransport || 'udp', // tcp, udp, unix, tls
38
+ port: options.syslogPort || 514,
34
39
  }
35
40
 
36
- syslogClient = syslog.createClient(cliArgs.syslogAddress || '127.0.0.1', syslogOptions);
37
- processName = require('path').basename(process.mainModule.filename || process.argv0);
38
- exports.close = () => syslogClient.close();
39
- }
40
- }
41
+ this._syslog = syslog.createClient(options.syslogAddress || '127.0.0.1', options);
42
+ this._processName = require('path').basename(process.mainModule.filename || process.argv0);
41
43
 
42
- function log(level, ...argv)
43
- {
44
- {
45
- const logPrefix = `${processName}[${process.pid}]: `;
44
+ ['debug','error','info','log','warn'].forEach(level => {
45
+ console[level] = (...args) => this._log(level, ...args);
46
+ });
47
+ },
48
+
49
+ _log(level, ...items) {
50
+ const strBuilder = [`${this._processName}[${process.pid}]:`];
51
+
52
+ items.forEach(i => {
53
+ try {
54
+ switch (typeof i) {
55
+ case 'object':
56
+ strBuilder.push(JSON.stringify(i));
57
+ default:
58
+ strBuilder.push(String(i));
59
+ }
60
+ }
61
+ catch (e) {
62
+ if (e instanceof TypeError) {
63
+ strBuilder.push('[encoding error: ' + e.message + ']');
64
+ }
65
+ }
66
+ });
46
67
 
47
68
  // Use the string log-level to look up the severity number:
48
69
  let severity = {
@@ -53,17 +74,18 @@ function log(level, ...argv)
53
74
  debug: syslog.Severity.Debug,
54
75
  }[level];
55
76
 
56
- const logMessages = argv.join(' ').split('\n');
57
-
58
- for (let logMessage of logMessages)
59
- {
60
- logMessage = logPrefix + logMessage;
61
- syslogClient.log(logMessage, { severity }, error => {
62
- if (error)
63
- _console.error('168: Unexpected error writing to syslog:');
64
- });
65
- }
77
+ this._syslog.log(strBuilder.join(' '), {
78
+ severity,
79
+ }, error => {
80
+ if (error)
81
+ _console.error('168: Unexpected error writing to syslog:', error);
82
+ });
66
83
  }
67
- }
84
+ };
68
85
 
69
- exports.at = log;
86
+ for (const [prop, value] of Object.entries(consoleLogger))
87
+ {
88
+ if (typeof value === 'function')
89
+ exports[prop] = value.bind(consoleLogger);
90
+ }
91
+ Object.assign(exports, eventlogLogger);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dcp-worker",
3
- "version": "3.2.30-8",
3
+ "version": "3.2.30-9",
4
4
  "description": "JavaScript portion of DCP Workers for Node.js",
5
5
  "main": "bin/dcp-worker",
6
6
  "keywords": [
@@ -12,7 +12,7 @@
12
12
  },
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "git+ssh://git@gitlab.com/Distributed-Compute-Protocol/dcp-worker.git"
15
+ "url": "git@github.com:Distributed-Compute-Labs/dcp-worker.git"
16
16
  },
17
17
  "license": "MIT",
18
18
  "author": "Kings Distributed Systems",
@@ -38,26 +38,17 @@
38
38
  "blessed-contrib": "^4.11.0",
39
39
  "chalk": "^4.1.0",
40
40
  "dcp-client": "4.3.0-4",
41
- "semver": "^7.3.8",
42
- "syslog-client": "1.1.1"
41
+ "semver": "^7.3.8"
43
42
  },
44
43
  "optionalDependencies": {
45
44
  "telnet-console": "^1.0.4"
46
45
  },
47
46
  "devDependencies": {
48
47
  "@kingsds/eslint-config": "^1.0.1",
49
- "eslint": ">=8"
50
- },
51
- "peerDependencies": {
52
- "node-eventlog": "https://gitpkg.now.sh/Distributive-Network/node-eventlog/package?dcp/0.0.1"
53
- },
54
- "peerDependenciesMeta": {
55
- "node-eventlog": {
56
- "optional": true
57
- }
48
+ "eslint": "7.30.0"
58
49
  },
59
50
  "engines": {
60
- "node": ">=18",
61
- "npm": ">=7"
51
+ "node": ">=16",
52
+ "npm": ">=6"
62
53
  }
63
54
  }