Skip to content

Instantly share code, notes, and snippets.

@ismet55555
Last active January 27, 2023 06:02
Show Gist options
  • Save ismet55555/1a0500415b1704ffcac697f15e3dc55f to your computer and use it in GitHub Desktop.
Save ismet55555/1a0500415b1704ffcac697f15e3dc55f to your computer and use it in GitHub Desktop.
Python Logger Setup
"""Logger Setup"""
###################################################################
# NOTES:
# - Stop using print() already
#
# - Simply import this file to setup the logger
# - Only has to be called on time during load
# - Example:
# from some_app import python_logger_setup
#
# - Once setup, you can add logger to top of any file
# import logging # Import the module
# log = logging.getLogger() # Get the logger handle
# log.info("Hey there") # Use the logger
#
# - More info: https://docs.python.org/3/howto/logging.html
###################################################################
import logging
import sys
import coloredlogs
app_name = "Your-App-Name-No-Spaces"
logging_level = logging.INFO
# (Optionl) Turn off INFO level logging for specific python package
# logging.getLogger("dicttoxml").setLevel(logging.ERROR)
# logging.getLogger("urllib3").setLevel(logging.WARNING)
# Setting up log file handler
file_handler = logging.handlers.RotatingFileHandler(
filename=f"{app_name}.log", # Relative to execution directory
mode="w", # Use "a" to append to log file
maxBytes=10000000, # Will remove oldest logs after this log file size
backupCount=0,
delay=True,
encoding="utf-8"
)
# Also include any sys.stdout in logs
stdout_handler = logging.StreamHandler(sys.stdout)
# Define log message format
logger_format = f"[{app_name}] - [%(asctime)s] - %(levelname)-10s - %(message)s"
date_format = "%d-%b-%y %H:%M:%S"
# Defining the logger
logging.basicConfig(
level=logging_level
format=logger_format,
datefmt=date_format,
handlers=[file_handler, stdout_handler],
)
# Applying color to the output logs
coloredlogs.install(fmt=logger_format, datefmt=date_format)
# Usage
log = logging.getLogger()
log.info("Successfully set up logger!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment