In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to use Python log to improve programming technology, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Why use logs instead of print ()
Logging is a very important function for programmers. Logging is also useful for debugging and displaying run-time information. In this article, I'll show you why and how to use python's logging module in your program.
There is a key difference between print statements and log output. Typically, a print statement is written to standard output (stdout), expecting it to be useful information or program output. However, the log is written to standard error (stderr). We can demonstrate this scenario as follows.
Import logging logging.basicConfig (level=logging.INFO) # We'll talk about this soon! Logging.warning ('Something bad could happenings') Logging.info ('You are running the program') logging.error (' Aw snap! Everything failed.') Print ("This is the program output")
Now, if I run this program, I will see the following on the command line.
$python log_test.py WARNING:root:Something bad could happen! INFO:root:You are running the program ERROR:root:Aw snap! Everything failed. This is the program output
However, there is too much information for the average user. Although this is actually displayed together on the command line, the data is written to two separate streams. Therefore, a typical user should do the following.
$python log_test.py > program_output.txt WARNING:root:Something bad could happen! INFO:root:You are running the program ERROR:root:Aw snap! Everything failed. $cat program_output.txt This is the program output
Here, write useful program output to a file by redirecting >. So we can see what's going on on the terminal and easily get the output in the file. Now let's try to understand the log level!
Log and log level
Logging may occur for different reasons. These reasons are divided into the following severity.
Debugging: debug information for developers, such as calculated values, estimated parameters, url, API calls, etc.
Information: information, nothing serious.
Warning: a warning of user input, parameters, etc.
Error: report errors caused by what the user does or happens in the program.
CRITICAL: the highest priority log output. For key issues (depending on the use case).
The most common log types are DEBUG, INFO, and ERROR. However, it is easy for python to throw a version mismatch warning.
Configure loggers and log handlers
The recorder can be configured under different parameters. The logger can be configured to follow a specific log level, file name, file mode, and print log output format.
Configure log collector parameters
The logger can be configured as follows.
Import logging logging.basicConfig (filename='program.log', filemode='w', level=logging.DEBUG) logging.warning ('You are given a warningships')
The above setting requires the logger to output the log to a file named program.log. Filemode= 'w 'defines the nature of writing to a file. For example,'w 'opens a new file and overwrites anything there. By default, this parameter is'a log, which opens the log file in additional mode. Sometimes it is useful to have a log history. The level parameter defines the lowest level of logging. For example, if you set it to INFO, the debug log will not be printed. As you may have seen, the program needs to run in inverbose=debug mode to view some parameters. The default level is INFO.
Create a log handler
Although the above method is simple for a simple application, for production-ready software or services, we need a comprehensive logging process. This is because it is difficult to find specific error logs among millions of debug logs. In addition, we need to use a single logger throughout the program and module. So that we can correctly append the log to the same file. To do this, we can use handlers with different configurations for this task.
Import logging logger = logging.getLogger ("My Logger") logger.setLevel (logging.DEBUG) console_handler = logging.StreamHandler () file_handler = logging.FileHandler ('file.log', mode='w') console_handler.setLevel (logging.INFO) file_handler.setLevel (logging.DEBUG) logger.addHandler (console_handler) logger.addHandler (file_handler)
As you can see, we first get a logger that passes the name. This enables us to reuse the same logger elsewhere in the program. We set the global logging level to DEBUG. This is the lowest logging level, so it allows us to use any logging level in other handlers.
Next, we create two handlers for console and file authoring. For each processor, we provide a log level. This helps reduce the overhead of console output and transfer them to file handlers. Make it easy to deal with debugging later.
Format log output
Logs are not just about printing our own messages. Sometimes we need to print other information, such as time, log level, and process id. For this task, we can use the log format. Let's look at the following code.
Console_format = logging.Formatter ('% (name) s -% (levelname) s -% (message) s') file_format = logging.Formatter ('% (asctime) s -% (name) s -% (levelname) s -% (message) s') console_handler.setFormatter (console_format) file_handler.setFormatter (file_format)
Before adding a handler to the logger, we can format the log output as described above. There are more parameters available for this. You can find them here.
Reuse code
The following is a log code snippet that I will continue to use in many of my applications. I think this might be useful for you as a reader.
Import logging logger = logging.getLogger ('Program Name-Version') logger.setLevel (logging.DEBUG) formatter = logging.Formatter ('% (asctime) s -% (levelname) s -% (message) s') consoleHeader = logging.StreamHandler () consoleHeader.setFormatter (formatter) consoleHeader.setLevel (logging.INFO) fileHandler = logging.FileHandler (f "{output} / metabcc-lr.log") fileHandler.setLevel (logging.DEBUG) fileHandler.setFormatter (formatter) logger.addHandler (fileHandler) logger.addHandler (consoleHeader ) these are all the contents of the article "how to use logging to improve programming techniques in Python" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.