python練習_如何使用Logzero在Python中練習記錄

python練習

Logzero is a Python package created by Chris Hager that simplifies logging with Python 2 and 3. Logzero makes it easier as a print statement to show information and debugging details.

Logzero是Chris Hager創建的Python程序包,它簡化了Python 2和3的日志記錄。Logzero使它更容易用作顯示信息和調試詳細信息的打印語句。

If you are wondering what logging is, I recommend that you read the previous article I wrote about “How to Run Machine Learning Experiments with Python Logging Module”, especially the first 3 sections.

如果您想知道什么是日志記錄 ,我建議您閱讀上一篇有關“如何使用Python日志記錄模塊運行機器學習實驗”的文章 ,特別是前三部分。

In that article, you will learn:

在該文章中,您將學習:

  • What is Logging?

    什么是日志記錄?
  • Why logging is important.

    為什么記錄很重要。
  • Applications of logging in different technology industries.

    伐木在不同技術行業中的應用。

Logzero has different features that make it easier to use in Python projects. Some of these features are:

Logzero具有不同的功能,可以更輕松地在Python項目中使用。 其中一些功能是:

  • Easy logging to console and/or file.

    輕松記錄到控制臺和/或文件。
  • Provides a fully configured standard Python logger object.

    提供完整配置的標準Python記錄器對象。
  • Pretty formatting, including level-specific colors in the console.

    漂亮的格式,包括控制臺中特定于級別的顏色

  • works with all kinds of character encodings and special characters.

    適用于各種字符編碼和特殊字符。
  • Compatible with Python 2 and 3.

    與Python 2和3兼容。
  • No further Python dependencies.

    沒有更多的Python依賴項。

安裝 (Installation)

To install logzero with pip run the following:

要使用pip安裝logzero,請運行以下命令:

pip install -U logzero

You can also install logzero from the public Github repo:

您還可以從公共Github存儲庫安裝logzero:

git clone https://github.com/metachris/logzero.git
cd logzero
python setup.py install

基本范例 (Basic Example)

We will start with a basic example. In the python file, we will import the logger from logzero and try 4 different logging level examples.

我們將從一個基本示例開始。 在python文件中,我們將從logzero導入記錄器,并嘗試4種不同的記錄級別示例。

#import logger from logzero
from logzero import loggerlogger.debug("hello")
logger.info("info")
logger.warning("warning")
logger.error("error")

The output is colored so it's easy to read.

輸出是彩色的,因此易于閱讀。

As you can see each level has its own color. This means you can identify the level easily by checking the color.

如您所見,每個級別都有其自己的顏色。 這意味著您可以通過檢查顏色輕松識別等級。

將日志寫入文件 (Write logs to a file)

Most of the time Python users tend to write logs in the file. When the system is running you can save logs in the file and review them for error checks and maintenance purposes. You can also set a file to save all the log entries in legzero.

大多數時候,Python用戶傾向于在文件中寫入日志。 當系統運行時,您可以將日志保存在文件中,并檢查它們以進行錯誤檢查和維護。 您還可以設置文件以將所有日志條目保存在legzero中。

We will import the logger and logfile from logezero. The logfile method will help us configure the log file to save our log entries.

我們將從logezero導入記錄器和日志文件。 logfile方法將幫助我們配置日志文件以保存日志條目。

Now your log entries will be logged into the file named my_logfile.log.

現在,您的日志條目將被記錄到名為my_logfile.log的文件中。

#import logger and logfile
from logzero import logger, logfile#set logfile path
logfile('my_logfile.log')# Log messages
logger.info("This log message saved in the log file")

The output in the my_logfile.log contains the logging level label (for info level labeled as “I”), date, time, python filename, line number and the message itself.

my_logfile.log中的輸出包含日志記錄級別標簽(對于信息級別標記為“ I”),日期,時間,python文件名,行號和消息本身。

[I 200409 23:49:59 demo:8] This log message saved in the log file

旋轉日志文件 (Rotating a log file)

You don't need to have a single log file saving all the log entries. This results in a massive log file that is intensive for the system to open and close.

