Skip to content

Commit

Permalink
refine logging
Browse files Browse the repository at this point in the history
  • Loading branch information
rkaminsk committed Feb 23, 2024
1 parent 03fa0a5 commit d1d97c2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 18 deletions.
7 changes: 5 additions & 2 deletions src/fillname/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
The main entry point for the application.
"""

from .utils.logger import setup_logger
import sys

from .utils.logging import configure_logging, get_logger
from .utils.parser import get_parser


Expand All @@ -12,8 +14,9 @@ def main() -> None:
"""
parser = get_parser()
args = parser.parse_args()
log = setup_logger("main", args.log)
configure_logging(sys.stderr, args.log)

log = get_logger("main")
log.info("info")
log.warning("warning")
log.debug("debug")
Expand Down
30 changes: 14 additions & 16 deletions src/fillname/utils/logger.py → src/fillname/utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"""

import logging
import sys

from typing import TextIO

COLORS = {
"GREY": "\033[90m",
Expand Down Expand Up @@ -34,28 +35,25 @@ def filter(self, record: logging.LogRecord) -> bool:

return record.levelno == self.passlevel


def setup_logger(name: str, level: int) -> logging.Logger:
def configure_logging(stream: TextIO, level: int) -> None:
"""
Setup logger.
Configure application logging.
"""

logger = logging.getLogger(name)
logger.propagate = False
logger.setLevel(level)
log_message_str = "{}%(levelname)s:{} - %(message)s{}"

def set_handler(level: int, color: str) -> None:
handler = logging.StreamHandler(sys.stderr)
def make_handler(level: int, color: str) -> logging.StreamHandler:
handler = logging.StreamHandler(stream)
handler.addFilter(SingleLevelFilter(level, False))
handler.setLevel(level)
formatter = logging.Formatter(log_message_str.format(COLORS[color], COLORS["GREY"], COLORS["NORMAL"]))
handler.setFormatter(formatter)
logger.addHandler(handler)
return handler

set_handler(logging.INFO, "GREEN")
set_handler(logging.WARNING, "YELLOW")
set_handler(logging.DEBUG, "BLUE")
set_handler(logging.ERROR, "RED")
handlers = [make_handler(logging.INFO, "GREEN"), make_handler(logging.WARNING, "YELLOW"), make_handler(logging.DEBUG, "BLUE"), make_handler(logging.ERROR, "RED")]
logging.basicConfig(handlers=handlers, level=level)

return logger
def get_logger(name):
"""
Get a logger with the given name.
"""
return logging.getLogger(name)

0 comments on commit d1d97c2

Please sign in to comment.