Last active
September 2, 2020 16:20
-
-
Save leela/395dab9b502f517916a008f2dded12bb to your computer and use it in GitHub Desktop.
python - Log only severity level error and above messages into error.log & also log all the messages into debug.log
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
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 |
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
Zero division error | |
Traceback (most recent call last): | |
File "logging_example.py", line 27, in division | |
return a/b | |
ZeroDivisionError: division by zero |
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
""" | |
* 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