Created
September 29, 2021 18:26
-
-
Save knu2xs/c4b6667272454177a2f7d2d8c4936c5e to your computer and use it in GitHub Desktop.
concisely get an easy to use logger
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 | |
from pathlib import Path | |
from typing import Union | |
def get_logger(log_path: Union[str, Path] = 'logfile.log', log_name: str = 'logger', log_level: int = logging.ERROR): | |
""" | |
Standardized way to create a console and file logger in one. | |
Args: | |
log_path: Where to save the log file. | |
log_name: Name of the logger to identify it. | |
log_level: One of the logging levels to use. (logging.INFO, logging.DEBUG, | |
logging.WARN, logging.ERROR, or logging.CRITICAL) | |
Return: | |
Logger to use for reporting. | |
""" | |
# get a logger to work with | |
logger = logging.getLogger(log_name) | |
# create a formtter to incude useful information | |
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
# create both a file and stream handler | |
fh = logging.FileHandler(log_path) | |
sh = logging.StreamHandler() | |
# add the handlers to the logger | |
for hndlr in [fh, sh]: | |
hndlr.setFormatter(formatter) | |
logger.addHandler(hndlr) | |
# set the log level for reporting | |
logger.setLevel(log_level) | |
return logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment