python記錄日志
Making your code production-ready is not an easy task. There are so many things to consider, one of them being able to monitor the application’s flow. That’s where logging comes in — a simple tool to save some nerves and many, many hours.
使您的代碼可用于生產環境并非易事。 有很多事情要考慮,其中之一就是能夠監視應用程序的流程。 這就是日志記錄的來源-一個簡單的工具,可以節省很多時間和許多時間。
Python has great built-in support for logging. It’s implemented through the logging
library, and is quite similar to options found in other major programming languages.
Python具有強大的內置日志記錄支持。 它是通過logging
庫實現的,與其他主要編程語言中的選項非常相似。
If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic.
如果您更喜歡視頻,或者只是想增強自己的知識,請隨時觀看我們有關該主題的視頻。
Before we jump into the code, let’s briefly discuss why you should care about logging, and cover some light theory behind it.
在進入代碼之前,讓我們簡要討論一下為什么您應該關心日志記錄,并介紹其背后的一些輕理論。
記錄-為什么? (Logging — Why?)
I’ve mentioned previously that logging is used to monitor applications flow, among other things. The question you may have now is why can’t we just use print statements? We can, but it’s not ideal. There’s no way to track the severity of the message through simple print statements. That’s where logging shines.
前面已經提到過,日志記錄用于監視應用程序流,等等。 您現在可能遇到的問題是, 為什么我們不能僅使用打印語句? 我們可以,但是并不理想。 無法通過簡單的打印語句來跟蹤消息的嚴重性。 那就是伐木大放異彩的地方。
Here’s my top 3 list of reasons why you should use logging in your applications:
這是我應該在應用程序中使用日志記錄的前三點原因:
To get an understanding of how your code works — you don’t want to be blind in production
為了了解您的代碼如何工作 -您不想在生產中盲目
To capture and fix unexpected errors — and detect potential bigger issues with your code
捕獲和修復意外錯誤 -并檢測代碼中潛在的更大問題
To analyze and visualize how the app performs — more advanced topic
分析和可視化應用程序的性能 -更高級的主題
As mentioned previously, the logging
library is built into Python programming language and provides 5 severity levels:
如前所述, logging
庫內置于Python編程語言中,并提供5個嚴重級別:
- DEBUG 調試
- INFO 信息
- WARNING 警告
- ERROR 錯誤
- CRITICAL 危急
You can reason just from the name when you should use one instead of the other, but it’s important to note that Python shows messages of severity level WARNING and above by default. That behavior can be changed.
您可以僅從名稱中推斷出何時應使用一個而不是另一個,但要注意的是,Python默認顯示嚴重級別為WARNING或更高的消息。 該行為可以更改。
Let’s now explore logging with some simple code.
現在讓我們用一些簡單的代碼來探索日志記錄。
記錄-如何? (Logging — How?)
To start, let’s perform a couple of imports:
首先,讓我們執行幾個導入:
import random
import time
from datetime import datetime
import logging
As you can see, the logging
library is included here. I’ve mentioned previously that Python will show only messages of severity level WARNING and above, so here’s how we can change that:
如您所見, logging
庫包含在此處。 前面已經提到過,Python將僅顯示嚴重級別為WARNING及以上的消息,因此,我們可以通過以下方法進行更改:
logging.basicConfig(level=logging.DEBUG)
And that’s it! Let's declare a simple function that generates a random number from 0 to 4, and logs messages of different severity level based on that random number. After a message is displayed, the program sleeps for a second. This function is used purely for testing:
就是這樣! 讓我們聲明一個簡單的函數,該函數生成一個0到4之間的隨機數,并根據該隨機數記錄不同嚴重性級別的消息。 顯示一條消息后,程序將Hibernate一秒鐘。 此功能僅用于測試:
def log_tester():
x = random.randint(0, 4)
if x == 0:
logging.debug(‘Debug message’)
elif x == 1:
logging.info(‘Info message’)
elif x == 2:
logging.warning(‘Warning message’)
elif x == 3:
logging.error(‘Error message’)
elif x == 4:
logging.critical(‘Critical message’) time.sleep(1)
return
And finally, we need to call this function somewhere, so why don’t we do that in a loop? Just to have multiple messages printed out:
最后,我們需要在某個地方調用此函數,那么為什么不循環執行呢? 只是為了打印出多條消息:
for i in range(5):
log_tester()
If you run this code now, you will get an output similar to mine:
如果現在運行此代碼,您將獲得類似于我的輸出:
Output:WARNING:root:Warning message
ERROR:root:Error message
DEBUG:root:Debug message
INFO:root:Info message
INFO:root:Info message
Keep in mind that your output may differ, due to the randomization process.
請記住,由于隨機化過程,您的輸出可能會有所不同。
This format is fine for some cases, but other times we might want more control, and to be able to further customize how the output looks like.
在某些情況下,這種格式是可以的,但在其他情況下,我們可能需要更多控制權,并能夠進一步自定義輸出的外觀。
Let’s explore how.
讓我們探討一下。
輸出格式 (Output formatting)
Let’s alter the logging.basicConfig
slightly:
讓我們稍微修改logging.basicConfig
:
logging.basicConfig(level=logging.DEBUG, format=’%(levelname)s → %(name)s:%(message)s’)
If you were to run this code now, the messages would be formatted in the way specified:
如果您現在要運行此代碼,則將以指定的方式格式化消息:
Output:CRITICAL → root:Critical message
WARNING → root:Warning message
DEBUG → root:Debug message
DEBUG → root:Debug message
CRITICAL → root:Critical message
That’s fine, but what I like to do is to add current date and time information to messages. It’s easy to do with format strings:
很好,但是我想做的是向消息中添加當前日期和時間信息。 使用格式字符串很容易:
logging.basicConfig(level=logging.DEBUG, format=f’%(levelname)s → {datetime.now()} → %(name)s:%(message)s’)
Here’s how our new format looks like:
我們的新格式如下所示:
DEBUG → 2020–08–09 10:32:11.519365 → root:Debug message
DEBUG → 2020–08–09 10:32:11.519365 → root:Debug message
DEBUG → 2020–08–09 10:32:11.519365 → root:Debug message
ERROR → 2020–08–09 10:32:11.519365 → root:Error message
WARNING → 2020–08–09 10:32:11.519365 → root:Warning message
Now we’re getting somewhere! To get the actual time the message was logged you’d need to embed the call to datetime.now()
inside the message.
現在我們到了某個地方! 要獲取記錄消息的實際時間,您需要將調用嵌入到消息中的datetime.now()
。
The only problem is that the logs are lost forever once the terminal window is closed. So instead of outputting the messages to the console, let’s explore how we can save them to a file.
唯一的問題是,一旦關閉終端窗口,日志將永遠丟失。 因此,讓我們探索如何將它們保存到文件中,而不是將消息輸出到控制臺。
保存到文件 (Saving to a file)
To save log messages to a file, we need to specify values for two more parameters:
要將日志消息保存到文件,我們需要為另外兩個參數指定值:
filename
— name of the file in which logs will be savedfilename
將在其中保存日志的文件的名稱filemode
— write or append modes, we’ll explore those in a bitfilemode
寫入或追加模式,我們將在稍后進行探討
Let’s see how we can use the write
mode first. This mode will overwrite any existing file with the specified name every time the application is run. Here’s the configuration:
讓我們看看如何首先使用write
模式。 每次運行該應用程序時,此模式都會覆蓋具有指定名稱的任何現有文件。 配置如下:
logging.basicConfig(
filename=’test.log’,
filemode=’w’,
level=logging.DEBUG,
format=’%(levelname)s → {datetime.now()} → %(name)s:%(message)s’
)
If you run the program now, no output would be shown in the console. Instead, a new file called test.log
is created, and it contains your log messages:
如果立即運行該程序,則控制臺中不會顯示任何輸出。 而是創建一個名為test.log
的新文件,其中包含您的日志消息:
test.log:WARNING → 2020–08–09 10:35:54.115026 → root:Warning message
INFO → 2020–08–09 10:35:54.115026 → root:Info message
WARNING → 2020–08–09 10:35:54.115026 → root:Warning message
DEBUG → 2020–08–09 10:35:54.115026 → root:Debug message
CRITICAL → 2020–08–09 10:35:54.115026 → root:Critical message
If you were to run the program again, these 5 rows would be lost and replaced with new 5 rows. In some cases that’s not what you want, so we can use the append
mode to keep the previous data and write new rows o the end. Here’s the configuration:
如果要再次運行該程序,這5行將丟失并被新的5行替換。 在某些情況下,這不是您想要的,因此我們可以使用append
模式保留先前的數據并在末尾寫入新行。 配置如下:
logging.basicConfig(
filename=’test.log’,
filemode=’a’,
level=logging.DEBUG,
format=’%(levelname)s → {datetime.now()} → %(name)s:%(message)s’
)
If you were to run the program now, and look at our file, you’d see 10 rows there:
如果您現在要運行該程序并查看我們的文件,則會在其中看到10行:
test.log:WARNING → 2020–08–09 10:35:54.115026 → root:Warning message
INFO → 2020–08–09 10:35:54.115026 → root:Info message
WARNING → 2020–08–09 10:35:54.115026 → root:Warning message
DEBUG → 2020–08–09 10:35:54.115026 → root:Debug message
CRITICAL → 2020–08–09 10:35:54.115026 → root:Critical message
DEBUG → 2020-08-09 10:36:24.699579 → root:Debug message
INFO → 2020-08-09 10:36:24.699579 → root:Info message
CRITICAL → 2020-08-09 10:36:24.699579 → root:Critical message
CRITICAL → 2020-08-09 10:36:24.699579 → root:Critical message
CRITICAL → 2020-08-09 10:36:24.699579 → root:Critical message
And that’s it. You now know the basics of logging. Let’s wrap things up in the next section.
就是這樣。 您現在知道了日志記錄的基礎知識。 讓我們在下一節中總結一下。
你走之前 (Before you go)
Logging isn’t the most fun thing to do, sure. But without it, you are basically blind. Take a moment to think about how would you monitor the behavior and flow of a deployed application without logging? Not so easy, I know.
當然,記錄并不是最有趣的事情。 但是沒有它,您基本上是盲人。 花點時間考慮一下如何在不登錄的情況下監視已部署應用程序的行為和流程? 我知道這并不容易。
In 5 minutes we’ve got the basics covered, and you are now ready to implement logging in your next application. It doesn’t have to be an application in strict terms, you can also use it for data science projects as well.
在5分鐘內,我們已經涵蓋了基礎知識,現在您可以在下一個應用程序中實現日志記錄了。 嚴格來說,它不一定是應用程序,也可以將其用于數據科學項目。
Thanks for reading. Take care.
謝謝閱讀。 照顧自己。
Join my private email list for more helpful insights.
加入我的私人電子郵件列表以獲取更多有用的見解。
翻譯自: https://towardsdatascience.com/logging-explained-in-5-minutes-walkthrough-with-python-8bd7d8c2cf3a
python記錄日志
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/387975.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/387975.shtml 英文地址,請注明出處:http://en.pswp.cn/news/387975.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!