From 7f182d63727230747afdf353f0e87a7241276537 Mon Sep 17 00:00:00 2001
From: Christian Paul <christianp@matrix.org>
Date: Wed, 9 Dec 2020 16:34:52 +0100
Subject: [PATCH] Warn if the log level is invalid

---
 src/log.ts       | 11 +++++++++++
 test/test_log.ts | 18 ++++++++++++++++++
 2 files changed, 29 insertions(+)

diff --git a/src/log.ts b/src/log.ts
index 0477d8a..aa86412 100644
--- a/src/log.ts
+++ b/src/log.ts
@@ -46,6 +46,10 @@ export class Log {
     private static config: DiscordBridgeConfigLogging;
     private static logger: Logger;
 
+    private static isValidLevel(level: string) {
+        return ['silly', 'verbose', 'info', 'http', 'warn', 'error', 'silent'].includes(level);
+    }
+
     private static setupLogger() {
         if (Log.logger) {
             Log.logger.close();
@@ -53,6 +57,9 @@ export class Log {
         const tsports: transports.StreamTransportInstance[] = Log.config.files.map((file) =>
             Log.setupFileTransport(file),
         );
+        if (Log.config.console && !Log.isValidLevel(Log.config.console)) {
+            new Log("Log").warn("Console log level is invalid. Please pick one of the case-sensitive levels provided in the sample config.");
+        }
         tsports.push(new transports.Console({
             level: Log.config.console,
         }));
@@ -80,6 +87,10 @@ export class Log {
             return info;
         });
 
+        if (config.level && !Log.isValidLevel(config.level)) {
+            new Log("Log").warn(`Log level of ${config.file} is invalid. Please pick one of the case-sensitive levels provided in the sample config.`);
+        }
+
         const opts = {
             datePattern: config.datePattern,
             filename: config.file,
diff --git a/test/test_log.ts b/test/test_log.ts
index 00acb7d..ca9b044 100644
--- a/test/test_log.ts
+++ b/test/test_log.ts
@@ -71,6 +71,24 @@ describe("Log", () => {
             expect(Log.config.files).to.not.be.empty;
             expect(Log.config.files[0].file).to.equal("./logfile.log");
         });
+        it("should warn if log level got misspelled", () => {
+            Log.Configure({
+                console: "WARNING",
+                lineDateFormat: "HH:mm:ss",
+            });
+            expect(loggedMessages).to.contain("Console log level is invalid. Please pick one of the case-sensitive levels provided in the sample config.");
+        });
+        it("should warn if log level for a file got misspelled", () => {
+            Log.Configure({
+                files: [
+                    {
+                        file: "./logfile.log",
+                        level: "WARNING",
+                    },
+                ],
+            });
+            expect(loggedMessages).to.contain("Log level of ./logfile.log is invalid. Please pick one of the case-sensitive levels provided in the sample config.");
+        });
     });
     describe("ForceSilent", () => {
         it("should be silent", () => {
-- 
GitLab