Skip to content

Instantly share code, notes, and snippets.

@aleksb86
Last active February 7, 2017 09:18
Show Gist options
  • Save aleksb86/6b0a57ac4b91922dc3920aa8a4d4c022 to your computer and use it in GitHub Desktop.
Save aleksb86/6b0a57ac4b91922dc3920aa8a4d4c022 to your computer and use it in GitHub Desktop.
Python simple logging snippet
import logging
# Set logger with logfile (*.log) in same directory as current
# executing file.
logger = set_logger('{}.log'.format(os.path.abspath(__file__)))
# Write error event with traceback information:
try:
1 / 0
except Exception as e:
logger.error('Error - divide by zero!', exc_info=True)
def set_logger(log_file_path):
"""
Method for set up logger
(writing events to logfile)
"""
logger = logging.getLogger(__name__)
handler = logging.FileHandler(log_file_path)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment