本系列文章來源:<a>https://blog.ansheng.me/article/python-full-stack-way</a>
logging模塊用于便捷記錄日志且線程安全。
日志級(jí)別
等級(jí) 數(shù)值
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0
只有大于當(dāng)前日志等級(jí)的操作才會(huì)被記錄母蛛。
實(shí)例
寫入單文件
代碼
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# 導(dǎo)入logging模塊
import logging
# 創(chuàng)建一個(gè)log.log日志文件
logging.basicConfig(filename='log.log',
# 格式化的字符串
format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
# 時(shí)間
datefmt='%Y-%m-%d %H:%M:%S %p',
# 錯(cuò)誤級(jí)別
level=logging.NOTSET
)
logging.critical('critical')
logging.error('error')
logging.warning('warning')
logging.info('info')
logging.debug('debug')
logging.log(logging.INFO, 'NOTSET')
執(zhí)行結(jié)果:
[root@wangerxiao tmp]# python s.py
生成報(bào)錯(cuò)日志文件log.log
[root@wangerxiao tmp]# cat log.log
2017-06-02 14:51:53 PM - root - CRITICAL - s: critical
2017-06-02 14:51:53 PM - root - ERROR - s: error
2017-06-02 14:51:53 PM - root - WARNING - s: warning
2017-06-02 14:51:53 PM - root - INFO - s: info
2017-06-02 14:51:53 PM - root - DEBUG - s: debug
2017-06-02 14:51:53 PM - root - INFO - s: NOTSET
logging.basicConfig函數(shù)各參數(shù)
參數(shù) 說明
filename 指定日志文件名
filemode 和file函數(shù)意義相同,指定日志文件的打開模式刹淌,'w'或'a'
format 指定輸出的格式和內(nèi)容,format可以輸出很多有用的信息讥耗,如下所示
datefmt 指定時(shí)間格式有勾,同time.strftime()
level 設(shè)置日志級(jí)別,默認(rèn)為logging.WARNING
format參數(shù)
參數(shù) 說明
%(levelno)s 打印日志級(jí)別的數(shù)值
%(levelname)s 打印日志級(jí)別名稱
%(pathname)s 打印當(dāng)前執(zhí)行程序的路徑葛账,其實(shí)就是sys.argv[0]
%(filename)s 打印當(dāng)前執(zhí)行程序名
%(funcName)s 打印日志的當(dāng)前函數(shù)
%(lineno)d 打印日志的當(dāng)前行號(hào)
%(asctime)s 打印日志的時(shí)間
%(thread)d 打印線程ID
%(threadName)s 打印線程名稱
%(process)d 打印進(jìn)程ID
%(message)s 打印日志信息
多文件日志
對(duì)于上述記錄日志的功能柠衅,只能將日志記錄在單文件中,如果想要設(shè)置多個(gè)日志文件籍琳,logging.basicConfig將無法完成菲宴,需要自定義文件和日志操作對(duì)象。
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import logging
# 創(chuàng)建文件
file_1 = logging.FileHandler("log1.log", "a")
# 創(chuàng)建寫入的日志格式
fmt1 = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(message)s")
# 文件用格式
file_1.setFormatter(fmt1)
file_2 = logging.FileHandler("log2.log", "a")
fmt2 = logging.Formatter()
file_2.setFormatter(fmt2)
logger1 = logging.Logger("s1", level=logging.ERROR)
logger1.addHandler(file_1)
logger1.addHandler(file_2)
logger1.critical("1111")
# 定義文件
file_2_1 = logging.FileHandler('l2_1.log', 'a')
fmt = logging.Formatter()
file_2_1.setFormatter(fmt)
# 定義日志
logger2 = logging.Logger('s2', level=logging.INFO)
logger2.addHandler(file_2_1)
如上述創(chuàng)建的兩個(gè)日志對(duì)象
1.當(dāng)使用logger1寫日志時(shí)趋急,會(huì)將相應(yīng)的內(nèi)容寫入 l1_1.log 和 l1_2.log 文件中
2.當(dāng)使用logger2寫日志時(shí)喝峦,會(huì)將相應(yīng)的內(nèi)容寫入 l2_1.log 文件中