Skip to content

Commit

Permalink
Implement log rotation
Browse files Browse the repository at this point in the history
    - Add RotationFileHabdler for log rotation (5M, 3 backups)
    - Update log format to include filename in debug mode
    - Configure separate handlers for "xradiosd" and "xradios" loggers
    - Remove global logging configuration
  • Loading branch information
andreztz committed Aug 5, 2024
1 parent 41290b5 commit 4f49d56
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions xradios/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os
import logging
import logging.config
from logging.handlers import RotatingFileHandler

from appdirs import user_log_dir
from appdirs import user_data_dir
Expand All @@ -13,22 +15,29 @@

xradios_config_dir = Path(user_config_dir(appname=app_name))
xradios_config_dir.mkdir(parents=True, exist_ok=True)

xradios_data_dir = Path(user_data_dir(appname=app_name))
xradios_data_dir.mkdir(parents=True, exist_ok=True)

xradios_log_dir = Path(user_log_dir(appname=app_name))
xradios_log_dir.mkdir(parents=True, exist_ok=True)

log_level = getattr(logging, os.environ.get("XRADIOS_LOG_LEVEL", "INFO"))

if log_level == logging.DEBUG:
log_format = "%(levelname)s - %(name)s - %(module)s - %(funcName)s - %(message)s"
log_format = "%(levelname)s - %(name)s - %(filename)s -%(module)s - %(funcName)s - %(message)s"
else:
log_format = "%(levelname)s - %(name)s - %(message)s"

log_file = "xradios.log"

logging.basicConfig(
filename=xradios_log_dir / log_file, level=log_level, format=log_format
# logging.config.dictConfig(config={"level": log_level, "handlers": [], "version": 1})
logging.basicConfig(level=log_level, format=log_format)

logging.getLogger().handlers = []
handler = RotatingFileHandler(
filename=xradios_log_dir / log_file,
maxBytes=5 * 1024 * 1024,
backupCount=2
)
# handler.setLevel(log_level)
# handler.setFormatter(logging.Formatter(log_format))
logging.getLogger("xradiosd").addHandler(handler)
logging.getLogger("xradios").addHandler(handler)

0 comments on commit 4f49d56

Please sign in to comment.