separate log functions

pull/910/head
Andreas Brett 3 years ago
parent d21f7971b5
commit e5913c5abc

@ -1,7 +1,7 @@
const fs = require("fs");
const { R } = require("redbean-node");
const { setSetting, setting } = require("./util-server");
const { log, sleep } = require("../src/util");
const { log_info, log_debug, log_error, sleep } = require("../src/util");
const dayjs = require("dayjs");
const knex = require("knex");
@ -76,7 +76,7 @@ class Database {
fs.mkdirSync(Database.uploadDir, { recursive: true });
}
log("db", `Data Dir: ${Database.dataDir}`);
log_info("db", `Data Dir: ${Database.dataDir}`);
}
static async connect() {
@ -117,10 +117,10 @@ class Database {
await R.exec("PRAGMA cache_size = -12000");
await R.exec("PRAGMA auto_vacuum = FULL");
log("db", "SQLite config:");
log("db", await R.getAll("PRAGMA journal_mode"));
log("db", await R.getAll("PRAGMA cache_size"));
log("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()"));
}
static async patch() {
@ -130,15 +130,15 @@ class Database {
version = 0;
}
log("db", "Your database version: " + version);
log("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("db", "Database patch not needed");
log_info("db", "Database patch not needed");
} else if (version > this.latestVersion) {
log("db", "Warning: Database version is newer than expected");
log_info("db", "Warning: Database version is newer than expected");
} else {
log("db", "Database patch is needed");
log_info("db", "Database patch is needed");
this.backup(version);
@ -146,17 +146,17 @@ class Database {
try {
for (let i = version + 1; i <= this.latestVersion; i++) {
const sqlFile = `./db/patch${i}.sql`;
log("db", `Patching ${sqlFile}`);
log_info("db", `Patching ${sqlFile}`);
await Database.importSQLFile(sqlFile);
log("db", `Patched ${sqlFile}`);
log_info("db", `Patched ${sqlFile}`);
await setSetting("database_version", i);
}
} catch (ex) {
await Database.close();
log("db", ex, "error");
log("db", "Start Uptime-Kuma failed due to issue patching the database", "error");
log("db", "Please submit a bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues", "error");
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);
@ -171,15 +171,15 @@ class Database {
* @returns {Promise<void>}
*/
static async patch2() {
log("db", "Database Patch 2.0 Process");
log_info("db", "Database Patch 2.0 Process");
let databasePatchedFiles = await setting("databasePatchedFiles");
if (! databasePatchedFiles) {
databasePatchedFiles = {};
}
log("db", "Patched files:", "debug");
log("db", databasePatchedFiles, "debug");
log_debug("db", "Patched files:");
log_debug("db", databasePatchedFiles);
try {
for (let sqlFilename in this.patchList) {
@ -187,15 +187,15 @@ class Database {
}
if (this.patched) {
log("db", "Database Patched Successfully");
log_info("db", "Database Patched Successfully");
}
} catch (ex) {
await Database.close();
log("db", ex, "error");
log("db", "Start Uptime-Kuma failed due to issue patching the database", "error");
log("db", "Please submit the bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues", "error");
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();
@ -214,16 +214,16 @@ class Database {
let value = this.patchList[sqlFilename];
if (! value) {
log("db", sqlFilename + " skip");
log_info("db", sqlFilename + " skip");
return;
}
// Check if patched
if (! databasePatchedFiles[sqlFilename]) {
log("db", sqlFilename + " is not patched");
log_info("db", sqlFilename + " is not patched");
if (value.parents) {
log("db", sqlFilename + " need parents");
log_info("db", sqlFilename + " need parents");
for (let parentSQLFilename of value.parents) {
await this.patch2Recursion(parentSQLFilename, databasePatchedFiles);
}
@ -231,14 +231,14 @@ class Database {
this.backup(dayjs().format("YYYYMMDDHHmmss"));
log("db", sqlFilename + " is patching");
log_info("db", sqlFilename + " is patching");
this.patched = true;
await this.importSQLFile("./db/" + sqlFilename);
databasePatchedFiles[sqlFilename] = true;
log("db", sqlFilename + " was patched successfully");
log_info("db", sqlFilename + " was patched successfully");
} else {
log("db", sqlFilename + " is already patched, skip", "debug");
log_debug("db", sqlFilename + " is already patched, skip");
}
}
@ -290,7 +290,7 @@ class Database {
};
process.addListener("unhandledRejection", listener);
log("db", "Closing the database");
log_info("db", "Closing the database");
while (true) {
Database.noReject = true;
@ -300,10 +300,10 @@ class Database {
if (Database.noReject) {
break;
} else {
log("db", "Waiting to close the database");
log_info("db", "Waiting to close the database");
}
}
log("db", "SQLite closed");
log_info("db", "SQLite closed");
process.removeListener("unhandledRejection", listener);
}
@ -315,7 +315,7 @@ class Database {
*/
static backup(version) {
if (! this.backupPath) {
log("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);
@ -338,7 +338,7 @@ class Database {
*/
static restore() {
if (this.backupPath) {
log("db", "Patching the database failed!!! Restoring the backup", "error");
log_error("db", "Patching the database failed!!! Restoring the backup");
const shmPath = Database.path + "-shm";
const walPath = Database.path + "-wal";
@ -357,7 +357,7 @@ class Database {
fs.unlinkSync(walPath);
}
} catch (e) {
log("db", "Restore failed; you may need to restore the backup manually", "error");
log_error("db", "Restore failed; you may need to restore the backup manually");
process.exit(1);
}
@ -373,14 +373,14 @@ class Database {
}
} else {
log("db", "Nothing to restore");
log_info("db", "Nothing to restore");
}
}
static getSize() {
log("db", "Database.getSize()", "debug");
log_debug("db", "Database.getSize()");
let stats = fs.statSync(Database.path);
log("db", stats, "debug");
log_debug("db", stats);
return stats.size;
}

@ -3,13 +3,13 @@
Modified with 0 dependencies
*/
let fs = require("fs");
const { log } = require("../src/util");
const { log_error } = require("../src/util");
let ImageDataURI = (() => {
function decode(dataURI) {
if (!/data:image\//.test(dataURI)) {
log("image-data-uri", "It seems that it is not an Image Data URI. Couldn't match \"data:image/\"", "error");
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("image-data-uri", "Missing some of the required params: data, mediaType", "error");
log_error("image-data-uri", "Missing some of the required params: data, mediaType");
return null;
}

@ -1,7 +1,7 @@
const path = require("path");
const Bree = require("bree");
const { SHARE_ENV } = require("worker_threads");
const { log } = require("../src/util");
const { log_info } = require("../src/util");
const jobs = [
{
@ -19,7 +19,7 @@ const initBackgroundJobs = function (args) {
workerData: args,
},
workerMessageHandler: (message) => {
log("jobs", message);
log_info("jobs", message);
}
});

@ -6,7 +6,7 @@ dayjs.extend(utc);
dayjs.extend(timezone);
const axios = require("axios");
const { Prometheus } = require("../prometheus");
const { log, UP, DOWN, PENDING, flipStatus, TimeLogger } = require("../../src/util");
const { log_info, log_debug, log_error, log_warn, 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");
@ -141,7 +141,7 @@ class Monitor extends BeanModel {
// Do not do any queries/high loading things before the "bean.ping"
let startTime = dayjs().valueOf();
log("monitor", `[${this.name}] Prepare Options for axios`, "debug");
log_debug("monitor", `[${this.name}] Prepare Options for axios`);
const options = {
url: this.url,
method: (this.method || "get").toLowerCase(),
@ -162,7 +162,7 @@ class Monitor extends BeanModel {
},
};
log("monitor", `[${this.name}] Axios Request`, "debug");
log_debug("monitor", `[${this.name}] Axios Request`);
let res = await axios.request(options);
bean.msg = `${res.status} - ${res.statusText}`;
bean.ping = dayjs().valueOf() - startTime;
@ -170,30 +170,30 @@ class Monitor extends BeanModel {
// Check certificate if https is used
let certInfoStartTime = dayjs().valueOf();
if (this.getUrl()?.protocol === "https:") {
log("monitor", `[${this.name}] Check cert`, "debug");
log_debug("monitor", `[${this.name}] Check cert`);
try {
let tlsInfoObject = checkCertificate(res);
tlsInfo = await this.updateTlsInfo(tlsInfoObject);
if (!this.getIgnoreTls()) {
log("monitor", `[${this.name}] call sendCertNotification`, "debug");
log_debug("monitor", `[${this.name}] call sendCertNotification`);
await this.sendCertNotification(tlsInfoObject);
}
} catch (e) {
if (e.message !== "No TLS certificate in response") {
log("monitor", "Caught error", "error");
log("monitor", e.message, "error");
log_error("monitor", "Caught error");
log_error("monitor", e.message);
}
}
}
if (process.env.TIMELOGGER === "1") {
log("monitor", "Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms", "debug");
log_debug("monitor", "Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms");
}
if (process.env.UPTIME_KUMA_LOG_RESPONSE_BODY_MONITOR_ID == this.id) {
log("monitor", res.data);
log_info("monitor", res.data);
}
if (this.type === "http") {
@ -273,7 +273,7 @@ class Monitor extends BeanModel {
time
]);
log("monitor", "heartbeatCount" + heartbeatCount + " " + time, "debug");
log_debug("monitor", "heartbeatCount" + heartbeatCount + " " + time);
if (heartbeatCount <= 0) {
throw new Error("No heartbeat in the time window");
@ -356,7 +356,7 @@ class Monitor extends BeanModel {
let beatInterval = this.interval;
log("monitor", `[${this.name}] Check isImportant`, "debug");
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,
@ -364,11 +364,11 @@ class Monitor extends BeanModel {
if (isImportant) {
bean.important = true;
log("monitor", `[${this.name}] sendNotification`, "debug");
log_debug("monitor", `[${this.name}] sendNotification`);
await Monitor.sendNotification(isFirstBeat, this, bean);
// Clear Status Page Cache
log("monitor", `[${this.name}] apicache clear`, "debug");
log_debug("monitor", `[${this.name}] apicache clear`);
apicache.clear();
} else {
@ -376,24 +376,24 @@ class Monitor extends BeanModel {
}
if (bean.status === UP) {
log("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("monitor", `Monitor #${this.id} '${this.name}': Pending: ${bean.msg} | Max retries: ${this.maxretries} | Retry: ${retries} | Retry Interval: ${beatInterval} seconds | Type: ${this.type}`, "warn");
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("monitor", `Monitor #${this.id} '${this.name}': Failing: ${bean.msg} | Interval: ${beatInterval} seconds | Type: ${this.type}`, "warn");
log_warn("monitor", `Monitor #${this.id} '${this.name}': Failing: ${bean.msg} | Interval: ${beatInterval} seconds | Type: ${this.type}`);
}
log("monitor", `[${this.name}] Send to socket`, "debug");
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("monitor", `[${this.name}] Store`, "debug");
log_debug("monitor", `[${this.name}] Store`);
await R.store(bean);
log("monitor", `[${this.name}] prometheus.update`, "debug");
log_debug("monitor", `[${this.name}] prometheus.update`);
prometheus.update(bean, tlsInfo);
previousBeat = bean;
@ -402,15 +402,15 @@ class Monitor extends BeanModel {
if (demoMode) {
if (beatInterval < 20) {
log("monitor", "beat interval too low, reset to 20s");
log_info("monitor", "beat interval too low, reset to 20s");
beatInterval = 20;
}
}
log("monitor", `[${this.name}] SetTimeout for next check.`, "debug");
log_debug("monitor", `[${this.name}] SetTimeout for next check.`);
this.heartbeatInterval = setTimeout(safeBeat, beatInterval * 1000);
} else {
log("monitor", `[${this.name}] isStop = true, no next check.`);
log_info("monitor", `[${this.name}] isStop = true, no next check.`);
}
};
@ -421,10 +421,10 @@ class Monitor extends BeanModel {
} catch (e) {
console.trace(e);
errorLog(e, false);
log("monitor", "Please report to https://github.com/louislam/uptime-kuma/issues", "error");
log_error("monitor", "Please report to https://github.com/louislam/uptime-kuma/issues");
if (! this.isStop) {
log("monitor", "Try to restart the monitor");
log_info("monitor", "Try to restart the monitor");
this.heartbeatInterval = setTimeout(safeBeat, this.interval * 1000);
}
}
@ -482,17 +482,17 @@ class Monitor extends BeanModel {
if (isValidObjects) {
if (oldCertInfo.certInfo.fingerprint256 !== checkCertificateResult.certInfo.fingerprint256) {
log("monitor", "Resetting sent_history", "debug");
log_debug("monitor", "Resetting sent_history");
await R.exec("DELETE FROM notification_sent_history WHERE type = 'certificate' AND monitor_id = ?", [
this.id
]);
} else {
log("monitor", "No need to reset sent_history", "debug");
log("monitor", oldCertInfo.certInfo.fingerprint256, "debug");
log("monitor", checkCertificateResult.certInfo.fingerprint256, "debug");
log_debug("monitor", "No need to reset sent_history");
log_debug("monitor", oldCertInfo.certInfo.fingerprint256);
log_debug("monitor", checkCertificateResult.certInfo.fingerprint256);
}
} else {
log("monitor", "Not valid object", "debug");
log_debug("monitor", "Not valid object");
}
} catch (e) { }
@ -513,7 +513,7 @@ class Monitor extends BeanModel {
await Monitor.sendUptime(24 * 30, io, monitorID, userID);
await Monitor.sendCertInfo(io, monitorID, userID);
} else {
log("monitor", "No clients in the room, no need to send stats", "debug");
log_debug("monitor", "No clients in the room, no need to send stats");
}
}
@ -660,8 +660,8 @@ class Monitor extends BeanModel {
try {
await Notification.send(JSON.parse(notification.config), msg, await monitor.toJSON(), bean.toJSON());
} catch (e) {
log("monitor", "Cannot send notification to " + notification.name, "error");
log("monitor", e, "error");
log_error("monitor", "Cannot send notification to " + notification.name);
log_error("monitor", e);
}
}
}
@ -678,7 +678,7 @@ class Monitor extends BeanModel {
if (tlsInfoObject && tlsInfoObject.certInfo && tlsInfoObject.certInfo.daysRemaining) {
const notificationList = await Monitor.getNotificationList(this);
log("monitor", "call sendCertNotificationByTargetDays", "debug");
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);
@ -688,7 +688,7 @@ class Monitor extends BeanModel {
async sendCertNotificationByTargetDays(daysRemaining, targetDays, notificationList) {
if (daysRemaining > targetDays) {
log("monitor", `No need to send cert notification. ${daysRemaining} > ${targetDays}`, "debug");
log_debug("monitor", `No need to send cert notification. ${daysRemaining} > ${targetDays}`);
return;
}
@ -702,21 +702,21 @@ class Monitor extends BeanModel {
// Sent already, no need to send again
if (row) {
log("monitor", "Sent already, no need to send again", "debug");
log_debug("monitor", "Sent already, no need to send again");
return;
}
let sent = false;
log("monitor", "Send certificate notification", "debug");
log_debug("monitor", "Send certificate notification");
for (let notification of notificationList) {
try {
log("monitor", "Sending to " + notification.name, "debug");
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("monitor", "Cannot send cert notification to " + notification.name, "error");
log("monitor", e, "error");
log_error("monitor", "Cannot send cert notification to " + notification.name);
log_error("monitor", e);
}
}
@ -728,7 +728,7 @@ class Monitor extends BeanModel {
]);
}
} else {
log("monitor", "No notification, no need to send cert notification", "debug");
log_debug("monitor", "No notification, no need to send cert notification");
}
}
}

@ -1,7 +1,7 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
const Crypto = require("crypto");
const { log } = require("../../src/util");
const { log_debug } = require("../../src/util");
class Matrix extends NotificationProvider {
name = "matrix";
@ -17,11 +17,11 @@ class Matrix extends NotificationProvider {
.slice(0, size)
);
log("notification", "Random String: " + randomString, "debug");
log_debug("notification", "Random String: " + randomString);
const roomId = encodeURIComponent(notification.internalRoomId);
log("notification", "Matrix Room ID: " + roomId, "debug");
log_debug("notification", "Matrix Room ID: " + roomId);
try {
let config = {

@ -23,14 +23,14 @@ 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 } = require("../src/util");
const { log_info } = require("../src/util");
class Notification {
providerList = {};
static init() {
log("notification", "Prepare Notification Providers");
log_info("notification", "Prepare Notification Providers");
this.providerList = {};

@ -1,5 +1,5 @@
const PrometheusClient = require("prom-client");
const { log } = require("../src/util");
const { log_error } = require("../src/util");
const commonLabels = [
"monitor_name",
@ -57,23 +57,23 @@ class Prometheus {
}
monitor_cert_is_valid.set(this.monitorLabelValues, is_valid);
} catch (e) {
log("prometheus", "Caught error", "error");
log("prometheus", e, "error");
log_error("prometheus", "Caught error");
log_error("prometheus", e);
}
try {
monitor_cert_days_remaining.set(this.monitorLabelValues, tlsInfo.certInfo.daysRemaining);
} catch (e) {
log("prometheus", "Caught error", "error");
log("prometheus", e, "error");
log_error("prometheus", "Caught error");
log_error("prometheus", e);
}
}
try {
monitor_status.set(this.monitorLabelValues, heartbeat.status);
} catch (e) {
log("prometheus", "Caught error", "error");
log("prometheus", e, "error");
log_error("prometheus", "Caught error");
log_error("prometheus", e);
}
try {
@ -84,8 +84,8 @@ class Prometheus {
monitor_response_time.set(this.monitorLabelValues, -1);
}
} catch (e) {
log("prometheus", "Caught error", "error");
log("prometheus", e, "error");
log_error("prometheus", "Caught error");
log_error("prometheus", e);
}
}

@ -1,5 +1,5 @@
const { RateLimiter } = require("limiter");
const { log } = require("../src/util");
const { log_info } = 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("rate-limit", "remaining requests: " + remainingRequests);
log_info("rate-limit", "remaining requests: " + remainingRequests);
if (remainingRequests < 0) {
if (callback) {
callback({

@ -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 } = require("../../src/util");
const { UP, flipStatus, log_debug } = require("../../src/util");
let router = express.Router();
let cache = apicache.middleware;
@ -56,8 +56,8 @@ router.get("/api/push/:pushToken", async (request, response) => {
duration = dayjs(bean.time).diff(dayjs(previousHeartbeat.time), "second");
}
log("router", "PreviousStatus: " + previousStatus, "debug");
log("router", "Current Status: " + status, "debug");
log_debug("router", "PreviousStatus: " + previousStatus);
log_debug("router", "Current Status: " + status);
bean.important = Monitor.isImportantBeat(isFirstBeat, previousStatus, status);
bean.monitor_id = monitor.id;

@ -1,57 +1,57 @@
const args = require("args-parser")(process.argv);
const { sleep, log, getRandomInt, genSecret } = require("../src/util");
const { sleep, log_info, log_debug, log_error, log_warn, getRandomInt, genSecret } = require("../src/util");
const config = require("./config");
log("server", "Welcome to Uptime Kuma");
log("server", "Arguments", "debug");
log("server", args, "debug");
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("server", "Node Env: " + process.env.NODE_ENV);
log_info("server", "Node Env: " + process.env.NODE_ENV);
log("server", "Importing Node libraries");
log_info("server", "Importing Node libraries");
const fs = require("fs");
const http = require("http");
const https = require("https");
log("server", "Importing 3rd-party libraries");
log("server", "Importing express", "debug");
log_info("server", "Importing 3rd-party libraries");
log_debug("server", "Importing express");
const express = require("express");
log("server", "Importing socket.io", "debug");
log_debug("server", "Importing socket.io");
const { Server } = require("socket.io");
log("server", "Importing redbean-node", "debug");
log_debug("server", "Importing redbean-node");
const { R } = require("redbean-node");
log("server", "Importing jsonwebtoken", "debug");
log_debug("server", "Importing jsonwebtoken");
const jwt = require("jsonwebtoken");
log("server", "Importing http-graceful-shutdown", "debug");
log_debug("server", "Importing http-graceful-shutdown");
const gracefulShutdown = require("http-graceful-shutdown");
log("server", "Importing prometheus-api-metrics", "debug");
log_debug("server", "Importing prometheus-api-metrics");
const prometheusAPIMetrics = require("prometheus-api-metrics");
log("server", "Importing compare-versions", "debug");
log_debug("server", "Importing compare-versions");
const compareVersions = require("compare-versions");
const { passwordStrength } = require("check-password-strength");
log("server", "Importing 2FA Modules", "debug");
log_debug("server", "Importing 2FA Modules");
const notp = require("notp");
const base32 = require("thirty-two");
log("server", "Importing this project modules");
log("server", "Importing Monitor", "debug");
log_info("server", "Importing this project modules");
log_debug("server", "Importing Monitor");
const Monitor = require("./model/monitor");
log("server", "Importing Settings", "debug");
log_debug("server", "Importing Settings");
const { getSettings, setSettings, setting, initJWTSecret, checkLogin, startUnitTest, FBSD, errorLog } = require("./util-server");
log("server", "Importing Notification", "debug");
log_debug("server", "Importing Notification");
const { Notification } = require("./notification");
Notification.init();
log("server", "Importing Database", "debug");
log_debug("server", "Importing Database");
const Database = require("./database");
log("server", "Importing Background Jobs", "debug");
log_debug("server", "Importing Background Jobs");
const { initBackgroundJobs } = require("./jobs");
const { loginRateLimiter } = require("./rate-limiter");
@ -60,7 +60,7 @@ const { login } = require("./auth");
const passwordHash = require("./password-hash");
const checkVersion = require("./check-version");
log("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 (::)
@ -72,7 +72,7 @@ if (!hostname && !FBSD) {
}
if (hostname) {
log("server", "Custom hostname: " + hostname);
log_info("server", "Custom hostname: " + hostname);
}
const port = parseInt(process.env.UPTIME_KUMA_PORT || process.env.PORT || args.port || 3001);
@ -95,22 +95,22 @@ const twofa_verification_opts = {
const testMode = !!args["test"] || false;
if (config.demoMode) {
log("server", "==== Demo Mode ====");
log_info("server", "==== Demo Mode ====");
}
log("server", "Creating express and socket.io instance");
log_info("server", "Creating express and socket.io instance");
const app = express();
let server;
if (sslKey && sslCert) {
log("server", "Server Type: HTTPS");
log_info("server", "Server Type: HTTPS");
server = https.createServer({
key: fs.readFileSync(sslKey),
cert: fs.readFileSync(sslCert)
}, app);
} else {
log("server", "Server Type: HTTP");
log_info("server", "Server Type: HTTP");
server = http.createServer(app);
}
@ -168,7 +168,7 @@ try {
} catch (e) {
// "dist/index.html" is not necessary for development
if (process.env.NODE_ENV !== "development") {
log("server", "Error: Cannot find 'dist/index.html', did you install correctly?", "error");
log_error("server", "Error: Cannot find 'dist/index.html', did you install correctly?");
process.exit(1);
}
}
@ -181,7 +181,7 @@ exports.entryPage = "dashboard";
exports.entryPage = await setting("entryPage");
log("server", "Adding route");
log_info("server", "Adding route");
// ***************************
// Normal Router here
@ -234,7 +234,7 @@ exports.entryPage = "dashboard";
}
});
log("server", "Adding socket handler");
log_info("server", "Adding socket handler");
io.on("connection", async (socket) => {
sendInfo(socket);
@ -242,7 +242,7 @@ exports.entryPage = "dashboard";
totalClient++;
if (needSetup) {
log("server", "Redirect to setup page");
log_info("server", "Redirect to setup page");
socket.emit("setup");
}
@ -255,30 +255,30 @@ exports.entryPage = "dashboard";
// ***************************
socket.on("loginByToken", async (token, callback) => {
log("auth", `Login by token. IP=${getClientIp(socket)}`);
log_info("auth", `Login by token. IP=${getClientIp(socket)}`);
try {
let decoded = jwt.verify(token, jwtSecret);
log("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("auth", "afterLogin", "debug");
log_debug("auth", "afterLogin");
afterLogin(socket, user);
log("auth", "afterLogin ok", "debug");
log_debug("auth", "afterLogin ok");
log("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("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,
@ -287,7 +287,7 @@ exports.entryPage = "dashboard";
}
} catch (error) {
log("auth", `Invalid token for user ${decoded.username}. IP=${getClientIp(socket)}`, "error");
log_error("auth", `Invalid token for user ${decoded.username}. IP=${getClientIp(socket)}`);
callback({
ok: false,
@ -298,11 +298,11 @@ exports.entryPage = "dashboard";
});
socket.on("login", async (data, callback) => {
log("auth", `Login by username + password. IP=${getClientIp(socket)}`);
log_info("auth", `Login by username + password. IP=${getClientIp(socket)}`);
// Login Rate Limit
if (! await loginRateLimiter.pass(callback)) {
log("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;
}
@ -312,7 +312,7 @@ exports.entryPage = "dashboard";
if (user.twofa_status == 0) {
afterLogin(socket, user);
log("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,
@ -324,7 +324,7 @@ exports.entryPage = "dashboard";
if (user.twofa_status == 1 && !data.token) {
log("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,
@ -342,7 +342,7 @@ exports.entryPage = "dashboard";
socket.userID,
]);
log("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,
@ -352,7 +352,7 @@ exports.entryPage = "dashboard";
});
} else {
log("auth", `Invalid token provided for user ${data.username}. IP=${getClientIp(socket)}`, "warn");
log_warn("auth", `Invalid token provided for user ${data.username}. IP=${getClientIp(socket)}`);
callback({
ok: false,
@ -362,7 +362,7 @@ exports.entryPage = "dashboard";
}
} else {
log("auth", `Incorrect username or password for user ${data.username}. IP=${getClientIp(socket)}`, "warn");
log_warn("auth", `Incorrect username or password for user ${data.username}. IP=${getClientIp(socket)}`);
callback({
ok: false,
@ -428,7 +428,7 @@ exports.entryPage = "dashboard";
socket.userID,
]);
log("auth", `Saved 2FA token for user ${data.username}. IP=${getClientIp(socket)}`);
log_info("auth", `Saved 2FA token for user ${data.username}. IP=${getClientIp(socket)}`);
callback({
ok: true,
@ -436,7 +436,7 @@ exports.entryPage = "dashboard";
});
} catch (error) {
log("auth", `Error changing 2FA token for user ${data.username}. IP=${getClientIp(socket)}`, "error");
log_error("auth", `Error changing 2FA token for user ${data.username}. IP=${getClientIp(socket)}`);
callback({
ok: false,
@ -453,7 +453,7 @@ exports.entryPage = "dashboard";
socket.userID,
]);
log("auth", `Disabled 2FA token for user ${data.username}. IP=${getClientIp(socket)}`);
log_info("auth", `Disabled 2FA token for user ${data.username}. IP=${getClientIp(socket)}`);
callback({
ok: true,
@ -461,7 +461,7 @@ exports.entryPage = "dashboard";
});
} catch (error) {
log("auth", `Error disabling 2FA token for user ${data.username}. IP=${getClientIp(socket)}`, "error");
log_error("auth", `Error disabling 2FA token for user ${data.username}. IP=${getClientIp(socket)}`);
callback({
ok: false,
@ -577,7 +577,7 @@ exports.entryPage = "dashboard";
await startMonitor(socket.userID, bean.id);
await sendMonitorList(socket);
log("monitor", `Added Monitor: ${monitorID} User ID: ${socket.userID}`);
log_info("monitor", `Added Monitor: ${monitorID} User ID: ${socket.userID}`);
callback({
ok: true,
@ -587,7 +587,7 @@ exports.entryPage = "dashboard";
} catch (e) {
log("monitor", `Error adding Monitor: ${monitorID} User ID: ${socket.userID}`, "error");
log_error("monitor", `Error adding Monitor: ${monitorID} User ID: ${socket.userID}`);
callback({
ok: false,
@ -644,7 +644,7 @@ exports.entryPage = "dashboard";
});
} catch (e) {
console.error(e);
log_error("monitor", e);
callback({
ok: false,
msg: e.message,
@ -660,7 +660,7 @@ exports.entryPage = "dashboard";
ok: true,
});
} catch (e) {
console.error(e);
log_error("monitor", e);
callback({
ok: false,
msg: e.message,
@ -672,7 +672,7 @@ exports.entryPage = "dashboard";
try {
checkLogin(socket);
log("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,
@ -696,7 +696,7 @@ exports.entryPage = "dashboard";
try {
checkLogin(socket);
log("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.");
@ -767,7 +767,7 @@ exports.entryPage = "dashboard";
try {
checkLogin(socket);
log("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`);
log_info("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`);
if (monitorID in monitorList) {
monitorList[monitorID].stop();
@ -1103,7 +1103,7 @@ exports.entryPage = "dashboard";
let backupData = JSON.parse(uploadedJSON);
log("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 monitorListData = backupData.monitorList;
@ -1275,7 +1275,7 @@ exports.entryPage = "dashboard";
try {
checkLogin(socket);
log("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 = ? ", [
"",
@ -1301,7 +1301,7 @@ exports.entryPage = "dashboard";
try {
checkLogin(socket);
log("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
@ -1325,7 +1325,7 @@ exports.entryPage = "dashboard";
try {
checkLogin(socket);
log("manage", `Clear Statistics User ID: ${socket.userID}`);
log_info("manage", `Clear Statistics User ID: ${socket.userID}`);
await R.exec("DELETE FROM heartbeat");
@ -1345,24 +1345,24 @@ exports.entryPage = "dashboard";
statusPageSocketHandler(socket);
databaseSocketHandler(socket);
log("server", "added all socket handlers", "debug");
log_debug("server", "added all socket handlers");
// ***************************
// Better do anything after added all socket handlers here
// ***************************
log("auth", "check auto login", "debug");
log_debug("auth", "check auto login");
if (await setting("disableAuth")) {
log("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("auth", "need auth", "debug");
log_debug("auth", "need auth");
}
});
log("server", "Init the server");
log_info("server", "Init the server");
server.once("error", async (err) => {
console.error("Cannot listen: " + err.message);
@ -1371,9 +1371,9 @@ exports.entryPage = "dashboard";
server.listen(port, hostname, () => {
if (hostname) {
log("server", `Listening on ${hostname}:${port}`);
log_info("server", `Listening on ${hostname}:${port}`);
} else {
log("server", `Listening on ${port}`);
log_info("server", `Listening on ${port}`);
}
startMonitors();
checkVersion.startInterval();
@ -1457,13 +1457,13 @@ async function getMonitorJSONList(userID) {
async function initDatabase() {
if (! fs.existsSync(Database.path)) {
log("server", "Copying Database");
log_info("server", "Copying Database");
fs.copyFileSync(Database.templatePath, Database.path);
}
log("server", "Connecting to the Database");
log_info("server", "Connecting to the Database");
await Database.connect();
log("server", "Connected");
log_info("server", "Connected");
// Patch the database
await Database.patch();
@ -1473,16 +1473,16 @@ async function initDatabase() {
]);
if (! jwtSecretBean) {
log("server", "JWT secret is not found, generate one.");
log_info("server", "JWT secret is not found, generate one.");
jwtSecretBean = await initJWTSecret();
log("server", "Stored JWT secret into database");
log_info("server", "Stored JWT secret into database");
} else {
log("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("server", "No user, need setup");
log_info("server", "No user, need setup");
needSetup = true;
}
@ -1492,7 +1492,7 @@ async function initDatabase() {
async function startMonitor(userID, monitorID) {
await checkOwner(userID, monitorID);
log("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,
@ -1518,7 +1518,7 @@ async function restartMonitor(userID, monitorID) {
async function pauseMonitor(userID, monitorID) {
await checkOwner(userID, monitorID);
log("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,
@ -1548,10 +1548,10 @@ async function startMonitors() {
}
async function shutdownFunction(signal) {
log("server", "Shutdown requested");
log("server", "Called signal: " + signal);
log_info("server", "Shutdown requested");
log_info("server", "Called signal: " + signal);
log("server", "Stopping all monitors");
log_info("server", "Stopping all monitors");
for (let id in monitorList) {
let monitor = monitorList[id];
monitor.stop();
@ -1565,7 +1565,7 @@ function getClientIp(socket) {
}
function finalFunction() {
log("server", "Graceful shutdown successful!");
log_info("server", "Graceful shutdown successful!");
}
gracefulShutdown(server, {

@ -1,7 +1,7 @@
const { R } = require("redbean-node");
const { checkLogin, setSettings } = require("../util-server");
const dayjs = require("dayjs");
const { log } = require("../../src/util");
const { log, log_info, log_debug, log_error } = require("../../src/util");
const ImageDataURI = require("../image-data-uri");
const Database = require("../database");
const apicache = require("../modules/apicache");
@ -124,7 +124,7 @@ module.exports.statusPageSocketHandler = (socket) => {
]);
let monitorOrder = 1;
console.log(group.monitorList);
log_info("socket", group.monitorList);
for (let monitor of group.monitorList) {
let relationBean = R.dispense("monitor_group");
@ -139,7 +139,7 @@ module.exports.statusPageSocketHandler = (socket) => {
}
// Delete groups that are not in the list
log("socket", "Delete groups that are not in the list", "debug");
log_debug("socket", "Delete groups that are not in the list");
const slots = groupIDList.map(() => "?").join(",");
await R.exec(`DELETE FROM \`group\` WHERE id NOT IN (${slots})`, groupIDList);
@ -149,7 +149,7 @@ module.exports.statusPageSocketHandler = (socket) => {
});
} catch (error) {
console.log(error);
log_error("socket", error);
callback({
ok: false,

@ -1,7 +1,7 @@
const tcpp = require("tcp-ping");
const Ping = require("./ping-lite");
const { R } = require("redbean-node");
const { log } = require("../src/util");
const { log_debug } = require("../src/util");
const passwordHash = require("./password-hash");
const dayjs = require("dayjs");
const { Resolver } = require("dns");
@ -119,7 +119,7 @@ exports.setting = async function (key) {
try {
const v = JSON.parse(value);
log("util", `Get Setting: ${key}: ${v}`, "debug");
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("util", `[${i}] ${link.fingerprint}`, "debug");
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("util", `[Last] ${link.issuerCertificate.fingerprint}`, "debug");
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("util", "Parsing Certificate Info", "debug");
log_debug("util", "Parsing Certificate Info");
const parsedInfo = parseCertificateInfo(info);
return {
@ -345,7 +345,7 @@ exports.startUnitTest = async () => {
*/
exports.convertToUTF8 = (body) => {
const guessEncoding = chardet.detect(body);
//log("util", "Guess Encoding: " + guessEncoding, "debug");
//log_debug("util", "Guess Encoding: " + guessEncoding);
const str = iconv.decode(body, guessEncoding);
return str.toString();
};

@ -435,7 +435,7 @@ dayjs.extend(timezone);
import { timezoneList, setPageLocale } from "../util-frontend";
import { useToast } from "vue-toastification";
import { log } from "../util.ts";
import { log_debug } from "../util.ts";
const toast = useToast();
@ -639,20 +639,20 @@ export default {
this.loadDatabaseSize();
toast.success("Done");
} else {
log("settings", res, "debug");
log_debug("settings", res);
}
});
},
loadDatabaseSize() {
log("settings", "load database size", "debug");
log_debug("settings", "load database size");
this.$root.getSocket().emit("getDatabaseSize", (res) => {
if (res.ok) {
this.databaseSize = res.size;
log("settings", "database size: " + res.size, "debug");
log_debug("settings", "database size: " + res.size);
} else {
log("settings", res, "debug");
log_debug("settings", res);
}
});

@ -7,7 +7,7 @@
// Backend uses the compiled file util.js
// Frontend uses util.ts
exports.__esModule = true;
exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.log = exports.ucfirst = exports.sleep = exports.flipStatus = exports.STATUS_PAGE_PARTIAL_DOWN = exports.STATUS_PAGE_ALL_UP = exports.STATUS_PAGE_ALL_DOWN = exports.PENDING = exports.UP = exports.DOWN = exports.appName = exports.isDev = void 0;
exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.log_debug = exports.log_error = exports.log_warn = exports.log_info = exports.ucfirst = exports.sleep = exports.flipStatus = exports.STATUS_PAGE_PARTIAL_DOWN = exports.STATUS_PAGE_ALL_UP = exports.STATUS_PAGE_ALL_DOWN = exports.PENDING = exports.UP = exports.DOWN = exports.appName = exports.isDev = void 0;
var _dayjs = require("dayjs");
var dayjs = _dayjs;
exports.isDev = process.env.NODE_ENV === "development";
@ -44,9 +44,7 @@ function ucfirst(str) {
return firstLetter.toUpperCase() + str.substr(1);
}
exports.ucfirst = ucfirst;
// log levels = info / warn / error / debug
function log(module, msg, level) {
if (level === void 0) { level = "info"; }
module = module.toUpperCase();
level = level.toUpperCase();
var now = new Date().toISOString();
@ -69,7 +67,22 @@ function log(module, msg, level) {
console.log(formattedMessage);
}
}
exports.log = log;
function log_info(module, msg) {
log(module, msg, "info");
}
exports.log_info = log_info;
function log_warn(module, msg) {
log(module, msg, "warn");
}
exports.log_warn = log_warn;
function log_error(module, msg) {
log(module, msg, "error");
}
exports.log_error = log_error;
function log_debug(module, msg) {
log(module, msg, "debug");
}
exports.log_debug = log_debug;
function polyfill() {
/**
* String.prototype.replaceAll() polyfill

@ -49,8 +49,7 @@ export function ucfirst(str: string) {
return firstLetter.toUpperCase() + str.substr(1);
}
// log levels = info / warn / error / debug
export function log(module: string, msg: any, level:string = "info") {
function log(module: string, msg: any, level:string) {
module = module.toUpperCase();
level = level.toUpperCase();
@ -72,6 +71,21 @@ export function log(module: string, msg: any, level:string = "info") {
}
}
export function log_info(module: string, msg: any) {
log(module, msg, "info");
}
export function log_warn(module: string, msg: any) {
log(module, msg, "warn");
}
export function log_error(module: string, msg: any) {
log(module, msg, "error");
}
export function log_debug(module: string, msg: any) {
log(module, msg, "debug");
}
declare global { interface String { replaceAll(str: string, newStr: string): string; } }

Loading…
Cancel
Save