python 通过logging写入日志到文件和控制台的实例
如下所示:
importlogging
#创建一个logger
logger=logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
#创建一个handler,用于写入日志文件
fh=logging.FileHandler('test.log')
fh.setLevel(logging.DEBUG)
#再创建一个handler,用于输出到控制台
ch=logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#定义handler的输出格式
formatter=logging.Formatter('[%(asctime)s][%(thread)d][%(filename)s][line:%(lineno)d][%(levelname)s]##%(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
#给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)
#记录一条日志
logger.info('foorbar')
关于formatter的配置,采用的是%(
Nameofthelogger(loggingchannel).
Numericlogginglevelforthemessage(
Textlogginglevelforthemessage(
Fullpathnameofthesourcefilewheretheloggingcallwasissued(ifavailable).
Filenameportionofpathname.
Module(nameportionoffilename).
Nameoffunctioncontainingtheloggingcall.
Sourcelinenumberwheretheloggingcallwasissued(ifavailable).
Timewhenthe
TimeinmillisecondswhentheLogRecordwascreated,relativetothetimetheloggingmodulewasloaded.
Human-readabletimewhenthe
Millisecondportionofthetimewhenthe
ThreadID(ifavailable).
Threadname(ifavailable).
ProcessID(ifavailable).
Theloggedmessage,computedas
以上这篇python通过logging写入日志到文件和控制台的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。