python:logging模塊(記錄打印日誌)

logging.basicConfig(**kwargs):建立默認處理器從而將調試消息寫至文件,它接受一個字典python

filename:指定文件名,把記錄輸出定向的文件裏面,若是不指定文件名就會直接打印到屏幕上多線程

filemode:指打開文件的模式(默認爲a)ide

format:指定的字符串格式spa

datefmt:指定日期格式線程

level:指定日誌的級別debug

級別 含義
CRITICAL,FATAL 50 臨界
ERROR 40 錯誤
WARNING,WARN 30 警告
INFO 20 通知
DEBUG 10 調試

#coding:utf-8
import logging
logging.basicConfig(level = logging.INFO)#定義日誌級別爲INFO級別
#下面是定義各個級別的日誌輸出
logging.debug('I am debug')     
logging.info('I am info')
logging.warn('I am warning')
logging.error('I am error')
logging.critical('I am critical')
######運行結果######
>>> INFO:root:I am info
WARNING:root:I am warning
ERROR:root:I am error
CRITICAL:root:I am critical
因爲定義的日誌級別是INFO,而debug級別的值只有10,而INFO的是20
全部不會打印出來,只打印大於INFO值的日誌記錄
通常我調試程序都是直接打印在屏幕的因此就沒輸出到文件了

logging模塊還支持將線程名嵌入到各個日誌消息中調試

下面寫個利用logging模塊調試多線程的例子:日誌

#coding:utf-8
import threading
import time
import logging
logging.basicConfig(level = logging.DEBUG,
format ='[%(levelname)8s]\t (%(threadName)10s)\t %(message)30s')
def worker():
    #logging的日誌格式必須是字符型,不接受float和int
    logging.debug('worker start:%s'%time.time())
    time.sleep(2)
    logging.debug('worker done:%s'%time.time())
          
def saihi():
    logging.debug('saihi start:%s'%time.time())
    time.sleep(2)
    worker()
    logging.debug('saihi done:%s'%time.time())
          
t = threading.Thread(target = saihi, name = 't')
x = threading.Thread(target = worker, name = 'x')
w = threading.Thread(target = worker)
t.start()
x.start()
w.start()
#####運行結果#####
[   DEBUG]   (         t)       saihi start:1374939516.13
[   DEBUG]   (         x)      worker start:1374939516.13
[   DEBUG]   (  Thread-1)      worker start:1374939516.13
[   DEBUG]   (         t)      worker start:1374939518.13
[   DEBUG]   (  Thread-1)       worker done:1374939518.13
[   DEBUG]   (         x)       worker done:1374939518.13
[   DEBUG]   (         t)       worker done:1374939520.13
[   DEBUG]   (         t)        saihi done:1374939520.13
相關文章
相關標籤/搜索