Skip to content

Instantly share code, notes, and snippets.

@agalea91
Created July 30, 2019 17:30
Show Gist options
  • Save agalea91/fb15953be47562d6b619c2bd4dc3417c to your computer and use it in GitHub Desktop.
Save agalea91/fb15953be47562d6b619c2bd4dc3417c to your computer and use it in GitHub Desktop.
Initialize python logging with file handler
def init_logging(level='debug'):
import logging
import os
import datetime
from pytz import timezone
if level == 'debug':
LOGGING_LEVEL = logging.DEBUG
elif level == 'info':
LOGGING_LEVEL = logging.INFO
else:
raise ValueError('Invalid option for level ({})'.format(level))
DATE_STR = datetime.datetime.now(
timezone('US/Pacific')
).isoformat()
LOGGING_FOLDER = 'logs'
if not os.path.exists(LOGGING_FOLDER):
os.makedirs(LOGGING_FOLDER)
LOGGING_HANDLERS = [
logging.FileHandler(os.path.join(
LOGGING_FOLDER,
'out.{}.log'.format(DATE_STR)
)),
logging.StreamHandler()
]
log_format = (
'%(asctime)s - '
'%(name)s - '
'%(funcName)s - '
'%(levelname)s - '
'%(message)s'
)
logging.basicConfig(
level=LOGGING_LEVEL,
format=log_format,
handlers=LOGGING_HANDLERS,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment