Using log messages to monitor variables and program errors can clearly distinguish log messages from output information. It is a common method for troubleshooting errors during program development.
directory
- 1 Use the log module
- Do not use the print() debugger
- 3 Log Level
- 4 Disabling Logs
- 5 Record logs to a file
Hello! The big bad Wolf who saved money to buy hair tonic came again. Recently, when I was in the most project development, I talked with my friends about fixing bugs.
Well, for an unskilled programmer, fixing bugs is really a headache, especially for large project development, when there are many variables, the repeated check errors can really make the hair tremble.
How many people in Python have used print() to print a variable to check for argument errors?
B: well… I did the same thing before I was bald, but later I discovered that assertions were a good thing in order to have more time to fix bugs in the future, and later in order to directly observe the process of a value change in the entire program, and discovered that log processing is really sweet.
So today, the Big Bad Wolf is going to talk to you about Python log handling,
Journaling is a great way to understand what’s happening in your program and in what order.
To log the execution of a program in Python, we need to invoke the Logging module. With this module, we can easily create custom log messages. These log messages describe when the program is executing and when the logging function is called, and list the values of any variables we want to specify at that time.
On the other hand, if we find some log messages missing in the log file, it indicates that some code was skipped and never executed. What does this mean… Well, as a programmer, you probably know that too.
1 Use the log module
To use log messages, you need to enable the logging module to display log information on the screen while the application is running, so of course you need to call the module first and type the following code:
Call logging
import logging
logging.basicConfig(filename='logginginfo.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
Copy the code
The purpose of this line of code is to define an output format that outputs the execution time of a particular log message.
When Python logs an event, it creates a LogRecord object and stores information about the event. The Logging module’s functions allow you to specify how the LogRecord object should be seen and how you want the details to be displayed.
It is important to note that when we want to output the monitored values through a log file, we call logging.debug (), which prints the same way as print(), and the format of the output values for this line is what we originally specified in logging.loasicConfig(). And includes the parameter message we pass to debug().
Take a factorial function as an example. We monitor how each variable in the function changes as the program runs:
# factorial calculation log message output instance
import logging
logging.basicConfig( level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
#logging.disable(logging.CRITICAL)
logging.debug("Program test:")
def factorial(n) :
logging.debug("The factorial number is: %s" %(n))
result = 1
for i in range(1, n + 1):
result *= i
logging.debug("In this case, the number multiplied by: %s, the result is %s" %(i, result))
logging.debug('Final result: %s' %(result))
return result
print(factorial(5))
Copy the code
Running results:
From the output of these log messages, we can see the changes in the values within the loop as the program executes. From the printed log file, we can see that the logging.debug () function not only outputs the values of the variables we are monitoring, but also the time and word Bebug when the function is called.
Through such a log we can be very intuitive to see the changes in the process of running the program.
Do not use the print() debugger
Now let’s talk about why it is not recommended to use print() to monitor the output of values. This is not to say that pintf cannot print the values of the variables we monitor.
Instead, we spend a lot of time cleaning the print() function out of the code for each log message after debugging the program, so that we are likely to delete all the output we expect.
However, log messages are a good way to avoid this, and you can add as many log variables to your program as you want.
Don’t you need to disable the output of log files at the end?
Of course not, but statements that use logging.debug() don’t need to be disabled one by one at the end, just call logging.disable(logging.critical) to disable logging altogether.
Unlike the print () function, which must delete or comment out every line, the logging.disable module makes it easier to show and hide log files.
Ha ha, next you might think I’m going to say logging.disable().
B: well… Isn’t it a surprise to see the level of logging messages in Python? Nothing will have oh!
3 Log Level
The log file we are calling has log levels, and “log levels” provides one way.
In this way, log messages are classified according to their importance. Five log levels are shown in the following table, from the least important to the most important. Different log function messages can be recorded and output according to a certain level.
The log message is passed to these functions as a string, and the log level is only for the purpose of detecting possible errors in the program. Ultimately, the specific level of log messages used depends on your program.
The nice thing about logging levels is that we can change the priority of the log messages we want to see by passing logging DEBUG as the level keyword argument to the basicConfig() function, which displays messages at all log levels.
At the same time, we may not want to display all log messages during a program development, so we can modify the level keyword parameter.
For example, change the level keyword parameter of basicConfig() to logging.error. In this way, only ERROR and CRITICAL log messages are displayed. Logs below ERROR are not displayed on the screen.
For example, in the following line of code, we only disable INFO and below log messages, but do not disable WARNING messages above INFO
# log disable
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
# Disable INFO and below log messages
logging.disable(logging.INFO)
logging.debug("Program test:")
def factorial(n) :
logging.debug("The factorial number is: %s" %(n))
result = 1
for i in range(1, n + 1):
result *= i
logging.debug("In this case, the number multiplied by: %s, the result is %s" %(i, result))
logging.warning('Final result: %s' %(result))
return result
print(factorial(5))
Copy the code
The results are as follows:
Ok, after talking about the log level, it is time to disable the log appearance!
4 Disabling Logs
After debugging, we don’t want all of these logs to appear on the screen, so we need to disable them by calling logging.disable, so that the log messages don’t have to go into the program to manually delete or comment out all the logs, just pass a level to logging.disable. He would ban all log messages at that level and lower,
So if you want to disable all logging, just add it to your program
logging.disable(logging.CRITICAL),
Copy the code
It is also important to note that the logging.disable() function disables all subsequent messages of this level and below.
So here we can put the logging.disable() function to disable log messages at the front of the application file, under the import Logging module, so that it can be easily found and commented out as needed to enable or disable log messages.
5 Record logs to a file
In addition to displaying log messages on the screen, we can also write them into text files. The purpose of this is to prevent too many log files from being displayed on the screen during program debugging, thus affecting the reading of variables. The rogging. BasicConfig function accepts the filename keyword as an argument, like this:
Write the log to a file
logging.basicConfig(filename='logginginfo.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
Copy the code
The log message is then saved to a specific text file, using the same factorial function to save the log message to TXT file:
In this case, the output of the program will only have what we want to print with print(), and the log message will be saved in the corresponding log file.
While log messages are useful, if they are not displayed in files, they may appear on the screen with the results we want to output, making it difficult to find the actual output from the program. Once the log information is written to a file, the screen will be clean and tidy, and the information will be well preserved.
In this way, after the program runs, if some program errors are found, we can directly read the log in the text file to view the variable information.
I think so. Yeah.Thumb up attentionHey!
Follow my wechat official account“Grey Wolf Cave Owner”The background to reply“Python notes”To get fromGet started to master the full set of Python notes and Python common knowledge functions quick guide!
Big bad Wolf is looking forward to progress with you!