Last active
February 7, 2017 09:18
-
-
Save aleksb86/6b0a57ac4b91922dc3920aa8a4d4c022 to your computer and use it in GitHub Desktop.
Python simple logging snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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