Nearby lessons
86 of 159Python - Logging
- Understand why storing application flow and exception information is important
- Know the six logging levels and their severity values
- Configure logging with basicConfig(filename=..., level=...)
- Write log messages using debug, info, warning, error, and critical
- Write exception information into the log file with logging.exception()
Python Logging
It is highly recommended to store the complete application flow and exception information in a file.
This process is called Logging.
Advantages of Logging
- We can use log files while performing debugging.
- We can provide statistics such as the number of requests per day.
Logging Module
To implement Logging, Python provides one inbuilt module.
Logging Levels
Depending on the type of information, logging data is divided into the following 6 levels.
| Logging Level | Value | Description |
|---|---|---|
| CRITICAL | 50 | Represents a very serious problem that needs high attention. |
| ERROR | 40 | Represents a serious error. |
| WARNING | 30 | Represents a warning message. Some caution is needed. It alerts the programmer. |
| INFO | 20 | Represents a message with some important information. |
| DEBUG | 10 | Represents a message with debugging information. |
| NOTSET | 0 | Represents that the level is not set. |
Default Logging Level
By default, while executing a Python program, only WARNING level and higher level messages are displayed.
That means, by default, messages of the following levels are shown:
- WARNING
- ERROR
- CRITICAL
Messages of these levels are not displayed by default:
- DEBUG
- INFO
How to Implement Logging
To perform Logging:
- Create a file to store log messages.
- Specify which level of messages should be stored.
We can do this by using the basicConfig() function of the logging module:
Explanation
- filename='log.txt' — creates a log file named
log.txt. - level=logging.WARNING — stores WARNING level messages and all higher level messages.
Methods Used to Write Log Messages
After creating the log file, we can write messages by using the following methods:
| Method | Purpose |
|---|---|
logging.debug() |
Writes a DEBUG message |
logging.info() |
Writes an INFO message |
logging.warning() |
Writes a WARNING message |
logging.error() |
Writes an ERROR message |
logging.critical() |
Writes a CRITICAL message |
Program to Create a Log File and Write WARNING and Higher Level Messages
Write a Python program to create a log file and write WARNING and higher level messages.
log.txt (WARNING Level)
After executing the above program, the log.txt file contains:
WARNING:root:This is warning message ERROR:root:This is error message CRITICAL:root:This is critical message
Explanation
The print() statement writes Logging Module Demo to the console only — it is not written to the log file.
Because the logging level is set to WARNING, only WARNING, ERROR, and CRITICAL messages are stored:
| Log Method | Stored in log.txt? |
|---|---|
logging.debug() |
❌ No |
logging.info() |
❌ No |
logging.warning() |
✅ Yes |
logging.error() |
✅ Yes |
logging.critical() |
✅ Yes |
Program Using DEBUG Level
If we set the logging level to DEBUG, then all messages will be written to the log file.
log.txt (DEBUG Level)
DEBUG:root:This is debug message INFO:root:This is info message WARNING:root:This is warning message ERROR:root:This is error message CRITICAL:root:This is critical message
Comparison
| Logging Level | Messages Written to log.txt |
|---|---|
logging.WARNING |
WARNING, ERROR, CRITICAL |
logging.DEBUG |
DEBUG, INFO, WARNING, ERROR, CRITICAL |
How to Write Python Program Exceptions to the Log File
By using the following function, we can write exception information to the log file.
Python Program to Write Exception Information to the Log File
Write a Python program to write exception information to the log file.
Program Execution
Case 1 - input 10 and 2:
5.0
No exception occurs, so the division is performed successfully.
Case 2 - input 10 and 0:
cannot divide with zero
A ZeroDivisionError is raised. The program prints cannot divide with zero and writes the complete exception information to mylog.txt by using logging.exception(msg).
Case 3 - input 10 and ten:
Enter only int values
A ValueError is raised. The program prints Enter only int values and stores the complete exception information in mylog.txt.
Purpose of logging.info() and logging.exception()
logging.info("A New request Came:")writes a message when a new request starts.logging.info("Request Processing Completed")writes a message when the request finishes.logging.exception(msg)writes the full exception information into the log file whenever an exception occurs.
Complete Program Flow
Start Program
│
▼
Configure Logging
│
▼
Write "A New request Came:"
│
▼
Read First Number
│
▼
Read Second Number
│
▼
Perform Division
│
├───────────────────────┐
│ │
▼ ▼
Success Exception Occurs
│ │
│ ├──► ZeroDivisionError
│ │ │
│ │ ▼
│ │ logging.exception(msg)
│ │
│ └──► ValueError
│ │
│ ▼
│ logging.exception(msg)
│
▼
Write "Request Processing Completed"
│
▼
End
- Logging stores application flow and exception details in a file instead of only printing to the console
- The default logging level is WARNING - only WARNING and higher messages appear
- basicConfig(filename, level) creates the log file and sets the minimum level to record
- print() goes to the console only; logging methods write to the log file
- logging.exception(msg) writes the full exception details into the log file from inside an except block