您無需保存所有日志條目的單個日志文件。 這將導致大量的日志文件,這對于系統打開和關閉而言非常耗時。

You can use the maxBytes and backupCount parameters to allow the file to roll over at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearly maxBytes in length. If either maxBytes or backupCount is zero, rollover never occurs.

您可以使用maxBytesbackupCount參數來允許文件以預定大小滾動。 當將要超過該大小時,將關閉文件,并以靜默方式打開一個新文件以進行輸出。 只要當前日志文件的長度接近maxBytes,就會發生翻轉。 如果maxBytes或backupCount為零,則永遠不會發生過渡。

In the example below, we have set the maxBytes to be 1000000 bytes (1 MB). This means that when the size exceeds 1MB the file is closed and a new file is opened to save log entries. The number of backups to keep is set to 3.

在下面的示例中,我們將maxBytes設置為1000000字節(1 MB)。 這意味著,當大小超過1MB時,將關閉文件并打開一個新文件以保存日志條目。 要保留的備份數設置為3。

# Set a rotating logfile
logzero.logfile("my_logfile.log", maxBytes=1000000, backupCount=3)

設置最低日志記錄級別 (Set a Minimum Logging Level)

The logging level means to set the importance level of a given log message. You can also set a different log level for the file handler by using the loglevel argument in the logfile method.

日志記錄級別是指設置給定日志消息的重要性級別。 您還可以通過使用logfile方法中的loglevel參數為文件處理程序設置不同的日志級別

In the example below, we set loglevel to be warning. This means all log entries below the warning level will not be saved into a log file.

在下面的示例中,我們將loglevel設置為warning 。 這意味著低于警告級別的所有日志條目都不會保存到日志文件中。

#import logzero package
from logzero import logger, logfile
import logging# You can also set a different loglevel for the file handler
logfile("my_logfile.log", loglevel=logging.WARNING)# Log messages
logger.info("This log message saved in the log file")
logger.warning("This log message saved in the log file")

設置自定義格式器 (Set a custom formatter)

How you want the log record to be formated is up to you. There are different ways you can format your log record. You can include the date, time and logging level in your format so that you know when the log was sent and at what level.

您希望如何格式化日志記錄取決于您自己。 您可以使用多種方式來格式化日志記錄。 您可以采用格式包括日期,時間和日志記錄級別,以便您知道何時發送日志以及處于什么級別。

The example below shows how you can configure the format of the log records.

下面的示例顯示如何配置日志記錄的格式。

#import logzero package
import logzero
from logzero import logger, logfile
import logging#set file path
logfile("my_logfile.log")# Set a custom formatter
my_formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s: %(message)s');
logzero.formatter(my_formatter)# Log messages
logger.info("This log message saved in the log file")
logger.warning("This log message saved in the log file")

In the example above we have configured the log format by including filename, date, time, logging level name, and message.

在上面的示例中,我們通過包括文件名,日期,時間,日志記錄級別名稱消息來配置日志格式

This is the output in the my_logfile.log:

這是my_logfile.log中的輸出:

demo.py - 2020–04–10 00:51:44,706 - INFO: This log message saved in the log file
demo.py - 2020–04–10 00:51:44,707 - WARNING: This log message saved in the log file

自定義記錄器實例 (Custom Logger Instances)

Instead of using the default logger, you can also setup specific logger instances with logzero.setup_logger(..). You can configure and returns a fully configured logger instance with different parameters such as name, logfile name, formatter, maxBytes, backupCount, and logging level.

除了使用默認記錄器之外,您還可以使用logzero.setup_logger(..)設置特定的記錄器實例。 您可以使用不同的參數(例如名稱,日志文件名稱,格式化程序,maxBytes,backupCount日志記錄級別)配置并返回完全配置的記錄器實例

This is a working example of how to setup logging with a custom logger instance:

這是一個如何使用自定義日志記錄器實例設置日志記錄的有效示例:

