Skip to content

Instantly share code, notes, and snippets.

@schuster-rainer
Created January 10, 2012 10:59
Show Gist options
  • Save schuster-rainer/1588477 to your computer and use it in GitHub Desktop.
Save schuster-rainer/1588477 to your computer and use it in GitHub Desktop.
configure console and rotating logger
import os
import logging
import logging.handlers
import datetime
def configure_console_and_rotating_logger(log_file_name=__name__,
log_folder="./logs",
date_format="%Y-%m-%d %H:%M:%S",
log_format="%(asctime)s - %(module)s - %(levelname)s - %(message)s",
log_level=logging.NOTSET,
max_bytes=500000,
backup_count=20):
logger = logging.getLogger()
logger.setLevel(log_level)
#compute day of year
day_of_year = datetime.datetime.now().toordinal()
# setup rotating log handler
log_folder = os.path.abspath(log_folder)
if not os.path.exists(log_folder):
os.mkdir(log_folder)
console_handler = logging.StreamHandler()
rotating_name = log_file_name + "_%06d.log" % day_of_year
rotating_name = os.path.join(log_folder, rotating_name)
rotating_handler = logging.handlers.RotatingFileHandler(rotating_name,
maxBytes=max_bytes,
backupCount=backup_count)
# setup formatters
formatter = logging.Formatter(log_format, date_format)
console_handler.setFormatter(formatter)
rotating_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.addHandler(rotating_handler )
if __name__ == "__main__":
#example usage
configure_console_and_rotating_logger()
logging.info("test")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment