Skip to content

Instantly share code, notes, and snippets.

@Red-Eyed
Last active September 11, 2024 15:40
Show Gist options
  • Save Red-Eyed/024735453be38b629254d805e77f6c5a to your computer and use it in GitHub Desktop.
Save Red-Eyed/024735453be38b629254d805e77f6c5a to your computer and use it in GitHub Desktop.
Convenient way to set python logging
from pathlib import Path
import logging
import sys
def set_logger(error_file: Path, info_file: Path):
error_file = Path(error_file).expanduser().resolve()
error_file.parent.mkdir(exist_ok=True, parents=True)
info_file = Path(info_file).expanduser().resolve()
info_file.parent.mkdir(exist_ok=True, parents=True)
formatter = logging.Formatter(fmt='[%(asctime)s] [%(levelname)s] [%(module)s]: %(message)s')
class LevelFilter(logging.Filter):
def __init__(self, low, high):
self._low = low
self._high = high
logging.Filter.__init__(self)
def filter(self, record):
if self._low <= record.levelno <= self._high:
return True
return False
error_file_handler = logging.FileHandler(filename=error_file.as_posix())
error_file_handler.addFilter(LevelFilter(logging.WARNING, logging.CRITICAL))
error_file_handler.setFormatter(formatter)
info_file_handler = logging.FileHandler(filename=info_file.as_posix())
info_file_handler.addFilter(LevelFilter(logging.INFO, logging.INFO))
info_file_handler.setFormatter(formatter)
info_stream_handler = logging.StreamHandler(sys.stdout)
info_stream_handler.addFilter(LevelFilter(logging.INFO, logging.INFO))
info_stream_handler.setFormatter(formatter)
logging.basicConfig(handlers=[info_file_handler, error_file_handler, info_stream_handler],
force=True,
level=logging.INFO)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment