Skip to content

Commit

Permalink
Merge pull request #100 from jeremiah-k/map_plugin-bare-excepts
Browse files Browse the repository at this point in the history
Add options to log to file
  • Loading branch information
jeremiah-k authored Nov 24, 2024
2 parents 29b2946 + 3fe87d2 commit 0a08362
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 10 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ plugins/__pycache__/
*.pyd
*$py.class
custom_plugins/
logs/*
plugins/custom/*
plugins/community/*

# Allow the directories themselves to be tracked
!logs/.gitkeep
!plugins/custom/.gitkeep
!plugins/community/.gitkeep
39 changes: 32 additions & 7 deletions log_utils.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,46 @@
import logging

import os
from logging.handlers import RotatingFileHandler
from config import relay_config


def get_logger(name):
logger = logging.getLogger(name=name)
log_level = getattr(logging, relay_config["logging"]["level"].upper())

logger.setLevel(log_level)
logger.propagate = False # Add this line to prevent double logging
logger.propagate = False

handler = logging.StreamHandler()
handler.setFormatter(
# Add stream handler (console logging)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(
logging.Formatter(
fmt="%(asctime)s %(levelname)s:%(name)s:%(message)s",
datefmt="%Y-%m-%d %H:%M:%S %z",
)
)
logger.addHandler(handler)
logger.addHandler(stream_handler)

# Check if file logging is enabled
if relay_config["logging"].get("log_to_file", False):
# Default to `logs/mmrelay.log` if no filename is provided
log_file = relay_config["logging"].get("filename", "logs/mmrelay.log")

# Only create directories if the path is not the default
if log_file != "logs/mmrelay.log":
log_dir = os.path.dirname(log_file)
if log_dir: # Ensure non-empty directory paths exist
os.makedirs(log_dir, exist_ok=True)

# Set up size-based log rotation
max_bytes = relay_config["logging"].get("max_log_size", 10 * 1024 * 1024) # Default 10 MB
backup_count = relay_config["logging"].get("backup_count", 5) # Default to 5 backups
file_handler = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)

file_handler.setFormatter(
logging.Formatter(
fmt="%(asctime)s %(levelname)s:%(name)s:%(message)s",
datefmt="%Y-%m-%d %H:%M:%S %z",
)
)
logger.addHandler(file_handler)

return logger
Empty file added logs/.gitkeep
Empty file.
9 changes: 6 additions & 3 deletions plugins/map_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@

import s2sphere
import staticmaps
from log_utils import get_logger
from nio import AsyncClient, UploadResponse
from PIL import Image, ImageFont

from plugins.base_plugin import BasePlugin

logger = get_logger(__name__)

class TextLabel(staticmaps.Object):
def __init__(self, latlng: s2sphere.LatLng, text: str, fontSize: int = 12) -> None:
Expand Down Expand Up @@ -53,7 +55,8 @@ def render_pillow(self, renderer: staticmaps.PillowRenderer) -> None:
try:
font = ImageFont.truetype(path, self._font_size)
break
except Exception:
except OSError:
logger.warning(f"Failed to load font from {path}")
pass

if not font:
Expand Down Expand Up @@ -281,15 +284,15 @@ async def handle_room_message(self, room, event, full_message):

try:
zoom = int(zoom)
except:
except ValueError:
zoom = self.config.get("zoom", 13)

if zoom < 0 or zoom > 30:
zoom = 8

try:
image_size = (int(image_size[0]), int(image_size[1]))
except:
except (ValueError, TypeError):
image_size = (
self.config.get("image_width", 1000),
self.config.get("image_height", 1000),
Expand Down
5 changes: 5 additions & 0 deletions sample_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ meshtastic:

logging:
level: info
log_to_file: true
filename: logs/mmrelay.log # Default location
max_log_size: 10485760 # 10 MB (default if omitted)
backup_count: 5 # Keep 5 backups (default if omitted)

#Note: Some plugins are experimental and some need maintenance.
plugins:
Expand All @@ -28,6 +32,7 @@ plugins:
nodes:
active: true
# Other core plugins..

#community-plugins: # Note: Community plugins are a new feature. Please report any issues.
# sample_plugin:
# active: true
Expand Down

0 comments on commit 0a08362

Please sign in to comment.