![]() |
VOOZH | about |
Logging is the process of keeping a record of what a program is doing while it runs, which helps developers understand program behavior and easily find and fix errors like invalid inputs or system failures.
Output
ERROR:root:GFG raised an error
Explanation:
There are five built-in levels of the log message.
If required, developers have the option to create more levels but these are sufficient enough to handle every possible situation.
Below are some useful logging handlers in Python that help control where and how log messages are output.
Handler | Description |
|---|---|
StreamHandler | Sends messages to streams (file-like objects). |
FileHandler | Sends messages to disk files. |
RotatingFileHandler | Sends messages to disk files, with support for maximum log file sizes and log file rotation. |
Below example shows how to log messages directly to a file using Python’s FileHandler.
Output: The code writes the log messages to the file app.log.
This is an info message
This is an error message
Explanation:
Logging in Python lets you record messages while your program runs. Follow these simple steps:
Logging a variable means recording the value of a variable while a program runs, which helps track how data changes, debug issues, and understand program behavior step by step.
Output
INFO: The value of age is 25
Explanation:
Python allows you to record messages with different importance levels. For example, you can log simple information, warnings, errors, or critical problems, which helps beginners track what’s happening in a program step by step.
The above code will generate a file with the provided name (newfile.log) and if we open the file, the file contains the following data.
Explanation:
Logging exceptions helps indicate errors or unusual conditions in a program. Raising an exception stops normal execution and notifies the caller or logging system about the issue.
In this code, we are raising an Exception that is being caught by the logging.exception.
Output
Enter a value: -1
2023-06-15 18:25:18,064 - ERROR - Exception occurred: Invalid value: Value cannot be negative.
ValueError: Invalid value: Value cannot be negative.
Explanation:
While print() can help in simple scripts, it is not reliable for complex programs. Python’s built-in logging module is more flexible: