python中l(wèi)ogging包的使用總結(jié)
1.logging 簡介
Python的logging package提供了通用的日志系統(tǒng),可以方便第三方模塊或者是應(yīng)用使用。這個(gè)模塊提供不同的日志級(jí)別,并可以采用不同的方式記錄日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己實(shí)現(xiàn)具體的日志記錄方式。
logging包中定義了Logger、Formatter、Handler和Filter等重要的類,除此之外還有config模塊。
Logger是日志對(duì)象,直接提供日志記錄操作的接口
Formatter定義日志的記錄格式及內(nèi)容
Handler定義日志寫入的目的地,你可以把日志保存成本地文件,也可以每個(gè)小時(shí)寫一個(gè)日志文件,還可以把日志通過socket傳到別的機(jī)器上。python提供了十幾種實(shí)用handler,比較常用的有StreamHandler,BaseRotatingHandler,SocketHandler,DatagramHandler,SMTPHandler等。我們可以通過Logger對(duì)象的addHandler()方法,將log輸出到多個(gè)目的地。
2.Logging package
在python編程中,引入了Logging package,那么可以存在一個(gè)名稱為root的Logging對(duì)象,以及很多其他名稱的Logging對(duì)象。不同的Logger對(duì)象的Handler,F(xiàn)ormatter等是分開設(shè)置的。
(1)logging.getLogger() 如果getLogging中不帶參數(shù),那么返回的是名稱為root的Logger對(duì)象,如果帶參數(shù),那么就以該參數(shù)為名稱的Logger對(duì)象。同名稱的Logger對(duì)象是一樣的。
(2)logging.basicConfig() 此方法是為名稱為root的Logger對(duì)象進(jìn)行配置。
(3)logging.info() logging.debug()等,使用的root Logger對(duì)象進(jìn)行信息輸出。如果是用其他的Logging對(duì)象進(jìn)行l(wèi)og輸出,可以使用Logging.getLogger(name).info()來實(shí)現(xiàn)。
(4)日志的等級(jí)
CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0
在python中有0,10,20,30,40,50這6個(gè)等級(jí)數(shù)值,這6個(gè)等級(jí)數(shù)值分別對(duì)應(yīng)了一個(gè)字符串常量,作為等級(jí)名稱,如上。但是可以通過logging.addLevelName(20, "NOTICE:")這個(gè)方法來改變這個(gè)映射關(guān)系,來定制化日志等級(jí)名稱。
通過Logger對(duì)象的setLevel()方法,可以配置Logging對(duì)象的默認(rèn)日志等級(jí),只有當(dāng)一條日志的等級(jí)大于等于這個(gè)默認(rèn)的等級(jí),才會(huì)輸出到log文件中。
當(dāng)使用logging.info(msg)輸出log時(shí),內(nèi)部封裝會(huì)用數(shù)字20作為日志等級(jí)數(shù)值,默認(rèn)情況下20對(duì)應(yīng)的是INFO,但如果通過addLevelName()修改了20對(duì)應(yīng)的等級(jí)名稱,那么log中打印的就將是個(gè)性化的等級(jí)名稱。
3.logging包使用配置文件
在1~2中描述的,對(duì)一個(gè)Logger對(duì)象的Handler,F(xiàn)ormatter等都是在程序中定義或綁定的。而實(shí)際上Logging的個(gè)性化的配置可以放到配置文件中。
logging的配置文件舉例如下:
[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=
對(duì)應(yīng)程序?yàn)椋?/p>
import logging
import logging.config
logging.config.fileConfig("logging.conf") # 采用配置文件
# create logger
logger = logging.getLogger("simpleExample")
# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
4.一個(gè)常用的Logging封裝工具
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#coding=utf-8
import logging
import os
class Logger(object):
"""
封裝好的Logger工具
"""
def __init__(self, logPath):
"""
initial
"""
log_path = logPath
logging.addLevelName(20, "NOTICE:")
logging.addLevelName(30, "WARNING:")
logging.addLevelName(40, "FATAL:")
logging.addLevelName(50, "FATAL:")
logging.basicConfig(level=logging.DEBUG,
format="%(levelname)s %(asctime)s [pid:%(process)s] %(filename)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
filename=log_path,
filemode="a")
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s [pid:%(process)s] %(message)s")
console.setFormatter(formatter)
logging.getLogger("").addHandler(console)
def debug(self, msg=""):
"""
output DEBUG level LOG
"""
logging.debug(str(msg))
def info(self, msg=""):
"""
output INFO level LOG
"""
logging.info(str(msg))
def warning(self, msg=""):
"""
output WARN level LOG
"""
logging.warning(str(msg))
def exception(self, msg=""):
"""
output Exception stack LOG
"""
logging.exception(str(msg))
def error(self, msg=""):
"""
output ERROR level LOG
"""
logging.error(str(msg))
def critical(self, msg=""):
"""
output FATAL level LOG
"""
logging.critical(str(msg))
if __name__ == "__main__":
testlog = Logger("oupput.log")
testlog.info("info....")
testlog.warning("warning....")
testlog.critical("critical....")
try:
lists = []
print lists[1]
except Exception as ex:
"""logging.exception()輸出格式:
FATAL: [pid:7776] execute task failed. the exception as follows:
Traceback (most recent call last):
File "logtool.py", line 86, in <module>
print lists[1]
IndexError: list index out of range
"""
testlog.exception("execute task failed. the exception as follows:")
testlog.info("++++++++++++++++++++++++++++++++++++++++++++++")
"""logging.error()輸出格式:
FATAL: [pid:7776] execute task failed. the exception as follows:
"""
testlog.error("execute task failed. the exception as follows:")
exit(1)
備注:exception()方法能夠完整的打印異常的堆棧信息。error()方法只會(huì)打印參數(shù)傳入的信息。
備注:
按照官方文檔的介紹,logging 是線程安全的,也就是說,在一個(gè)進(jìn)程內(nèi)的多個(gè)線程同時(shí)往同一個(gè)文件寫日志是安全的。但是多個(gè)進(jìn)程往同一個(gè)文件寫日志是不安全的。
- Python內(nèi)置模塊logging用法實(shí)例分析
- 詳解Python自建logging模塊
- Python logging管理不同級(jí)別log打印和存儲(chǔ)實(shí)例
- python使用logging模塊發(fā)送郵件代碼示例
- python logging日志模塊的詳解
- python中 logging的使用詳解
- python中l(wèi)ogging庫的使用總結(jié)
- python中日志logging模塊的性能及多進(jìn)程詳解
- 詳解使用python的logging模塊在stdout輸出的兩種方法
- 詳解Python中l(wèi)ogging日志模塊在多進(jìn)程環(huán)境下的使用
- python logging 日志輪轉(zhuǎn)文件不刪除問題的解決方法
- Python中內(nèi)置的日志模塊logging用法詳解
- Python使用logging結(jié)合decorator模式實(shí)現(xiàn)優(yōu)化日志輸出的方法
相關(guān)文章
Python 12306搶火車票腳本 Python京東搶手機(jī)腳本
這篇文章主要為大家詳細(xì)介紹了Python 12306搶火車票腳本和Python京東搶手機(jī)腳本,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
pycharm 使用心得(八)如何調(diào)用另一文件中的函數(shù)
事件環(huán)境: pycharm 編寫了函數(shù)do() 保存在make.py 如何在另一個(gè)file里調(diào)用do函數(shù)?2014-06-06
python利用腳本輕松實(shí)現(xiàn)ssh免密登陸配置
這篇文章主要為大家詳細(xì)介紹了python如何利用腳本輕松實(shí)現(xiàn)ssh免密登陸配置,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
pytorch 修改預(yù)訓(xùn)練model實(shí)例
今天小編就為大家分享一篇pytorch 修改預(yù)訓(xùn)練model實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
解決python3 整數(shù)數(shù)組轉(zhuǎn)bytes的效率問題
這篇文章主要介紹了解決python3 整數(shù)數(shù)組轉(zhuǎn)bytes的效率問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python實(shí)現(xiàn)Wordcloud生成詞云圖的示例
這篇文章主要介紹了Python實(shí)現(xiàn)Wordcloud生成詞云圖的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
python 遞歸相關(guān)知識(shí)總結(jié)
這篇文章主要介紹了python 遞歸相關(guān)知識(shí)總結(jié),幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-03-03
Python3實(shí)現(xiàn)發(fā)送郵件和發(fā)送短信驗(yàn)證碼功能
這篇文章主要介紹了Python3實(shí)現(xiàn)發(fā)送郵件和發(fā)送短信驗(yàn)證碼功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01

