python记录日志_5分钟内解释日志记录—使用Python演练
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.
使您的代碼可用于生產(chǎn)環(huán)境并非易事。 有很多事情要考慮,其中之一就是能夠監(jiān)視應(yīng)用程序的流程。 這就是日志記錄的來源-一個簡單的工具,可以節(jié)省很多時間和許多時間。
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具有強(qiáng)大的內(nèi)置日志記錄支持。 它是通過logging庫實(shí)現(xiàn)的,與其他主要編程語言中的選項非常相似。
If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic.
如果您更喜歡視頻,或者只是想增強(qiáng)自己的知識,請隨時觀看我們有關(guān)該主題的視頻。
Before we jump into the code, let’s briefly discuss why you should care about logging, and cover some light theory behind it.
在進(jìn)入代碼之前,讓我們簡要討論一下為什么您應(yīng)該關(guān)心日志記錄,并介紹其背后的一些輕理論。
記錄-為什么? (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.
前面已經(jīng)提到過,日志記錄用于監(jiān)視應(yīng)用程序流,等等。 您現(xiàn)在可能遇到的問題是, 為什么我們不能僅使用打印語句? 我們可以,但是并不理想。 無法通過簡單的打印語句來跟蹤消息的嚴(yán)重性。 那就是伐木大放異彩的地方。
Here’s my top 3 list of reasons why you should use logging in your applications:
這是我應(yīng)該在應(yīng)用程序中使用日志記錄的前三點(diǎn)原因:
To get an understanding of how your code works — you don’t want to be blind in production
為了了解您的代碼如何工作 -您不想在生產(chǎn)中盲目
To capture and fix unexpected errors — and detect potential bigger issues with your code
捕獲和修復(fù)意外錯誤 -并檢測代碼中潛在的更大問題
To analyze and visualize how the app performs — more advanced topic
分析和可視化應(yīng)用程序的性能 -更高級的主題
As mentioned previously, the logging library is built into Python programming language and provides 5 severity levels:
如前所述, logging庫內(nèi)置于Python編程語言中,并提供5個嚴(yán)重級別:
- DEBUG 調(diào)試
- 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.
您可以僅從名稱中推斷出何時應(yīng)使用一個而不是另一個,但要注意的是,Python默認(rèn)顯示嚴(yán)重級別為WARNING或更高的消息。 該行為可以更改。
Let’s now explore logging with some simple code.
現(xiàn)在讓我們用一些簡單的代碼來探索日志記錄。
記錄-如何? (Logging — How?)
To start, let’s perform a couple of imports:
首先,讓我們執(zhí)行幾個導(dǎo)入:
import randomimport 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庫包含在此處。 前面已經(jīng)提到過,Python將僅顯示嚴(yán)重級別為WARNING及以上的消息,因此,我們可以通過以下方法進(jìn)行更改:
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:
就是這樣! 讓我們聲明一個簡單的函數(shù),該函數(shù)生成一個0到4之間的隨機(jī)數(shù),并根據(jù)該隨機(jī)數(shù)記錄不同嚴(yán)重性級別的消息。 顯示一條消息后,程序?qū)ibernate一秒鐘。 此功能僅用于測試:
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:
最后,我們需要在某個地方調(diào)用此函數(shù),那么為什么不循環(huán)執(zhí)行呢? 只是為了打印出多條消息:
for i in range(5):log_tester()
If you run this code now, you will get an output similar to mine:
如果現(xiàn)在運(yùn)行此代碼,您將獲得類似于我的輸出:
Output:WARNING:root:Warning messageERROR: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.
請記住,由于隨機(jī)化過程,您的輸出可能會有所不同。
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.
在某些情況下,這種格式是可以的,但在其他情況下,我們可能需要更多控制權(quán),并能夠進(jìn)一步自定義輸出的外觀。
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:
如果您現(xiàn)在要運(yùn)行此代碼,則將以指定的方式格式化消息:
Output:CRITICAL → root:Critical messageWARNING → 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:
很好,但是我想做的是向消息中添加當(dāng)前日期和時間信息。 使用格式字符串很容易:
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 messageDEBUG → 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.
現(xiàn)在我們到了某個地方! 要獲取記錄消息的實(shí)際時間,您需要將調(diào)用嵌入到消息中的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.
唯一的問題是,一旦關(guān)閉終端窗口,日志將永遠(yuǎn)丟失。 因此,讓我們探索如何將它們保存到文件中,而不是將消息輸出到控制臺。
保存到文件 (Saving to a file)
To save log messages to a file, we need to specify values for two more parameters:
要將日志消息保存到文件,我們需要為另外兩個參數(shù)指定值:
filename — name of the file in which logs will be saved
filename將在其中保存日志的文件的名稱
filemode — write or append modes, we’ll explore those in a bit
filemode寫入或追加模式,我們將在稍后進(jìn)行探討
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模式。 每次運(yùn)行該應(yīng)用程序時,此模式都會覆蓋具有指定名稱的任何現(xiàn)有文件。 配置如下:
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:
如果立即運(yùn)行該程序,則控制臺中不會顯示任何輸出。 而是創(chuàng)建一個名為test.log的新文件,其中包含您的日志消息:
test.log:WARNING → 2020–08–09 10:35:54.115026 → root:Warning messageINFO → 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:
如果要再次運(yùn)行該程序,這5行將丟失并被新的5行替換。 在某些情況下,這不是您想要的,因此我們可以使用append模式保留先前的數(shù)據(jù)并在末尾寫入新行。 配置如下:
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:
如果您現(xiàn)在要運(yùn)行該程序并查看我們的文件,則會在其中看到10行:
test.log:WARNING → 2020–08–09 10:35:54.115026 → root:Warning messageINFO → 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.
就是這樣。 您現(xiàn)在知道了日志記錄的基礎(chǔ)知識。 讓我們在下一節(jié)中總結(jié)一下。
你走之前 (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.
當(dāng)然,記錄并不是最有趣的事情。 但是沒有它,您基本上是盲人。 花點(diǎn)時間考慮一下如何在不登錄的情況下監(jiān)視已部署應(yīng)用程序的行為和流程? 我知道這并不容易。
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分鐘內(nèi),我們已經(jīng)涵蓋了基礎(chǔ)知識,現(xiàn)在您可以在下一個應(yīng)用程序中實(shí)現(xiàn)日志記錄了。 嚴(yán)格來說,它不一定是應(yīng)用程序,也可以將其用于數(shù)據(jù)科學(xué)項目。
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記錄日志
總結(jié)
以上是生活随笔為你收集整理的python记录日志_5分钟内解释日志记录—使用Python演练的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到爸爸给我剪头发是什么意思
- 下一篇: 每个人都应该使用的Python 3中被忽