Skip to content

Commit

Permalink
Refine LoggerConfig and LoggerSettings
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinFoka committed Oct 16, 2024
1 parent 7178db1 commit 42e02a1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 18 deletions.
40 changes: 26 additions & 14 deletions frinx/common/logging/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import logging
import logging.config
from typing import Literal

from frinx.common.logging.root_logger import root_log_handler
from frinx.common.logging.settings import LoggerSettings
Expand All @@ -7,52 +9,62 @@

class LoggerConfig:
"""
Configuration class for setting up logging.
LoggerConfig class is responsible for setting up and configuring logging.
"""
_setup_done = False
_logger_settings = LoggerSettings()
_setup_done: bool = False # Class variable to ensure the logging setup happens only once

def __init__(self, level: str | None = None, handlers: list[str] | None = None):
self.level = level or self._logger_settings.DEFAULT_LOG_LEVEL
self.handlers = handlers or self._logger_settings.DEFAULT_HANDLERS
def __init__(self,
log_file_path: str | None = None,
level: Literal['DEBUG', 'INFO', 'WARNING'] | None = None) -> None:
"""
Initializes the LoggerConfig class with optional overrides for the log file path and log level.
"""
self.logger_settings = LoggerSettings()
self.logger_settings.LOG_FILE_PATH = log_file_path or self.logger_settings.LOG_FILE_PATH
self.logger_settings.LOG_LEVEL = level or self.logger_settings.LOG_LEVEL

def setup_logging(self) -> None:
"""Set up logging configuration using dictConfig."""
"""
Adds the root_log_handler for the root logger and marks the setup as complete to prevent reconfiguration.
"""
if LoggerConfig._setup_done:
return # Prevent reconfiguration

# Apply the logging configuration and add root_log_handler
logging.config.dictConfig(self.generate_logging_config())
logging.getLogger().addHandler(root_log_handler)
LoggerConfig._setup_done = True

def generate_logging_config(self) -> DictAny:
"""Generate the logging configuration dictionary."""
"""
Generates the dictionary for configuring the logging.
"""
return {
'version': 1,
'disable_existing_loggers': True,
'disable_existing_loggers': False,
'formatters': {
'verbose_formatter': {
'format': self._logger_settings.LOG_FORMAT_VERBOSE,
'format': self.logger_settings.LOG_FORMAT_VERBOSE,
'datefmt': '%Y-%m-%d %H:%M:%S',
},
'default_formatter': {
'format': self._logger_settings.LOG_FORMAT_DEFAULT,
'format': self.logger_settings.LOG_FORMAT_DEFAULT,
'datefmt': '%Y-%m-%d %H:%M:%S',
},
},
'handlers': {
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': str(self._logger_settings.LOG_FILE_PATH),
'filename': str(self.logger_settings.LOG_FILE_PATH),
'maxBytes': 10 * 1024 * 1024, # 10 MB
'backupCount': 10,
'level': self.level,
'level': self.logger_settings.LOG_LEVEL,
'formatter': 'verbose_formatter',
},
},
'root': {
'handlers': ['file'], # NOTE: The root_log_handler is attached automatically.
'level': self.level,
'level': self.logger_settings.LOG_LEVEL,
'propagate': False,
},
}
10 changes: 6 additions & 4 deletions frinx/common/logging/settings.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import os
from pathlib import Path

from pydantic_settings import BaseSettings


class LoggerSettings(BaseSettings):
LOG_FILE_PATH: Path = Path(os.environ.get('LOG_FILE_PATH', '/tmp/workers.log'))
DEFAULT_LOG_LEVEL: str = os.environ.get('LOG_LEVEL', 'INFO').upper()
DEFAULT_HANDLERS: list[str] = ['file'] # The root handler is used by default for logging.
"""
A class that defines logger settings, which can be overridden by environment variables.
Defaults are provided if no environment variables are set.
"""
LOG_FILE_PATH: str = os.environ.get('LOG_FILE_PATH', '/tmp/workers.log')
LOG_LEVEL: str = os.environ.get('LOG_LEVEL', 'INFO').upper()
LOG_FORMAT_DEFAULT: str = '%(asctime)s | %(threadName)s | %(levelname)s | %(source)s | %(message)s'
LOG_FORMAT_VERBOSE: str = '%(asctime)s | %(levelname)s | %(name)s | %(filename)s:%(lineno)d | %(message)s'

0 comments on commit 42e02a1

Please sign in to comment.