diff options
Diffstat (limited to 'services/data-logger.js')
| -rw-r--r-- | services/data-logger.js | 41 |
1 files changed, 30 insertions, 11 deletions
diff --git a/services/data-logger.js b/services/data-logger.js index 9c23de1..700bed0 100644 --- a/services/data-logger.js +++ b/services/data-logger.js @@ -1,6 +1,9 @@ const fs = require('fs'); +const path = require('path'); +const shell = require('shelljs'); const dataBroadcaster = require('./data-broadcaster'); +let logDirPath; let logIntervalMs; let maxLogEntries; @@ -8,16 +11,30 @@ loadLogConfig(); function loadLogConfig() { try { - let config = JSON.parse(fs.readFileSync('logger-config.json', 'utf8')); + // Use logger config file specified on command line, otherwise use default one. + if (process.argv.length > 2) { + loggerConfigPath = process.argv[2]; + } else { + loggerConfigPath = 'logger-config.json'; + } + console.log('Logger config file: "' + loggerConfigPath + '"') + + let config = JSON.parse(fs.readFileSync(loggerConfigPath, 'utf8')); + logDirPath = config.logDirPath; logIntervalMs = (config.logIntervalSeconds * 1000); maxLogEntries = config.maxLogEntries; } catch (err) { console.warn('Error reading logger config. Reverting to defaults.', err); + logDirPath = '.' // Current directory logIntervalMs = 60000 // 1 min maxLogEntries = 1440 // 24 hrs at 1/min - } + } + + // Create log directory path if it doesn't already exist. + console.log('Log directory path: "' + logDirPath + '"') + shell.mkdir('-p', logDirPath); } function startLogging(device) { @@ -26,15 +43,17 @@ function startLogging(device) { } function writeLog(filePath, log) { - fs.writeFile(filePath, JSON.stringify(log), { flag: 'w' }, (err) => { - if (err) { - console.warn('Error writing log for ' + device.alias + ' [' + device.deviceId + ']', err); - } - }); + try { + // Switched to sync write for now. TODO investigate issue from PR #19 + fs.writeFileSync(filePath, JSON.stringify(log), { flag: 'w' }); + } + catch (err) { + console.warn('Error writing log for ' + device.alias + ' [' + device.deviceId + ']', err); + } } function getLogEntries(filePath, callback) { - + fs.access(filePath, fs.constants.F_OK, (err) => { if(err) { // No log file, init empty one @@ -68,7 +87,7 @@ function log(device) { getLogEntries(filePath, (entries) => { entries.push(logEntry) - + // Remove old entries entries.splice(0, entries.length - maxLogEntries); @@ -80,7 +99,7 @@ function log(device) { } function getLogPath(deviceId) { - return deviceId + '-log.json'; + return path.join(logDirPath, deviceId + '-log.json'); } function getLogEntriesForDevice(deviceId, callback) { @@ -91,4 +110,4 @@ module.exports = { startLogging: startLogging, log: log, getLogEntriesForDevice: getLogEntriesForDevice -}
\ No newline at end of file +} |