diff --git a/server/database.js b/server/database.js index 5b9eab1c..b398101e 100644 --- a/server/database.js +++ b/server/database.js @@ -1,7 +1,7 @@ const fs = require("fs"); const { R } = require("redbean-node"); const { setSetting, setting } = require("./util-server"); -const { log_info, log_debug, log_error, sleep } = require("../src/util"); +const { log, sleep } = require("../src/util"); const dayjs = require("dayjs"); const knex = require("knex"); @@ -80,7 +80,7 @@ class Database { fs.mkdirSync(Database.uploadDir, { recursive: true }); } - log_info("db", `Data Dir: ${Database.dataDir}`); + log.info("db", `Data Dir: ${Database.dataDir}`); } static async connect(testMode = false, autoloadModels = true, noLog = false) { @@ -135,10 +135,10 @@ class Database { await R.exec("PRAGMA synchronous = FULL"); if (!noLog) { - log_info("db", "SQLite config:"); - log_info("db", await R.getAll("PRAGMA journal_mode")); - log_info("db", await R.getAll("PRAGMA cache_size")); - log_info("db", "SQLite Version: " + await R.getCell("SELECT sqlite_version()")); + log.info("db", "SQLite config:"); + log.info("db", await R.getAll("PRAGMA journal_mode")); + log.info("db", await R.getAll("PRAGMA cache_size")); + log.info("db", "SQLite Version: " + await R.getCell("SELECT sqlite_version()")); } } @@ -149,15 +149,15 @@ class Database { version = 0; } - log_info("db", "Your database version: " + version); - log_info("db", "Latest database version: " + this.latestVersion); + log.info("db", "Your database version: " + version); + log.info("db", "Latest database version: " + this.latestVersion); if (version === this.latestVersion) { - log_info("db", "Database patch not needed"); + log.info("db", "Database patch not needed"); } else if (version > this.latestVersion) { - log_info("db", "Warning: Database version is newer than expected"); + log.info("db", "Warning: Database version is newer than expected"); } else { - log_info("db", "Database patch is needed"); + log.info("db", "Database patch is needed"); this.backup(version); @@ -165,17 +165,17 @@ class Database { try { for (let i = version + 1; i <= this.latestVersion; i++) { const sqlFile = `./db/patch${i}.sql`; - log_info("db", `Patching ${sqlFile}`); + log.info("db", `Patching ${sqlFile}`); await Database.importSQLFile(sqlFile); - log_info("db", `Patched ${sqlFile}`); + log.info("db", `Patched ${sqlFile}`); await setSetting("database_version", i); } } catch (ex) { await Database.close(); - log_error("db", ex); - log_error("db", "Start Uptime-Kuma failed due to issue patching the database"); - log_error("db", "Please submit a bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); + log.error("db", ex); + log.error("db", "Start Uptime-Kuma failed due to issue patching the database"); + log.error("db", "Please submit a bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); this.restore(); process.exit(1); @@ -191,15 +191,15 @@ class Database { * @returns {Promise} */ static async patch2() { - log_info("db", "Database Patch 2.0 Process"); + log.info("db", "Database Patch 2.0 Process"); let databasePatchedFiles = await setting("databasePatchedFiles"); if (! databasePatchedFiles) { databasePatchedFiles = {}; } - log_debug("db", "Patched files:"); - log_debug("db", databasePatchedFiles); + log.debug("db", "Patched files:"); + log.debug("db", databasePatchedFiles); try { for (let sqlFilename in this.patchList) { @@ -207,15 +207,15 @@ class Database { } if (this.patched) { - log_info("db", "Database Patched Successfully"); + log.info("db", "Database Patched Successfully"); } } catch (ex) { await Database.close(); - log_error("db", ex); - log_error("db", "Start Uptime-Kuma failed due to issue patching the database"); - log_error("db", "Please submit the bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); + log.error("db", ex); + log.error("db", "Start Uptime-Kuma failed due to issue patching the database"); + log.error("db", "Please submit the bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); this.restore(); @@ -302,16 +302,16 @@ class Database { let value = this.patchList[sqlFilename]; if (! value) { - log_info("db", sqlFilename + " skip"); + log.info("db", sqlFilename + " skip"); return; } // Check if patched if (! databasePatchedFiles[sqlFilename]) { - log_info("db", sqlFilename + " is not patched"); + log.info("db", sqlFilename + " is not patched"); if (value.parents) { - log_info("db", sqlFilename + " need parents"); + log.info("db", sqlFilename + " need parents"); for (let parentSQLFilename of value.parents) { await this.patch2Recursion(parentSQLFilename, databasePatchedFiles); } @@ -319,14 +319,14 @@ class Database { this.backup(dayjs().format("YYYYMMDDHHmmss")); - log_info("db", sqlFilename + " is patching"); + log.info("db", sqlFilename + " is patching"); this.patched = true; await this.importSQLFile("./db/" + sqlFilename); databasePatchedFiles[sqlFilename] = true; - log_info("db", sqlFilename + " was patched successfully"); + log.info("db", sqlFilename + " was patched successfully"); } else { - log_debug("db", sqlFilename + " is already patched, skip"); + log.debug("db", sqlFilename + " is already patched, skip"); } } @@ -378,7 +378,7 @@ class Database { }; process.addListener("unhandledRejection", listener); - log_info("db", "Closing the database"); + log.info("db", "Closing the database"); while (true) { Database.noReject = true; @@ -388,10 +388,10 @@ class Database { if (Database.noReject) { break; } else { - log_info("db", "Waiting to close the database"); + log.info("db", "Waiting to close the database"); } } - log_info("db", "SQLite closed"); + log.info("db", "SQLite closed"); process.removeListener("unhandledRejection", listener); } @@ -403,7 +403,7 @@ class Database { */ static backup(version) { if (! this.backupPath) { - log_info("db", "Backing up the database"); + log.info("db", "Backing up the database"); this.backupPath = this.dataDir + "kuma.db.bak" + version; fs.copyFileSync(Database.path, this.backupPath); @@ -426,7 +426,7 @@ class Database { */ static restore() { if (this.backupPath) { - log_error("db", "Patching the database failed!!! Restoring the backup"); + log.error("db", "Patching the database failed!!! Restoring the backup"); const shmPath = Database.path + "-shm"; const walPath = Database.path + "-wal"; @@ -445,7 +445,7 @@ class Database { fs.unlinkSync(walPath); } } catch (e) { - log_error("db", "Restore failed; you may need to restore the backup manually"); + log.error("db", "Restore failed; you may need to restore the backup manually"); process.exit(1); } @@ -461,14 +461,14 @@ class Database { } } else { - log_info("db", "Nothing to restore"); + log.info("db", "Nothing to restore"); } } static getSize() { - log_debug("db", "Database.getSize()"); + log.debug("db", "Database.getSize()"); let stats = fs.statSync(Database.path); - log_debug("db", stats); + log.debug("db", stats); return stats.size; } diff --git a/server/image-data-uri.js b/server/image-data-uri.js index 84d2990a..063f7090 100644 --- a/server/image-data-uri.js +++ b/server/image-data-uri.js @@ -3,13 +3,13 @@ Modified with 0 dependencies */ let fs = require("fs"); -const { log_error } = require("../src/util"); +const { log } = require("../src/util"); let ImageDataURI = (() => { function decode(dataURI) { if (!/data:image\//.test(dataURI)) { - log_error("image-data-uri", "It seems that it is not an Image Data URI. Couldn't match \"data:image/\""); + log.error("image-data-uri", "It seems that it is not an Image Data URI. Couldn't match \"data:image/\""); return null; } @@ -23,7 +23,7 @@ let ImageDataURI = (() => { function encode(data, mediaType) { if (!data || !mediaType) { - log_error("image-data-uri", "Missing some of the required params: data, mediaType"); + log.error("image-data-uri", "Missing some of the required params: data, mediaType"); return null; } diff --git a/server/jobs.js b/server/jobs.js index 7ad670f6..739e867d 100644 --- a/server/jobs.js +++ b/server/jobs.js @@ -1,7 +1,7 @@ const path = require("path"); const Bree = require("bree"); const { SHARE_ENV } = require("worker_threads"); -const { log_info } = require("../src/util"); +const { log } = require("../src/util"); let bree; const jobs = [ { @@ -19,7 +19,7 @@ const initBackgroundJobs = function (args) { workerData: args, }, workerMessageHandler: (message) => { - log_info("jobs", message); + log.info("jobs", message); } }); diff --git a/server/logger.js b/server/logger.js new file mode 100644 index 00000000..e69de29b diff --git a/server/model/monitor.js b/server/model/monitor.js index 7d3a03ad..4146bd3c 100644 --- a/server/model/monitor.js +++ b/server/model/monitor.js @@ -6,7 +6,7 @@ dayjs.extend(utc); dayjs.extend(timezone); const axios = require("axios"); const { Prometheus } = require("../prometheus"); -const { log_info, log_debug, log_error, log_warn, UP, DOWN, PENDING, flipStatus, TimeLogger } = require("../../src/util"); +const { log, UP, DOWN, PENDING, flipStatus, TimeLogger } = require("../../src/util"); const { tcping, ping, dnsResolve, checkCertificate, checkStatusCode, getTotalClientInRoom, setting, errorLog } = require("../util-server"); const { R } = require("redbean-node"); const { BeanModel } = require("redbean-node/dist/bean-model"); @@ -193,7 +193,7 @@ class Monitor extends BeanModel { rejectUnauthorized: !this.getIgnoreTls(), }; - log_debug("monitor", `[${this.name}] Prepare Options for axios`); + log.debug("monitor", `[${this.name}] Prepare Options for axios`); const options = { url: this.url, @@ -230,8 +230,8 @@ class Monitor extends BeanModel { options.httpsAgent = new https.Agent(httpsAgentOptions); } - log_debug("monitor", `[${this.name}] Axios Options: ${JSON.stringify(options)}`); - log_debug("monitor", `[${this.name}] Axios Request`); + log.debug("monitor", `[${this.name}] Axios Options: ${JSON.stringify(options)}`); + log.debug("monitor", `[${this.name}] Axios Request`); let res = await axios.request(options); bean.msg = `${res.status} - ${res.statusText}`; @@ -240,30 +240,30 @@ class Monitor extends BeanModel { // Check certificate if https is used let certInfoStartTime = dayjs().valueOf(); if (this.getUrl()?.protocol === "https:") { - log_debug("monitor", `[${this.name}] Check cert`); + log.debug("monitor", `[${this.name}] Check cert`); try { let tlsInfoObject = checkCertificate(res); tlsInfo = await this.updateTlsInfo(tlsInfoObject); if (!this.getIgnoreTls() && this.isEnabledExpiryNotification()) { - log_debug("monitor", `[${this.name}] call sendCertNotification`); + log.debug("monitor", `[${this.name}] call sendCertNotification`); await this.sendCertNotification(tlsInfoObject); } } catch (e) { if (e.message !== "No TLS certificate in response") { - log_error("monitor", "Caught error"); - log_error("monitor", e.message); + log.error("monitor", "Caught error"); + log.error("monitor", e.message); } } } if (process.env.TIMELOGGER === "1") { - log_debug("monitor", "Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms"); + log.debug("monitor", "Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms"); } if (process.env.UPTIME_KUMA_LOG_RESPONSE_BODY_MONITOR_ID == this.id) { - log_info("monitor", res.data); + log.info("monitor", res.data); } if (this.type === "http") { @@ -343,7 +343,7 @@ class Monitor extends BeanModel { time ]); - log_debug("monitor", "heartbeatCount" + heartbeatCount + " " + time); + log.debug("monitor", "heartbeatCount" + heartbeatCount + " " + time); if (heartbeatCount <= 0) { // Fix #922, since previous heartbeat could be inserted by api, it should get from database @@ -427,7 +427,7 @@ class Monitor extends BeanModel { } } - log_debug("monitor", `[${this.name}] Check isImportant`); + log.debug("monitor", `[${this.name}] Check isImportant`); let isImportant = Monitor.isImportantBeat(isFirstBeat, previousBeat?.status, bean.status); // Mark as important if status changed, ignore pending pings, @@ -435,11 +435,11 @@ class Monitor extends BeanModel { if (isImportant) { bean.important = true; - log_debug("monitor", `[${this.name}] sendNotification`); + log.debug("monitor", `[${this.name}] sendNotification`); await Monitor.sendNotification(isFirstBeat, this, bean); // Clear Status Page Cache - log_debug("monitor", `[${this.name}] apicache clear`); + log.debug("monitor", `[${this.name}] apicache clear`); apicache.clear(); } else { @@ -447,33 +447,33 @@ class Monitor extends BeanModel { } if (bean.status === UP) { - log_info("monitor", `Monitor #${this.id} '${this.name}': Successful Response: ${bean.ping} ms | Interval: ${beatInterval} seconds | Type: ${this.type}`); + log.info("monitor", `Monitor #${this.id} '${this.name}': Successful Response: ${bean.ping} ms | Interval: ${beatInterval} seconds | Type: ${this.type}`); } else if (bean.status === PENDING) { if (this.retryInterval > 0) { beatInterval = this.retryInterval; } - log_warn("monitor", `Monitor #${this.id} '${this.name}': Pending: ${bean.msg} | Max retries: ${this.maxretries} | Retry: ${retries} | Retry Interval: ${beatInterval} seconds | Type: ${this.type}`); + log.warn("monitor", `Monitor #${this.id} '${this.name}': Pending: ${bean.msg} | Max retries: ${this.maxretries} | Retry: ${retries} | Retry Interval: ${beatInterval} seconds | Type: ${this.type}`); } else { - log_warn("monitor", `Monitor #${this.id} '${this.name}': Failing: ${bean.msg} | Interval: ${beatInterval} seconds | Type: ${this.type}`); + log.warn("monitor", `Monitor #${this.id} '${this.name}': Failing: ${bean.msg} | Interval: ${beatInterval} seconds | Type: ${this.type}`); } - log_debug("monitor", `[${this.name}] Send to socket`); + log.debug("monitor", `[${this.name}] Send to socket`); io.to(this.user_id).emit("heartbeat", bean.toJSON()); Monitor.sendStats(io, this.id, this.user_id); - log_debug("monitor", `[${this.name}] Store`); + log.debug("monitor", `[${this.name}] Store`); await R.store(bean); - log_debug("monitor", `[${this.name}] prometheus.update`); + log.debug("monitor", `[${this.name}] prometheus.update`); prometheus.update(bean, tlsInfo); previousBeat = bean; if (! this.isStop) { - log_debug("monitor", `[${this.name}] SetTimeout for next check.`); + log.debug("monitor", `[${this.name}] SetTimeout for next check.`); this.heartbeatInterval = setTimeout(safeBeat, beatInterval * 1000); } else { - log_info("monitor", `[${this.name}] isStop = true, no next check.`); + log.info("monitor", `[${this.name}] isStop = true, no next check.`); } }; @@ -484,10 +484,10 @@ class Monitor extends BeanModel { } catch (e) { console.trace(e); errorLog(e, false); - log_error("monitor", "Please report to https://github.com/louislam/uptime-kuma/issues"); + log.error("monitor", "Please report to https://github.com/louislam/uptime-kuma/issues"); if (! this.isStop) { - log_info("monitor", "Try to restart the monitor"); + log.info("monitor", "Try to restart the monitor"); this.heartbeatInterval = setTimeout(safeBeat, this.interval * 1000); } } @@ -551,17 +551,17 @@ class Monitor extends BeanModel { if (isValidObjects) { if (oldCertInfo.certInfo.fingerprint256 !== checkCertificateResult.certInfo.fingerprint256) { - log_debug("monitor", "Resetting sent_history"); + log.debug("monitor", "Resetting sent_history"); await R.exec("DELETE FROM notification_sent_history WHERE type = 'certificate' AND monitor_id = ?", [ this.id ]); } else { - log_debug("monitor", "No need to reset sent_history"); - log_debug("monitor", oldCertInfo.certInfo.fingerprint256); - log_debug("monitor", checkCertificateResult.certInfo.fingerprint256); + log.debug("monitor", "No need to reset sent_history"); + log.debug("monitor", oldCertInfo.certInfo.fingerprint256); + log.debug("monitor", checkCertificateResult.certInfo.fingerprint256); } } else { - log_debug("monitor", "Not valid object"); + log.debug("monitor", "Not valid object"); } } catch (e) { } @@ -582,7 +582,7 @@ class Monitor extends BeanModel { await Monitor.sendUptime(24 * 30, io, monitorID, userID); await Monitor.sendCertInfo(io, monitorID, userID); } else { - log_debug("monitor", "No clients in the room, no need to send stats"); + log.debug("monitor", "No clients in the room, no need to send stats"); } } @@ -729,8 +729,8 @@ class Monitor extends BeanModel { try { await Notification.send(JSON.parse(notification.config), msg, await monitor.toJSON(), bean.toJSON()); } catch (e) { - log_error("monitor", "Cannot send notification to " + notification.name); - log_error("monitor", e); + log.error("monitor", "Cannot send notification to " + notification.name); + log.error("monitor", e); } } } @@ -747,7 +747,7 @@ class Monitor extends BeanModel { if (tlsInfoObject && tlsInfoObject.certInfo && tlsInfoObject.certInfo.daysRemaining) { const notificationList = await Monitor.getNotificationList(this); - log_debug("monitor", "call sendCertNotificationByTargetDays"); + log.debug("monitor", "call sendCertNotificationByTargetDays"); await this.sendCertNotificationByTargetDays(tlsInfoObject.certInfo.daysRemaining, 21, notificationList); await this.sendCertNotificationByTargetDays(tlsInfoObject.certInfo.daysRemaining, 14, notificationList); await this.sendCertNotificationByTargetDays(tlsInfoObject.certInfo.daysRemaining, 7, notificationList); @@ -757,7 +757,7 @@ class Monitor extends BeanModel { async sendCertNotificationByTargetDays(daysRemaining, targetDays, notificationList) { if (daysRemaining > targetDays) { - log_debug("monitor", `No need to send cert notification. ${daysRemaining} > ${targetDays}`); + log.debug("monitor", `No need to send cert notification. ${daysRemaining} > ${targetDays}`); return; } @@ -771,21 +771,21 @@ class Monitor extends BeanModel { // Sent already, no need to send again if (row) { - log_debug("monitor", "Sent already, no need to send again"); + log.debug("monitor", "Sent already, no need to send again"); return; } let sent = false; - log_debug("monitor", "Send certificate notification"); + log.debug("monitor", "Send certificate notification"); for (let notification of notificationList) { try { - log_debug("monitor", "Sending to " + notification.name); + log.debug("monitor", "Sending to " + notification.name); await Notification.send(JSON.parse(notification.config), `[${this.name}][${this.url}] Certificate will be expired in ${daysRemaining} days`); sent = true; } catch (e) { - log_error("monitor", "Cannot send cert notification to " + notification.name); - log_error("monitor", e); + log.error("monitor", "Cannot send cert notification to " + notification.name); + log.error("monitor", e); } } @@ -797,7 +797,7 @@ class Monitor extends BeanModel { ]); } } else { - log_debug("monitor", "No notification, no need to send cert notification"); + log.debug("monitor", "No notification, no need to send cert notification"); } } diff --git a/server/notification-providers/matrix.js b/server/notification-providers/matrix.js index c074e867..915c772d 100644 --- a/server/notification-providers/matrix.js +++ b/server/notification-providers/matrix.js @@ -1,7 +1,7 @@ const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const Crypto = require("crypto"); -const { log_debug } = require("../../src/util"); +const { log } = require("../../src/util"); class Matrix extends NotificationProvider { name = "matrix"; @@ -17,11 +17,11 @@ class Matrix extends NotificationProvider { .slice(0, size) ); - log_debug("notification", "Random String: " + randomString); + log.debug("notification", "Random String: " + randomString); const roomId = encodeURIComponent(notification.internalRoomId); - log_debug("notification", "Matrix Room ID: " + roomId); + log.debug("notification", "Matrix Room ID: " + roomId); try { let config = { diff --git a/server/notification.js b/server/notification.js index a167669f..02faffaf 100644 --- a/server/notification.js +++ b/server/notification.js @@ -24,7 +24,7 @@ const Feishu = require("./notification-providers/feishu"); const AliyunSms = require("./notification-providers/aliyun-sms"); const DingDing = require("./notification-providers/dingding"); const Bark = require("./notification-providers/bark"); -const { log_info } = require("../src/util"); +const { log } = require("../src/util"); const SerwerSMS = require("./notification-providers/serwersms"); const Stackfield = require("./notification-providers/stackfield"); const WeCom = require("./notification-providers/wecom"); @@ -37,7 +37,7 @@ class Notification { providerList = {}; static init() { - log_info("notification", "Prepare Notification Providers"); + log.info("notification", "Prepare Notification Providers"); this.providerList = {}; diff --git a/server/prometheus.js b/server/prometheus.js index a7b5a93c..b9e1415e 100644 --- a/server/prometheus.js +++ b/server/prometheus.js @@ -1,5 +1,5 @@ const PrometheusClient = require("prom-client"); -const { log_error } = require("../src/util"); +const { log } = require("../src/util"); const commonLabels = [ "monitor_name", @@ -57,8 +57,8 @@ class Prometheus { } monitor_cert_is_valid.set(this.monitorLabelValues, is_valid); } catch (e) { - log_error("prometheus", "Caught error"); - log_error("prometheus", e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } try { @@ -66,16 +66,16 @@ class Prometheus { monitor_cert_days_remaining.set(this.monitorLabelValues, tlsInfo.certInfo.daysRemaining); } } catch (e) { - log_error("prometheus", "Caught error"); - log_error("prometheus", e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } } try { monitor_status.set(this.monitorLabelValues, heartbeat.status); } catch (e) { - log_error("prometheus", "Caught error"); - log_error("prometheus", e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } try { @@ -86,8 +86,8 @@ class Prometheus { monitor_response_time.set(this.monitorLabelValues, -1); } } catch (e) { - log_error("prometheus", "Caught error"); - log_error("prometheus", e); + log.error("prometheus", "Caught error"); + log.error("prometheus", e); } } diff --git a/server/rate-limiter.js b/server/rate-limiter.js index c6aa6ad5..f58f16cb 100644 --- a/server/rate-limiter.js +++ b/server/rate-limiter.js @@ -1,5 +1,5 @@ const { RateLimiter } = require("limiter"); -const { log_info } = require("../src/util"); +const { log } = require("../src/util"); class KumaRateLimiter { constructor(config) { @@ -9,7 +9,7 @@ class KumaRateLimiter { async pass(callback, num = 1) { const remainingRequests = await this.removeTokens(num); - log_info("rate-limit", "remaining requests: " + remainingRequests); + log.info("rate-limit", "remaining requests: " + remainingRequests); if (remainingRequests < 0) { if (callback) { callback({ diff --git a/server/routers/api-router.js b/server/routers/api-router.js index b7645a83..ad1a671b 100644 --- a/server/routers/api-router.js +++ b/server/routers/api-router.js @@ -5,7 +5,7 @@ const server = require("../server"); const apicache = require("../modules/apicache"); const Monitor = require("../model/monitor"); const dayjs = require("dayjs"); -const { UP, flipStatus, log_debug } = require("../../src/util"); +const { UP, flipStatus, log } = require("../../src/util"); const StatusPage = require("../model/status_page"); let router = express.Router(); @@ -62,8 +62,8 @@ router.get("/api/push/:pushToken", async (request, response) => { duration = dayjs(bean.time).diff(dayjs(previousHeartbeat.time), "second"); } - log_debug("router", "PreviousStatus: " + previousStatus); - log_debug("router", "Current Status: " + status); + log.debug("router", "PreviousStatus: " + previousStatus); + log.debug("router", "Current Status: " + status); bean.important = Monitor.isImportantBeat(isFirstBeat, previousStatus, status); bean.monitor_id = monitor.id; diff --git a/server/server.js b/server/server.js index faad4a58..60e9e4ff 100644 --- a/server/server.js +++ b/server/server.js @@ -11,42 +11,42 @@ if (nodeVersion < requiredVersion) { } const args = require("args-parser")(process.argv); -const { sleep, log_info, log_debug, log_error, log_warn, getRandomInt, genSecret, debug } = require("../src/util"); +const { sleep, log, getRandomInt, genSecret, debug } = require("../src/util"); const config = require("./config"); -log_info("server", "Welcome to Uptime Kuma"); -log_debug("server", "Arguments"); -log_debug("server", args); +log.info("server", "Welcome to Uptime Kuma"); +log.debug("server", "Arguments"); +log.debug("server", args); if (! process.env.NODE_ENV) { process.env.NODE_ENV = "production"; } -log_info("server", "Node Env: " + process.env.NODE_ENV); +log.info("server", "Node Env: " + process.env.NODE_ENV); -log_info("server", "Importing Node libraries"); +log.info("server", "Importing Node libraries"); const fs = require("fs"); const http = require("http"); const https = require("https"); -log_info("server", "Importing 3rd-party libraries"); -log_debug("server", "Importing express"); +log.info("server", "Importing 3rd-party libraries"); +log.debug("server", "Importing express"); const express = require("express"); -log_debug("server", "Importing socket.io"); +log.debug("server", "Importing socket.io"); const { Server } = require("socket.io"); -log_debug("server", "Importing redbean-node"); +log.debug("server", "Importing redbean-node"); const { R } = require("redbean-node"); -log_debug("server", "Importing jsonwebtoken"); +log.debug("server", "Importing jsonwebtoken"); const jwt = require("jsonwebtoken"); -log_debug("server", "Importing http-graceful-shutdown"); +log.debug("server", "Importing http-graceful-shutdown"); const gracefulShutdown = require("http-graceful-shutdown"); -log_debug("server", "Importing prometheus-api-metrics"); +log.debug("server", "Importing prometheus-api-metrics"); const prometheusAPIMetrics = require("prometheus-api-metrics"); -log_debug("server", "Importing compare-versions"); +log.debug("server", "Importing compare-versions"); const compareVersions = require("compare-versions"); const { passwordStrength } = require("check-password-strength"); -log_debug("server", "Importing 2FA Modules"); +log.debug("server", "Importing 2FA Modules"); const notp = require("notp"); const base32 = require("thirty-two"); @@ -71,23 +71,23 @@ class UptimeKumaServer { const server = module.exports = new UptimeKumaServer(); -log_info("server", "Importing this project modules"); -log_debug("server", "Importing Monitor"); +log.info("server", "Importing this project modules"); +log.debug("server", "Importing Monitor"); const Monitor = require("./model/monitor"); -log_debug("server", "Importing Settings"); +log.debug("server", "Importing Settings"); const { getSettings, setSettings, setting, initJWTSecret, checkLogin, startUnitTest, FBSD, errorLog, doubleCheckPassword } = require("./util-server"); -log_debug("server", "Importing Notification"); +log.debug("server", "Importing Notification"); const { Notification } = require("./notification"); Notification.init(); -log_debug("server", "Importing Proxy"); +log.debug("server", "Importing Proxy"); const { Proxy } = require("./proxy"); -log_debug("server", "Importing Database"); +log.debug("server", "Importing Database"); const Database = require("./database"); -log_debug("server", "Importing Background Jobs"); +log.debug("server", "Importing Background Jobs"); const { initBackgroundJobs, stopBackgroundJobs } = require("./jobs"); const { loginRateLimiter, twoFaRateLimiter } = require("./rate-limiter"); @@ -96,7 +96,7 @@ const { login } = require("./auth"); const passwordHash = require("./password-hash"); const checkVersion = require("./check-version"); -log_info("server", "Version: " + checkVersion.version); +log.info("server", "Version: " + checkVersion.version); // If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available and the unspecified IPv4 address (0.0.0.0) otherwise. // Dual-stack support for (::) @@ -108,7 +108,7 @@ if (!hostname && !FBSD) { } if (hostname) { - log_info("server", "Custom hostname: " + hostname); + log.info("server", "Custom hostname: " + hostname); } const port = parseInt(process.env.UPTIME_KUMA_PORT || process.env.PORT || args.port || 3001); @@ -132,22 +132,22 @@ const twofa_verification_opts = { const testMode = !!args["test"] || false; if (config.demoMode) { - log_info("server", "==== Demo Mode ===="); + log.info("server", "==== Demo Mode ===="); } -log_info("server", "Creating express and socket.io instance"); +log.info("server", "Creating express and socket.io instance"); const app = express(); let httpServer; if (sslKey && sslCert) { - log_info("server", "Server Type: HTTPS"); + log.info("server", "Server Type: HTTPS"); httpServer = https.createServer({ key: fs.readFileSync(sslKey), cert: fs.readFileSync(sslCert) }, app); } else { - log_info("server", "Server Type: HTTP"); + log.info("server", "Server Type: HTTP"); httpServer = http.createServer(app); } @@ -203,7 +203,7 @@ try { } catch (e) { // "dist/index.html" is not necessary for development if (process.env.NODE_ENV !== "development") { - log_error("server", "Error: Cannot find 'dist/index.html', did you install correctly?"); + log.error("server", "Error: Cannot find 'dist/index.html', did you install correctly?"); process.exit(1); } } @@ -215,7 +215,7 @@ try { exports.entryPage = await setting("entryPage"); await StatusPage.loadDomainMappingList(); - log_info("server", "Adding route"); + log.info("server", "Adding route"); // *************************** // Normal Router here @@ -273,7 +273,7 @@ try { } }); - log_info("server", "Adding socket handler"); + log.info("server", "Adding socket handler"); io.on("connection", async (socket) => { sendInfo(socket); @@ -281,7 +281,7 @@ try { totalClient++; if (needSetup) { - log_info("server", "Redirect to setup page"); + log.info("server", "Redirect to setup page"); socket.emit("setup"); } @@ -294,30 +294,30 @@ try { // *************************** socket.on("loginByToken", async (token, callback) => { - log_info("auth", `Login by token. IP=${getClientIp(socket)}`); + log.info("auth", `Login by token. IP=${getClientIp(socket)}`); try { let decoded = jwt.verify(token, jwtSecret); - log_info("auth", "Username from JWT: " + decoded.username); + log.info("auth", "Username from JWT: " + decoded.username); let user = await R.findOne("user", " username = ? AND active = 1 ", [ decoded.username, ]); if (user) { - log_debug("auth", "afterLogin"); + log.debug("auth", "afterLogin"); afterLogin(socket, user); - log_debug("auth", "afterLogin ok"); + log.debug("auth", "afterLogin ok"); - log_info("auth", `Successfully logged in user ${decoded.username}. IP=${getClientIp(socket)}`); + log.info("auth", `Successfully logged in user ${decoded.username}. IP=${getClientIp(socket)}`); callback({ ok: true, }); } else { - log_info("auth", `Inactive or deleted user ${decoded.username}. IP=${getClientIp(socket)}`); + log.info("auth", `Inactive or deleted user ${decoded.username}. IP=${getClientIp(socket)}`); callback({ ok: false, @@ -326,7 +326,7 @@ try { } } catch (error) { - log_error("auth", `Invalid token. IP=${getClientIp(socket)}`); + log.error("auth", `Invalid token. IP=${getClientIp(socket)}`); callback({ ok: false, @@ -337,7 +337,7 @@ try { }); socket.on("login", async (data, callback) => { - log_info("auth", `Login by username + password. IP=${getClientIp(socket)}`); + log.info("auth", `Login by username + password. IP=${getClientIp(socket)}`); // Checking if (typeof callback !== "function") { @@ -350,7 +350,7 @@ try { // Login Rate Limit if (! await loginRateLimiter.pass(callback)) { - log_info("auth", `Too many failed requests for user ${data.username}. IP=${getClientIp(socket)}`); + log.info("auth", `Too many failed requests for user ${data.username}. IP=${getClientIp(socket)}`); return; } @@ -360,7 +360,7 @@ try { if (user.twofa_status == 0) { afterLogin(socket, user); - log_info("auth", `Successfully logged in user ${data.username}. IP=${getClientIp(socket)}`); + log.info("auth", `Successfully logged in user ${data.username}. IP=${getClientIp(socket)}`); callback({ ok: true, @@ -372,7 +372,7 @@ try { if (user.twofa_status == 1 && !data.token) { - log_info("auth", `2FA token required for user ${data.username}. IP=${getClientIp(socket)}`); + log.info("auth", `2FA token required for user ${data.username}. IP=${getClientIp(socket)}`); callback({ tokenRequired: true, @@ -390,7 +390,7 @@ try { socket.userID, ]); - log_info("auth", `Successfully logged in user ${data.username}. IP=${getClientIp(socket)}`); + log.info("auth", `Successfully logged in user ${data.username}. IP=${getClientIp(socket)}`); callback({ ok: true, @@ -400,7 +400,7 @@ try { }); } else { - log_warn("auth", `Invalid token provided for user ${data.username}. IP=${getClientIp(socket)}`); + log.warn("auth", `Invalid token provided for user ${data.username}. IP=${getClientIp(socket)}`); callback({ ok: false, @@ -410,7 +410,7 @@ try { } } else { - log_warn("auth", `Incorrect username or password for user ${data.username}. IP=${getClientIp(socket)}`); + log.warn("auth", `Incorrect username or password for user ${data.username}. IP=${getClientIp(socket)}`); callback({ ok: false, @@ -494,7 +494,7 @@ try { socket.userID, ]); - log_info("auth", `Saved 2FA token. IP=${getClientIp(socket)}`); + log.info("auth", `Saved 2FA token. IP=${getClientIp(socket)}`); callback({ ok: true, @@ -502,7 +502,7 @@ try { }); } catch (error) { - log_error("auth", `Error changing 2FA token. IP=${getClientIp(socket)}`); + log.error("auth", `Error changing 2FA token. IP=${getClientIp(socket)}`); callback({ ok: false, @@ -521,7 +521,7 @@ try { await doubleCheckPassword(socket, currentPassword); await TwoFA.disable2FA(socket.userID); - log_info("auth", `Disabled 2FA token. IP=${getClientIp(socket)}`); + log.info("auth", `Disabled 2FA token. IP=${getClientIp(socket)}`); callback({ ok: true, @@ -529,7 +529,7 @@ try { }); } catch (error) { - log_error("auth", `Error disabling 2FA token. IP=${getClientIp(socket)}`); + log.error("auth", `Error disabling 2FA token. IP=${getClientIp(socket)}`); callback({ ok: false, @@ -657,7 +657,7 @@ try { await server.sendMonitorList(socket); await startMonitor(socket.userID, bean.id); - log_info("monitor", `Added Monitor: ${monitor.id} User ID: ${socket.userID}`); + log.info("monitor", `Added Monitor: ${monitor.id} User ID: ${socket.userID}`); callback({ ok: true, @@ -667,7 +667,7 @@ try { } catch (e) { - log_error("monitor", `Error adding Monitor: ${monitor.id} User ID: ${socket.userID}`); + log.error("monitor", `Error adding Monitor: ${monitor.id} User ID: ${socket.userID}`); callback({ ok: false, @@ -731,7 +731,7 @@ try { }); } catch (e) { - log_error("monitor", e); + log.error("monitor", e); callback({ ok: false, msg: e.message, @@ -747,7 +747,7 @@ try { ok: true, }); } catch (e) { - log_error("monitor", e); + log.error("monitor", e); callback({ ok: false, msg: e.message, @@ -759,7 +759,7 @@ try { try { checkLogin(socket); - log_info("monitor", `Get Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("monitor", `Get Monitor: ${monitorID} User ID: ${socket.userID}`); let bean = await R.findOne("monitor", " id = ? AND user_id = ? ", [ monitorID, @@ -783,7 +783,7 @@ try { try { checkLogin(socket); - log_info("monitor", `Get Monitor Beats: ${monitorID} User ID: ${socket.userID}`); + log.info("monitor", `Get Monitor Beats: ${monitorID} User ID: ${socket.userID}`); if (period == null) { throw new Error("Invalid period."); @@ -854,7 +854,7 @@ try { try { checkLogin(socket); - log_info("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`); if (monitorID in server.monitorList) { server.monitorList[monitorID].stop(); @@ -1186,7 +1186,7 @@ try { let backupData = JSON.parse(uploadedJSON); - log_info("manage", `Importing Backup, User ID: ${socket.userID}, Version: ${backupData.version}`); + log.info("manage", `Importing Backup, User ID: ${socket.userID}, Version: ${backupData.version}`); let notificationListData = backupData.notificationList; let proxyListData = backupData.proxyList; @@ -1381,7 +1381,7 @@ try { try { checkLogin(socket); - log_info("manage", `Clear Events Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("manage", `Clear Events Monitor: ${monitorID} User ID: ${socket.userID}`); await R.exec("UPDATE heartbeat SET msg = ?, important = ? WHERE monitor_id = ? ", [ "", @@ -1407,7 +1407,7 @@ try { try { checkLogin(socket); - log_info("manage", `Clear Heartbeats Monitor: ${monitorID} User ID: ${socket.userID}`); + log.info("manage", `Clear Heartbeats Monitor: ${monitorID} User ID: ${socket.userID}`); await R.exec("DELETE FROM heartbeat WHERE monitor_id = ?", [ monitorID @@ -1431,7 +1431,7 @@ try { try { checkLogin(socket); - log_info("manage", `Clear Statistics User ID: ${socket.userID}`); + log.info("manage", `Clear Statistics User ID: ${socket.userID}`); await R.exec("DELETE FROM heartbeat"); @@ -1453,24 +1453,24 @@ try { databaseSocketHandler(socket); proxySocketHandler(socket); - log_debug("server", "added all socket handlers"); + log.debug("server", "added all socket handlers"); // *************************** // Better do anything after added all socket handlers here // *************************** - log_debug("auth", "check auto login"); + log.debug("auth", "check auto login"); if (await setting("disableAuth")) { - log_info("auth", "Disabled Auth: auto login to admin"); + log.info("auth", "Disabled Auth: auto login to admin"); afterLogin(socket, await R.findOne("user")); socket.emit("autoLogin"); } else { - log_debug("auth", "need auth"); + log.debug("auth", "need auth"); } }); - log_info("server", "Init the server"); + log.info("server", "Init the server"); httpServer.once("error", async (err) => { console.error("Cannot listen: " + err.message); @@ -1479,9 +1479,9 @@ try { httpServer.listen(port, hostname, () => { if (hostname) { - log_info("server", `Listening on ${hostname}:${port}`); + log.info("server", `Listening on ${hostname}:${port}`); } else { - log_info("server", `Listening on ${port}`); + log.info("server", `Listening on ${port}`); } startMonitors(); checkVersion.startInterval(); @@ -1565,13 +1565,13 @@ async function getMonitorJSONList(userID) { async function initDatabase(testMode = false) { if (! fs.existsSync(Database.path)) { - log_info("server", "Copying Database"); + log.info("server", "Copying Database"); fs.copyFileSync(Database.templatePath, Database.path); } - log_info("server", "Connecting to the Database"); + log.info("server", "Connecting to the Database"); await Database.connect(testMode); - log_info("server", "Connected"); + log.info("server", "Connected"); // Patch the database await Database.patch(); @@ -1581,16 +1581,16 @@ async function initDatabase(testMode = false) { ]); if (! jwtSecretBean) { - log_info("server", "JWT secret is not found, generate one."); + log.info("server", "JWT secret is not found, generate one."); jwtSecretBean = await initJWTSecret(); - log_info("server", "Stored JWT secret into database"); + log.info("server", "Stored JWT secret into database"); } else { - log_info("server", "Load JWT secret from database."); + log.info("server", "Load JWT secret from database."); } // If there is no record in user table, it is a new Uptime Kuma instance, need to setup if ((await R.count("user")) === 0) { - log_info("server", "No user, need setup"); + log.info("server", "No user, need setup"); needSetup = true; } @@ -1600,7 +1600,7 @@ async function initDatabase(testMode = false) { async function startMonitor(userID, monitorID) { await checkOwner(userID, monitorID); - log_info("manage", `Resume Monitor: ${monitorID} User ID: ${userID}`); + log.info("manage", `Resume Monitor: ${monitorID} User ID: ${userID}`); await R.exec("UPDATE monitor SET active = 1 WHERE id = ? AND user_id = ? ", [ monitorID, @@ -1626,7 +1626,7 @@ async function restartMonitor(userID, monitorID) { async function pauseMonitor(userID, monitorID) { await checkOwner(userID, monitorID); - log_info("manage", `Pause Monitor: ${monitorID} User ID: ${userID}`); + log.info("manage", `Pause Monitor: ${monitorID} User ID: ${userID}`); await R.exec("UPDATE monitor SET active = 0 WHERE id = ? AND user_id = ? ", [ monitorID, @@ -1656,10 +1656,10 @@ async function startMonitors() { } async function shutdownFunction(signal) { - log_info("server", "Shutdown requested"); - log_info("server", "Called signal: " + signal); + log.info("server", "Shutdown requested"); + log.info("server", "Called signal: " + signal); - log_info("server", "Stopping all monitors"); + log.info("server", "Stopping all monitors"); for (let id in server.monitorList) { let monitor = server.monitorList[id]; monitor.stop(); @@ -1676,7 +1676,7 @@ function getClientIp(socket) { } function finalFunction() { - log_info("server", "Graceful shutdown successful!"); + log.info("server", "Graceful shutdown successful!"); } gracefulShutdown(httpServer, { diff --git a/server/socket-handlers/status-page-socket-handler.js b/server/socket-handlers/status-page-socket-handler.js index 25fa959e..11ecaab0 100644 --- a/server/socket-handlers/status-page-socket-handler.js +++ b/server/socket-handlers/status-page-socket-handler.js @@ -1,7 +1,7 @@ const { R } = require("redbean-node"); const { checkLogin, setSettings, setSetting } = require("../util-server"); const dayjs = require("dayjs"); -const { log, log_info, log_debug, log_error } = require("../../src/util"); +const { log } = require("../../src/util"); const ImageDataURI = require("../image-data-uri"); const Database = require("../database"); const apicache = require("../modules/apicache"); @@ -203,7 +203,7 @@ module.exports.statusPageSocketHandler = (socket) => { } // Delete groups that are not in the list - log_debug("socket", "Delete groups that are not in the list"); + log.debug("socket", "Delete groups that are not in the list"); const slots = groupIDList.map(() => "?").join(","); const data = [ @@ -226,7 +226,7 @@ module.exports.statusPageSocketHandler = (socket) => { }); } catch (error) { - log_error("socket", error); + log.error("socket", error); callback({ ok: false, diff --git a/server/util-server.js b/server/util-server.js index 203073fe..6904eb63 100644 --- a/server/util-server.js +++ b/server/util-server.js @@ -1,7 +1,7 @@ const tcpp = require("tcp-ping"); const Ping = require("./ping-lite"); const { R } = require("redbean-node"); -const { log_debug, genSecret } = require("../src/util"); +const { log, genSecret } = require("../src/util"); const passwordHash = require("./password-hash"); const { Resolver } = require("dns"); const child_process = require("child_process"); @@ -119,7 +119,7 @@ exports.setting = async function (key) { try { const v = JSON.parse(value); - log_debug("util", `Get Setting: ${key}: ${v}`); + log.debug("util", `Get Setting: ${key}: ${v}`); return v; } catch (e) { return value; @@ -206,7 +206,7 @@ const parseCertificateInfo = function (info) { const existingList = {}; while (link) { - log_debug("util", `[${i}] ${link.fingerprint}`); + log.debug("util", `[${i}] ${link.fingerprint}`); if (!link.valid_from || !link.valid_to) { break; @@ -221,7 +221,7 @@ const parseCertificateInfo = function (info) { if (link.issuerCertificate == null) { break; } else if (link.issuerCertificate.fingerprint in existingList) { - log_debug("util", `[Last] ${link.issuerCertificate.fingerprint}`); + log.debug("util", `[Last] ${link.issuerCertificate.fingerprint}`); link.issuerCertificate = null; break; } else { @@ -242,7 +242,7 @@ exports.checkCertificate = function (res) { const info = res.request.res.socket.getPeerCertificate(true); const valid = res.request.res.socket.authorized || false; - log_debug("util", "Parsing Certificate Info"); + log.debug("util", "Parsing Certificate Info"); const parsedInfo = parseCertificateInfo(info); return { @@ -367,7 +367,6 @@ exports.startUnitTest = async () => { */ exports.convertToUTF8 = (body) => { const guessEncoding = chardet.detect(body); - //log_debug("util", "Guess Encoding: " + guessEncoding); const str = iconv.decode(body, guessEncoding); return str.toString(); }; diff --git a/src/components/settings/MonitorHistory.vue b/src/components/settings/MonitorHistory.vue index 2f178f05..8fff6054 100644 --- a/src/components/settings/MonitorHistory.vue +++ b/src/components/settings/MonitorHistory.vue @@ -52,7 +52,7 @@