Created
January 12, 2022 02:49
-
-
Save humbdrag/35ff65308012907e5bccfca2d38f269b to your computer and use it in GitHub Desktop.
[Medium] Python logging setup application
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
# Set up logging directory and create logging file. | |
os.makedirs(log_path, exist_ok=True) | |
log_file = os.path.join(log_path, f'{datetime.date.today()}.log') | |
if os.path.exists(log_file): | |
append_write = 'a' # append if already exists | |
else: | |
append_write = 'w' # make a new file if not | |
# Setup up logging configuration. | |
root_logger = logging.getLogger() | |
root_logger.setLevel(logging.DEBUG) | |
# Create a Formatter. | |
formatter = logging.Formatter( | |
'%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
# Add a Stream Handler. | |
sh = logging.StreamHandler() | |
sh.setLevel(logging.WARNING) | |
sh.setFormatter(formatter) | |
root_logger.addHandler(sh) | |
# Add a File Handler. | |
fh = logging.FileHandler(filename=log_file, mode=append_write) | |
fh.setLevel(logging.DEBUG) | |
fh.setFormatter(formatter) | |
root_logger.addHandler(fh) | |
# Test the handlers. | |
root_logger.warning(f'Stream handler added.') | |
root_logger.debug(f'File handler added.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment