From c4ec798de318551bb2e5e3f14ef14f955413a80c Mon Sep 17 00:00:00 2001 From: Jeremiah K Date: Sat, 22 Apr 2023 14:44:56 -0500 Subject: [PATCH] Add optional timestamp support to logger --- README.md | 2 ++ main.py | 21 ++++++++++++++++++--- sample_config.yaml | 4 +++- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index cb480ae..ae313e1 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,8 @@ meshtastic: logging: level: "info" + show_timestamps: true + timestamp_format: '[%m/%d/%y]-%H:%M:%S' ``` ## Usage diff --git a/main.py b/main.py index e3fa8d6..8d4a5fd 100644 --- a/main.py +++ b/main.py @@ -16,17 +16,32 @@ from nio import AsyncClient, AsyncClientConfig, MatrixRoom, RoomMessageText, Roo from pubsub import pub from yaml.loader import SafeLoader from typing import List, Union +from datetime import datetime bot_start_time = int(time.time() * 1000) # Timestamp when the bot starts, used to filter out old messages -logging.basicConfig() -logger = logging.getLogger(name="meshtastic.matrix.relay") - # Load configuration with open("config.yaml", "r") as f: relay_config = yaml.load(f, Loader=SafeLoader) +# Configure logging +logger = logging.getLogger(name="meshtastic.matrix.relay") +log_level = getattr(logging, relay_config["logging"]["level"].upper()) +show_timestamps = relay_config["logging"]["show_timestamps"] +timestamp_format = relay_config["logging"]["timestamp_format"] + +if show_timestamps: + log_format = f"%(asctime)s %(levelname)s:%(name)s:%(message)s" +else: + log_format = "%(levelname)s:%(name)s:%(message)s" + logger.setLevel(getattr(logging, relay_config["logging"]["level"].upper())) +logger.propagate = False # Add this line to prevent double logging + +formatter = logging.Formatter(log_format, datefmt=timestamp_format) +handler = logging.StreamHandler() +handler.setFormatter(formatter) +logger.addHandler(handler) # Initialize SQLite database def initialize_database(): diff --git a/sample_config.yaml b/sample_config.yaml index ab59d19..afc2530 100644 --- a/sample_config.yaml +++ b/sample_config.yaml @@ -17,4 +17,6 @@ meshtastic: broadcast_enabled: true logging: - level: "info" \ No newline at end of file + level: "debug" + show_timestamps: true + timestamp_format: '[%m/%d/%y]-%H:%M:%S' \ No newline at end of file