import logzero package
from logzero import logger, logfile, setup_logger
import logging# Set a custom formatter
my_formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s: %(message)s');#create custom logger instance
custom_logger = setup_logger(name="My Custom Logger",logfile="my_logfile.log",formatter=my_formatter,maxBytes=1000000,backupCount=3,level=logging.INFO)# Log messages
custom_logger.info("This log message saved in the log file")
custom_logger.warning("This log message saved in the log file")

In the example above we have set a custom logger instance called custom_logger with different configured parameter values.

在上面的示例中,我們使用不同的配置參數值設置了一個名為custom_logger的自定義記錄器實例。

結語 (Wrap up)

In this article, you've learned the basics, along with some examples, of how to use the Logezero Python package. You can learn more about the features available in the documentation. Now you can start implementing the logzero package in your next python project.

在本文中,您學習了如何使用Logezero Python軟件包的基礎知識和一些示例。 您可以在文檔中了解更多有關可用功能的信息 。 現在,您可以在下一個python項目中開始實現logzero包。

If you learned something new or enjoyed reading this article, please share it so that others can see it. Until then, see you in the next post! I can also be reached on Twitter @Davis_McDavid

如果您學習了新知識或喜歡閱讀本文,請與他人分享,以便其他人可以看到。 在那之前,在下一篇文章中見! 也可以通過Twitter @Davis_McDavid與我聯系

翻譯自: https://www.freecodecamp.org/news/good-logging-practice-in-python-with-logzero/

python練習

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390434.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390434.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390434.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

1736. 替換隱藏數字得到的最晚時間

給你一個字符串 time ,格式為 hh:mm(小時:分鐘),其中某幾位數字被隱藏(用 ? 表示)。 有效的時間為 00:00 到 23:59 之間的所有時間,包括 00:00 和 23:59 。 替換 time 中隱藏的數…

電腦棒安裝linux_為什么要使用Linux? Linux很棒的11個理由

