User logger in node files

This commit is contained in:
rejas
2020-05-11 07:25:42 +02:00
parent 367233c318
commit f2d03a511e
5 changed files with 60 additions and 54 deletions

View File

@@ -10,12 +10,13 @@ var Utils = require(__dirname + "/utils.js");
var defaultModules = require(__dirname + "/../modules/default/defaultmodules.js"); var defaultModules = require(__dirname + "/../modules/default/defaultmodules.js");
var path = require("path"); var path = require("path");
var Log = require("./logger.js");
// Alias modules mentioned in package.js under _moduleAliases. // Alias modules mentioned in package.js under _moduleAliases.
require("module-alias/register"); require("module-alias/register");
// Get version number. // Get version number.
global.version = JSON.parse(fs.readFileSync("package.json", "utf8")).version; global.version = JSON.parse(fs.readFileSync("package.json", "utf8")).version;
console.log("Starting MagicMirror: v" + global.version); Log.log("Starting MagicMirror: v" + global.version);
// global absolute root path // global absolute root path
global.root_path = path.resolve(__dirname + "/../"); global.root_path = path.resolve(__dirname + "/../");
@@ -33,10 +34,10 @@ if (process.env.MM_PORT) {
// The next part is here to prevent a major exception when there // The next part is here to prevent a major exception when there
// is no internet connection. This could probable be solved better. // is no internet connection. This could probable be solved better.
process.on("uncaughtException", function (err) { process.on("uncaughtException", function (err) {
console.log("Whoops! There was an uncaught exception..."); Log.log("Whoops! There was an uncaught exception...");
console.error(err); Log.error(err);
console.log("MagicMirror will not quit, but it might be a good idea to check why this happened. Maybe no internet connection?"); Log.log("MagicMirror will not quit, but it might be a good idea to check why this happened. Maybe no internet connection?");
console.log("If you think this really is an issue, please open an issue on GitHub: https://github.com/MichMich/MagicMirror/issues"); Log.log("If you think this really is an issue, please open an issue on GitHub: https://github.com/MichMich/MagicMirror/issues");
}); });
/* App - The core app. /* App - The core app.
@@ -50,8 +51,8 @@ var App = function () {
* *
* argument callback function - The callback function. * argument callback function - The callback function.
*/ */
var loadConfig = function (callback) { var loadConfig = function(callback) {
console.log("Loading config ..."); Log.log("Loading config ...");
var defaults = require(__dirname + "/defaults.js"); var defaults = require(__dirname + "/defaults.js");
// For this check proposed to TestSuite // For this check proposed to TestSuite
@@ -69,11 +70,11 @@ var App = function () {
callback(config); callback(config);
} catch (e) { } catch (e) {
if (e.code === "ENOENT") { if (e.code === "ENOENT") {
console.error(Utils.colors.error("WARNING! Could not find config file. Please create one. Starting with default configuration.")); Log.error(Utils.colors.error("WARNING! Could not find config file. Please create one. Starting with default configuration."));
} else if (e instanceof ReferenceError || e instanceof SyntaxError) { } else if (e instanceof ReferenceError || e instanceof SyntaxError) {
console.error(Utils.colors.error("WARNING! Could not validate config file. Starting with default configuration. Please correct syntax errors at or above this line: " + e.stack)); Log.error(Utils.colors.error("WARNING! Could not validate config file. Starting with default configuration. Please correct syntax errors at or above this line: " + e.stack));
} else { } else {
console.error(Utils.colors.error("WARNING! Could not load config file. Starting with default configuration. Error found: " + e)); Log.error(Utils.colors.error("WARNING! Could not load config file. Starting with default configuration. Error found: " + e));
} }
callback(defaults); callback(defaults);
} }
@@ -91,7 +92,11 @@ var App = function () {
} }
}); });
if (usedDeprecated.length > 0) { if (usedDeprecated.length > 0) {
console.warn(Utils.colors.warn("WARNING! Your config is using deprecated options: " + usedDeprecated.join(", ") + ". Check README and CHANGELOG for more up-to-date ways of getting the same functionality.")); Log.warn(Utils.colors.warn(
"WARNING! Your config is using deprecated options: " +
usedDeprecated.join(", ") +
". Check README and CHANGELOG for more up-to-date ways of getting the same functionality.")
);
} }
}; };
@@ -116,7 +121,7 @@ var App = function () {
fs.accessSync(helperPath, fs.R_OK); fs.accessSync(helperPath, fs.R_OK);
} catch (e) { } catch (e) {
loadModule = false; loadModule = false;
console.log("No helper found for module: " + moduleName + "."); Log.log("No helper found for module: " + moduleName + ".");
} }
if (loadModule) { if (loadModule) {
@@ -124,11 +129,11 @@ var App = function () {
var m = new Module(); var m = new Module();
if (m.requiresVersion) { if (m.requiresVersion) {
console.log("Check MagicMirror version for node helper '" + moduleName + "' - Minimum version: " + m.requiresVersion + " - Current version: " + global.version); Log.log("Check MagicMirror version for node helper '" + moduleName + "' - Minimum version: " + m.requiresVersion + " - Current version: " + global.version);
if (cmpVersions(global.version, m.requiresVersion) >= 0) { if (cmpVersions(global.version, m.requiresVersion) >= 0) {
console.log("Version is ok!"); Log.log("Version is ok!");
} else { } else {
console.log("Version is incorrect. Skip module: '" + moduleName + "'"); Log.log("Version is incorrect. Skip module: '" + moduleName + "'");
return; return;
} }
} }
@@ -148,8 +153,8 @@ var App = function () {
* *
* argument module string - The name of the module (including subpath). * argument module string - The name of the module (including subpath).
*/ */
var loadModules = function (modules, callback) { var loadModules = function(modules, callback) {
console.log("Loading module helpers ..."); Log.log("Loading module helpers ...");
var loadNextModule = function () { var loadNextModule = function () {
if (modules.length > 0) { if (modules.length > 0) {
@@ -160,7 +165,7 @@ var App = function () {
}); });
} else { } else {
// All modules are loaded // All modules are loaded
console.log("All module helpers loaded."); Log.log("All module helpers loaded.");
callback(); callback();
} }
}; };
@@ -210,9 +215,9 @@ var App = function () {
} }
} }
loadModules(modules, function () { loadModules(modules, function() {
var server = new Server(config, function (app, io) { var server = new Server(config, function(app, io) {
console.log("Server started ..."); Log.log("Server started ...");
for (var h in nodeHelpers) { for (var h in nodeHelpers) {
var nodeHelper = nodeHelpers[h]; var nodeHelper = nodeHelpers[h];
@@ -221,7 +226,7 @@ var App = function () {
nodeHelper.start(); nodeHelper.start();
} }
console.log("Sockets connected & modules started ..."); Log.log("Sockets connected & modules started ...");
if (typeof callback === "function") { if (typeof callback === "function") {
callback(config); callback(config);
@@ -252,10 +257,8 @@ var App = function () {
* this.stop() is called by app.on("before-quit"... in `electron.js` * this.stop() is called by app.on("before-quit"... in `electron.js`
*/ */
process.on("SIGINT", () => { process.on("SIGINT", () => {
console.log("[SIGINT] Received. Shutting down server..."); Log.log("[SIGINT] Received. Shutting down server...");
setTimeout(() => { setTimeout(() => { process.exit(0); }, 3000); // Force quit after 3 seconds
process.exit(0);
}, 3000); // Force quit after 3 seconds
this.stop(); this.stop();
process.exit(0); process.exit(0);
}); });
@@ -263,10 +266,8 @@ var App = function () {
/* We also need to listen to SIGTERM signals so we stop everything when we are asked to stop by the OS. /* We also need to listen to SIGTERM signals so we stop everything when we are asked to stop by the OS.
*/ */
process.on("SIGTERM", () => { process.on("SIGTERM", () => {
console.log("[SIGTERM] Received. Shutting down server..."); Log.log("[SIGTERM] Received. Shutting down server...");
setTimeout(() => { setTimeout(() => { process.exit(0); }, 3000); // Force quit after 3 seconds
process.exit(0);
}, 3000); // Force quit after 3 seconds
this.stop(); this.stop();
process.exit(0); process.exit(0);
}); });

View File

@@ -1,7 +1,8 @@
"use strict"; "use strict";
const electron = require("electron"); const electron = require("electron");
const core = require(__dirname + "/app.js"); const core = require("./app.js");
const Log = require("./logger.js");
// Config // Config
var config = process.env.config ? JSON.parse(process.env.config) : {}; var config = process.env.config ? JSON.parse(process.env.config) : {};
@@ -85,8 +86,8 @@ function createWindow() {
// This method will be called when Electron has finished // This method will be called when Electron has finished
// initialization and is ready to create browser windows. // initialization and is ready to create browser windows.
app.on("ready", function () { app.on("ready", function() {
console.log("Launching application."); Log.log("Launching application.");
createWindow(); createWindow();
}); });
@@ -110,7 +111,7 @@ app.on("activate", function () {
* core.stop() is called by process.on("SIGINT"... in `app.js` * core.stop() is called by process.on("SIGINT"... in `app.js`
*/ */
app.on("before-quit", (event) => { app.on("before-quit", (event) => {
console.log("Shutting down server..."); Log.log("Shutting down server...");
event.preventDefault(); event.preventDefault();
setTimeout(() => { setTimeout(() => {
process.exit(0); process.exit(0);

View File

@@ -5,20 +5,21 @@
* MIT Licensed. * MIT Licensed.
*/ */
const Class = require("./class.js"); const Class = require("./class.js");
const Log = require("./logger.js");
const express = require("express"); const express = require("express");
var NodeHelper = Class.extend({ var NodeHelper = Class.extend({
init: function () { init: function() {
console.log("Initializing new module helper ..."); Log.log("Initializing new module helper ...");
}, },
loaded: function (callback) { loaded: function(callback) {
console.log("Module helper loaded: " + this.name); Log.log("Module helper loaded: " + this.name);
callback(); callback();
}, },
start: function () { start: function() {
console.log("Starting module helper: " + this.name); Log.log("Starting module helper: " + this.name);
}, },
/* stop() /* stop()
@@ -27,8 +28,8 @@ var NodeHelper = Class.extend({
* gracefully exit the module. * gracefully exit the module.
* *
*/ */
stop: function () { stop: function() {
console.log("Stopping module helper: " + this.name); Log.log("Stopping module helper: " + this.name);
}, },
/* socketNotificationReceived(notification, payload) /* socketNotificationReceived(notification, payload)
@@ -37,8 +38,8 @@ var NodeHelper = Class.extend({
* argument notification string - The identifier of the notification. * argument notification string - The identifier of the notification.
* argument payload mixed - The payload of the notification. * argument payload mixed - The payload of the notification.
*/ */
socketNotificationReceived: function (notification, payload) { socketNotificationReceived: function(notification, payload) {
console.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload); Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
}, },
/* setName(name) /* setName(name)
@@ -92,7 +93,7 @@ var NodeHelper = Class.extend({
var self = this; var self = this;
self.io = io; self.io = io;
console.log("Connecting socket for: " + this.name); Log.log("Connecting socket for: " + this.name);
var namespace = this.name; var namespace = this.name;
io.of(namespace).on("connection", function (socket) { io.of(namespace).on("connection", function (socket) {
// add a catch all event. // add a catch all event.
@@ -107,7 +108,7 @@ var NodeHelper = Class.extend({
// register catch all. // register catch all.
socket.on("*", function (notification, payload) { socket.on("*", function (notification, payload) {
if (notification !== "*") { if (notification !== "*") {
//console.log('received message in namespace: ' + namespace); //Log.log('received message in namespace: ' + namespace);
self.socketNotificationReceived(notification, payload); self.socketNotificationReceived(notification, payload);
} }
}); });

View File

@@ -4,14 +4,15 @@
* By Michael Teeuw https://michaelteeuw.nl * By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed. * MIT Licensed.
*/ */
var express = require("express"); var express = require("express");
var app = require("express")(); var app = require("express")();
var path = require("path"); var path = require("path");
var ipfilter = require("express-ipfilter").IpFilter; var ipfilter = require("express-ipfilter").IpFilter;
var fs = require("fs"); var fs = require("fs");
var helmet = require("helmet"); var helmet = require("helmet");
var Utils = require(__dirname + "/utils.js");
var Log = require("./logger.js");
var Utils = require("./utils.js");
var Server = function (config, callback) { var Server = function (config, callback) {
var port = config.port; var port = config.port;
@@ -31,12 +32,12 @@ var Server = function (config, callback) {
} }
var io = require("socket.io")(server); var io = require("socket.io")(server);
console.log("Starting server on port " + port + " ... "); Log.log("Starting server on port " + port + " ... ");
server.listen(port, config.address ? config.address : "localhost"); server.listen(port, config.address ? config.address : "localhost");
if (config.ipWhitelist instanceof Array && config.ipWhitelist.length === 0) { if (config.ipWhitelist instanceof Array && config.ipWhitelist.length === 0) {
console.info(Utils.colors.warn("You're using a full whitelist configuration to allow for all IPs")); Log.info(Utils.colors.warn("You're using a full whitelist configuration to allow for all IPs"));
} }
app.use(function (req, res, next) { app.use(function (req, res, next) {
@@ -44,7 +45,7 @@ var Server = function (config, callback) {
if (err === undefined) { if (err === undefined) {
return next(); return next();
} }
console.log(err.message); Log.log(err.message);
res.status(403).send("This device is not allowed to access your mirror. <br> Please check your config.js or config.js.sample to change this."); res.status(403).send("This device is not allowed to access your mirror. <br> Please check your config.js or config.js.sample to change this.");
}); });
}); });

View File

@@ -1,6 +1,8 @@
var app = require("../js/app.js"); const app = require("../js/app.js");
app.start(function (config) { const Log = require("../js/logger.js");
app.start(function(config) {
var bindAddress = config.address ? config.address : "localhost"; var bindAddress = config.address ? config.address : "localhost";
var httpType = config.useHttps ? "https" : "http"; var httpType = config.useHttps ? "https" : "http";
console.log("\nReady to go! Please point your browser to: " + httpType + "://" + bindAddress + ":" + config.port); Log.log("\nReady to go! Please point your browser to: " + httpType + "://" + bindAddress + ":" + config.port);
}); });