Last active
October 27, 2022 13:06
-
-
Save DrDougPhD/7380f007b1e567a65231c0b80c67350d to your computer and use it in GitHub Desktop.
Python Color Logging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import os | |
import pathlib | |
import colorlog | |
default_level = 'DEBUG' | |
def setup(verbosity: str = default_level): | |
level = logging.getLevelName(verbosity) | |
logger = logging.getLogger(__package__) | |
logger.setLevel(level) | |
here = pathlib.Path(__file__) | |
source_root = here.parent | |
project_root = source_root.parent | |
logging_directory = project_root / 'logs' | |
logging_directory.mkdir(parents=True, exist_ok=True) | |
file_log_handler = logging.FileHandler(logging_directory / f'{verbosity.lower()}.log') | |
file_log_handler.setLevel(level) | |
command_line_handler = logging.StreamHandler() | |
command_line_handler.setLevel(level) | |
default_record_factory = logging.getLogRecordFactory() | |
def relative_pathname_record_factory(*args, **kwargs): | |
record = default_record_factory(*args, **kwargs) | |
record_source_file_relative_path = pathlib.Path(record.pathname).relative_to(source_root) | |
if record_source_file_relative_path.name == '__init__.py': | |
record_source_file_relative_path = record_source_file_relative_path.parent | |
module_path = str(record_source_file_relative_path).replace(os.sep, '.') | |
record.relpathname = module_path | |
return record | |
logging.setLogRecordFactory(relative_pathname_record_factory) | |
# add colors to the logs! | |
colored_files_funcs_linenos_formatter = colorlog.ColoredFormatter( | |
fmt=( | |
"%(asctime)s - %(log_color)s%(levelname)-8s%(reset)s" | |
" [ %(relpathname)s:%(funcName)s()::%(lineno)s ] " | |
"%(message)s" | |
), | |
datefmt='%Y-%m-%d %H:%M:%S', | |
reset=True, | |
) | |
for handler in (file_log_handler, command_line_handler): | |
handler.setFormatter(colored_files_funcs_linenos_formatter) | |
logger.addHandler(handler) | |
return logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment