Skip to content

Commit

Permalink
Merge pull request #5 from MEHRSHAD-MIRSHEKARY/bugfix/log-levels-filt…
Browse files Browse the repository at this point in the history
…ering

Add LoggingLevelFilter to Ensure Proper Log Level Filtering
  • Loading branch information
ARYAN-NIKNEZHAD authored Aug 17, 2024
2 parents 941b5f0 + 9fdf063 commit 159169a
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
Empty file.
38 changes: 38 additions & 0 deletions django_logging/filters/level_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import logging


class LoggingLevelFilter(logging.Filter):
"""
Filters log records based on their logging level.
This filter is used to prevent log records from being written to log files
intended for lower log levels. For example, if we have separate log
files for DEBUG, INFO, WARNING, and ERROR levels, this filter ensures that
a log record with level ERROR is only written to the ERROR log file, and not
to the DEBUG, INFO or WARNING log files.
"""

def __init__(self, logging_level: int):
"""
Initializes a LoggingLevelFilter instance.
Args:
logging_level: The logging level to filter on (e.g. logging.DEBUG, logging.INFO, etc.).
Returns:
None
"""
super().__init__()
self.logging_level = logging_level

def filter(self, record: logging.LogRecord) -> bool:
"""
Filters a log record based on its level.
Args:
record: The log record to filter.
Returns:
True if the log record's level matches the specified logging level, False otherwise.
"""
return record.levelno == self.logging_level
12 changes: 12 additions & 0 deletions django_logging/settings/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import os
from typing import List, Dict, Optional

from django_logging.filters.level_filter import LoggingLevelFilter


class LogConfig:
"""
Expand Down Expand Up @@ -67,6 +69,7 @@ def set_conf(self) -> None:
"filename": log_file,
"formatter": "default",
"level": level,
"filters": [level.lower()]
}
for level, log_file in self.log_files.items()
}
Expand All @@ -76,6 +79,14 @@ def set_conf(self) -> None:
"level": "DEBUG",
}

filters = {
level.lower(): {
"()": LoggingLevelFilter,
"logging_level": getattr(logging, level),
}
for level in self.log_config.log_levels
}

loggers = {
level.lower(): {
"level": level,
Expand All @@ -88,6 +99,7 @@ def set_conf(self) -> None:
config = {
"version": 1,
"handlers": handlers,
"filters": filters,
"loggers": loggers,
"root": {"level": "DEBUG", "handlers": list(handlers.keys())},
"disable_existing_loggers": False,
Expand Down

0 comments on commit 159169a

Please sign in to comment.