python:logging模块(记录打

2020-01-08 15:50:42 浏览数 (1)

logging.basicConfig(**kwargs):创建默认处理器从而将调试消息写至文件,它接受一个字典

filename:指定文件名,把记录输出定向的文件里面,如果不指定文件名就会直接打印到屏幕上

filemode:指打开文件的模式(默认为a)

format:指定的字符串格式

datefmt:指定日期格式

level:指定日志的级别

级别

含义

CRITICAL,FATAL

50

临界

ERROR

40

错误

WARNING,WARN

30

警告

INFO

20

通知

DEBUG

10

调试

代码语言:javascript复制
#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模块调试多线程的例子:

代码语言:javascript复制
#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

0 人点赞