電腦棒安裝linuxIn this article, well look at some of the things developers love about Linux so you can decide if its right for you.在本文中,我們將研究開發人員對Linux的一些喜愛,以便您可以確定它是否適合您。 持續有效的改進。 (Constant a…

1743. 從相鄰元素對還原數組

存在一個由 n 個不同元素組成的整數數組 nums ,但你已經記不清具體內容。好在你還記得 nums 中的每一對相鄰元素。 給你一個二維整數數組 adjacentPairs ,大小為 n - 1 ,其中每個 adjacentPairs[i] [ui, vi] 表示元素 ui 和 vi 在 nums 中相…

十 web爬蟲講解2—Scrapy框架爬蟲—Scrapy安裝—Scrapy指令

Scrapy框架安裝 1、首先,終端執行命令升級pip: python -m pip install --upgrade pip2、安裝,wheel(建議網絡安裝) pip install wheel3、安裝,lxml(建議下載安裝)4、安裝,Twisted(建議下載安裝)5、安裝,Scrapy(建議網絡…

阿里與珠海橫琴新區達成戰略合作,阿里云助力打造橫琴智能島

5月17日,阿里巴巴集團、螞蟻金服集團與珠海橫琴新區管理委員會簽署戰略合作協議,三方將圍繞云計算、政務民生服務、城市治理、電子商務等領域展開深入合作,推動橫琴產業發展,共同建設新型智慧城市。 (阿里巴巴集團、螞…

chrome 開發工具_我最喜歡的Chrome開發工具提示和技巧

chrome 開發工具Chrome Developer Tools are a super powerful suite of tools for developing web applications. They can do so much, from very basic operations like traversing the DOM, to checking out network requests or even profiling your applications perform…

三十四 Python分布式爬蟲打造搜索引擎Scrapy精講—scrapy信號詳解

信號一般使用信號分發器dispatcher.connect(),來設置信號,和信號觸發函數,當捕獲到信號時執行一個函數 dispatcher.connect()信號分發器,第一個參數信號觸發函數,第二個參數是觸發信號, 以下是各種信號 sig…

1713. 得到子序列的最少操作次數

給你一個數組 target ,包含若干 互不相同 的整數,以及另一個整數數組 arr ,arr 可能 包含重復元素。 每一次操作中,你可以在 arr 的任意位置插入任一整數。比方說,如果 arr [1,4,1,2] ,那么你可以在中間添…

CVE-2018-1000136:Electron nodeIntegration繞過漏洞

1周前,研究人員發現一個影響Electron所有版本的漏洞,利用該漏洞可以開啟nodeIntegration,這可能會造成遠程代碼執行。Electron是一個使用JavaScript,HTML和CSS等Web技術創建原生程序的框架,它負責比較難搞的部分,而用戶…

bash腳本 文件_如何使用Bash腳本來管理從AWS S3存儲桶下載和查看文件

bash腳本 文件As you can read in this article, I recently had some trouble with my email server and decided to outsource email administration to Amazons Simple Email Service (SES). 正如您在本文中所讀到的 ,最近我的電子郵件服務器遇到了一些麻煩&…

rsync(六)命令中文手冊

rsync(1) rsync(1)名稱rsync - 一個快速、多功能的遠程(和本地)文件拷貝工具摘要Local: rsync [OPTION...] SRC... [DEST]Access via remote shell:Pull: rsync [OPTION...] [USE…

NFS共享存儲服務部署

服務端部署 1、檢查服務器上是否已安裝nfs及rpc,沒有則需要安裝檢查rpm -qa rpcbind nfs-utils安裝(已安裝略過)yum install -y rpcbind nfs-utils################################################################2、編寫nfs的配置文件cat…

區塊鏈運作機制_什么是區塊鏈及其運作方式?

區塊鏈運作機制If youre interested in technology, theres a good chance you’ve probably heard the terms Bitcoin, Crypto, Ethereum, or even "distributed, decentralized ledgers."如果您對技術感興趣,那么您很有可能已經聽說過比特幣&#xff0c…

敏捷管理之績效考核方案

前段時間,公司簽了年終獎確認。覺得公司發放年終獎完全是憑主觀發放,沒有事實依據,由此產生了對如何發放年終獎的一些想法。 獎金發放作為激勵員工最直接的手段,往往也是讓管理人員最難抉擇的,而且很多公司&#xff0c…

序言

為什么要寫這篇文章? 說起架構,剛入行的新人覺得是高大上的技術,有工作經驗的一些人又覺得是虛無縹緲的東西,不能落實。具體有用沒用,我不給答案,想通過寫這么一個例子來還原場景,讓讀者自己判斷…

kotlin編程語言_Kotlin初學者編程基礎

kotlin編程語言什么是Kotlin? (What is Kotlin?) Kotlin is a programming language developed by Jetbrains, the company behind some of the world’s most popular IDEs like IntelliJ and Pycharm.Kotlin是Jetbrains開發的一種編程語言,該公司是In…

記一個蒟蒻的絕望

感覺現在…… 怎么講,心挺冷的。 今天一月五號了。距離省選,時間好短啊。 我還有那么多東西不懂。甚至聽都沒聽說過。 等到真正去省選的時候,我可能跟現在一樣,什么都不會。 我的名字能不能被看到都不知道。哈,還進隊呢…

671. 二叉樹中第二小的節點

給定一個非空特殊的二叉樹,每個節點都是正數,并且每個節點的子節點數量只能為 2 或 0。如果一個節點有兩個子節點的話,那么該節點的值等于兩個子節點中較小的一個。 更正式地說,root.val min(root.left.val, root.right.val) 總…

CentOS查詢端口占用和清除端口占用的程序

1、查詢端口號占用,根據端口查看進程信息 [rootserver2 ~]# lsof -i:80COMMAND PID USER FD TYPE DEVICE SIZE NODE NAMEhttpd 5014 root 3u IPv4 14346 TCP server2:http (LISTEN)2、根據進程號查看進程對應的可執行程序 ps -f -p 進程號# p…

Android基礎夯實--你了解Handler有多少?

概述 對于剛入門的同學來說,往往都會對Handler比較迷茫,到底Handler是個什么樣的東西。當然,可能對于一些有工作經驗的工程師來說,他們也不一定能很準確地描述,我們來看下API的介紹。 Handler是用來結合線程的消息隊列…