Skip to content

Instantly share code, notes, and snippets.

@humbdrag
Created January 12, 2022 02:49
Show Gist options
  • Save humbdrag/35ff65308012907e5bccfca2d38f269b to your computer and use it in GitHub Desktop.
Save humbdrag/35ff65308012907e5bccfca2d38f269b to your computer and use it in GitHub Desktop.
[Medium] Python logging setup application
# 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