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.

使您的代碼可用于生產環境并非易事。 有很多事情要考慮,其中之一就是能夠監視應用程序的流程。 這就是日志記錄的來源-一個簡單的工具,可以節省很多時間和許多時間。

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:

這是我應該在應用程序中使用日志記錄的前三點原因:

  1. To get an understanding of how your code works — you don’t want to be blind in production

    為了了解您的代碼如何工作 -您不想在生產中盲目

  2. To capture and fix unexpected errors — and detect potential bigger issues with your code

    捕獲和修復意外錯誤 -并檢測代碼中潛在的更大問題

  3. 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 saved

    filename將在其中保存日志的文件的名稱

  • filemode — write or append modes, we’ll explore those in a bit

    filemode寫入或追加模式,我們將在稍后進行探討

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,一經查實,立即刪除!

相關文章

理解 Linux 中 `ls` 的輸出

理解 Linux 中 ls 的輸出ls 的輸出會因各 Linux 版本變種而略有差異,這里只討論一般情況下的輸出。 下面是來自 man page 關于 ls 的描述: $ man ls ls - list directory contents 列出文件夾中的內容。 但一般我們會配合著 -l 參數使用,將輸…

鎖表的進程和語句,并殺掉

查看鎖表進程SQL語句1: select sess.sid, sess.serial#, lo.oracle_username, lo.os_user_name, ao.object_name, lo.locked_mode from v$locked_object lo, dba_objects ao, v$session sess where ao.object_id lo.object_id and lo.session_id sess.sid; 查看鎖…

p值 t值 統計_非統計師的P值

p值 t值 統計Here is a summary of how I was taught to assess the p-value in hopes of helping some other non-statistician out there.這是關于如何教會我評估p值的摘要,希望可以幫助其他一些非統計學家。 P-value in Context上下文中的P值 Let’s start wit…

獲取對象屬性(key)

for…in方法Object.keysObject.getOwnPropertyNames關于對象的可枚舉性(enumerable) var obj {a: 1,b: 2 } Object.defineProperty(obj, c, {value: 3,enumerable: false }) 復制代碼enumerable設置為false,表示不可枚舉,for…in…

github免費空間玩法

GitHub 是一個用于使用Git版本控制系統的項目的基于互聯網的存取服務,GitHub于2008年2月運行。在2010年6月,GitHub宣布它現在已經提供可1百萬項目,可以說非常強大。 Github雖然是一個代碼倉庫,但是Github還免費為大家提供一個免費開源Github …

用php生成HTML文件的類

