Skip to content

Instantly share code, notes, and snippets.

@leela

leela/debug.log

Last active Sep 2, 2020
Embed
What would you like to do?
python - Log only severity level error and above messages into error.log & also log all the messages into debug.log
4 divided by 2
4 divided by 0
Zero division error
Traceback (most recent call last):
File "logging_example.py", line 27, in division
return a/b
ZeroDivisionError: division by zero
Zero division error
Traceback (most recent call last):
File "logging_example.py", line 27, in division
return a/b
ZeroDivisionError: division by zero
"""
* Log all the messages into debug.log
* Log only severity level error and above messages into error.log
"""
import logging
from logging import FileHandler
# create logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # handles messages of severity DEBUG and above
# create a handler to log all messages of sevirity DEBUG and above.
debug_handler = FileHandler("debug.log")
debug_handler.setLevel(logging.DEBUG)
# create a handler to log all messages of sevirity ERROR and above.
error_handler = FileHandler("error.log")
error_handler.setLevel(logging.ERROR)
# add handlers to logger.
# logger sends all the incoming messages to all the handlers.
logger.addHandler(debug_handler)
logger.addHandler(error_handler)
def division(a, b):
logger.debug(f"{a} divided by {b}") # this message comes only in debug.log
try:
return a/b
except ZeroDivisionError:
logger.error("Zero division error", exc_info=True) # this message comes in both error.log & debug.log
if __name__ == "__main__":
division(4, 2)
division(4, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.