目的 用PHP生成HTML文檔, 支持標簽嵌套縮進, 支持標簽自定義屬性 起因 這個東西確實也是心血來潮寫的, 本來打算是輸出HTML片段用的, 但后來就干脆寫成了一個可以輸出完整HTML的功能; 我很滿意里邊的實現縮進的機制, 大家有用到的可以看看p.s. 現在都是真正的前后端分離了(vue,…

在Markdown中輸入數學公式

寫在前面 最近想要把一些數學和編程方面的筆記記錄成電子筆記,因為修改、插入新內容等比較方便。這里記一下在Markdown中輸入數學公式的方法。 基礎知識 公式與文本的區別 公式輸入和文本輸入屬于不同的模式,公式中無法通過空格來控制空白,通…

如何不部署Keras / TensorFlow模型

While the most articles about deep learning are focusing at the modeling part, there are also few about how to deploy such models to production. Some of them say “production”, but they often simply use the un-optimized model and embed it into a Flask web…

[BZOJ3626] [LNOI2014] LCA 離線 樹鏈剖分

題面 考慮到詢問的\(l..r,z\)具有可減性,考慮把詢問差分掉,拆成\(r,z\)和\(l-1,z\)。 顯然這些LCA一定在\(z\)到根的路徑上。下面的問題就是怎么統計。 考慮不是那么暴力的暴力。 我們似乎可以把\(1..r\)的所有點先瞎搞一下,求出一個點內部有…

Linux查看系統各類信息

說明:Linux下可以在/proc/cpuinfo中看到每個cpu的詳細信息。但是對于雙核的cpu,在cpuinfo中會看到兩個cpu。常常會讓人誤以為是兩個單核的cpu。其實應該通過Physical Processor ID來區分單核和雙核。而Physical Processor ID可以從cpuinfo或者dmesg中找到…

biopython中文指南_Biopython新手指南-第1部分

biopython中文指南When you hear the word Biopython what is the first thing that came to your mind? A python library to handle biological data…? You are correct! Biopython provides a set of tools to perform bioinformatics computations on biological data s…

整合后臺服務和驅動代碼注入

整合后臺服務和驅動代碼注入 Home鍵的驅動代碼: /dev/input/event1: 0001 0066 00000001 /dev/input/event1: 0000 0000 00000000 /dev/input/event1: 0001 0066 00000000 /dev/input/event1: 0000 0000 00000000 對應輸入的驅動代碼: sendevent/dev/…

Java作業09-異常

6. 為如下代碼加上異常處理 byte[] content null; FileInputStream fis new FileInputStream("testfis.txt"); int bytesAvailabe fis.available();//獲得該文件可用的字節數 if(bytesAvailabe>0){content new byte[bytesAvailabe];//創建可容納文件大小的數組…

為數據計算提供強力引擎,阿里云文件存儲HDFS v1.0公測發布

2019獨角獸企業重金招聘Python工程師標準>>> 在2019年3月的北京云棲峰會上,阿里云正式推出全球首個云原生HDFS存儲服務—文件存儲HDFS,為數據分析業務在云上提供可線性擴展的吞吐能力和免運維的快速彈性伸縮能力,降低用戶TCO。阿里…

對食材的敬畏之心極致產品_這些數據科學產品組合將給您帶來敬畏和啟發(2020年中的版本)

對食材的敬畏之心極致產品重點 (Top highlight)為什么選擇投資組合? (Why portfolios?) Data science is a tough field. It combines in equal parts mathematics and statistics, computer science, and black magic. As of mid-2020, it is also a booming fiel…

android模擬用戶輸入

目錄(?)[-] geteventsendeventinput keyevent 本文講的是通過使用代碼,可以控制手機的屏幕和物理按鍵,也就是說不只是在某一個APP里去操作,而是整個手機系統。 getevent/sendevent getevent&sendevent 是Android系統下的一個工具&#x…

真格量化常見報錯信息和Debug方法

1.打印日志 1.1 在代碼中添加運行到特定部分的提示: 如果我們在用戶日志未能看到“調用到OnQuote事件”文字,說明其之前的代碼就出了問題,導致程序無法運行到OnQuote函數里的提示部分。解決方案為仔細檢查該部分之前的代碼是否出現問題。 1.2…

向量積判斷優劣弧_判斷經驗論文優劣的10條誡命

向量積判斷優劣弧There are a host of pathologies associated with the current peer review system that has been the subject of much discussion. One of the most substantive issues is that results reported in leading journals are commonly papers with the most e…

自定義PopView

改代碼是參考一個Demo直接改的&#xff0c;代碼中有一些漏洞&#xff0c;如果發現其他的問題&#xff0c;可以下方直接留言 .h文件 #import <UIKit/UIKit.h> typedef void(^PopoverBlock)(NSInteger index); interface CustomPopView : UIView //property(nonatomic,copy…

線控耳機監聽

當耳機的媒體按鍵被單擊后&#xff0c;Android系統會發出一個廣播&#xff0c;該廣播的攜帶者一個Action名為MEDIA_BUTTON的Intent。監聽該廣播便可以獲取手機的耳機媒體按鍵的單擊事件。 在Android中有個AudioManager類&#xff0c;該類會維護MEDIA_BUTTON廣播的分發&#xf…