![图片[1]-python如何打印日志-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5d69e2820987b852.jpg)
默认情况下,python使用logging模块将日志打印到屏幕上(stdout),日志级别为WARNING(即只有日志级别高于WARNING的日志信息才会输出),日志格式如下图所示:

简单使用
#!/usr/local/bin/python#-*-coding:utf-8-*-importlogging
logging.debug('debugmessage')
logging.info('infomessage')
logging.warn('warnmessage')
logging.error('errormessage')
logging.critical('criticalmessage')
输出
WARNING:root:warnmessage ERROR:root:errormessage CRITICAL:root:criticalmessage
通过logging.basicConfig函数对日志的输出格式及方式做相关配置。logging.basicConfig(**kwargs) 该函数必须在main函数线程除外的子线程启动之前调用,否则可能会造成日志重复记录
importlogging
fmt='%(asctime)s%(filename)s[line:%(lineno)d]%(levelname)s:%(message)s'
logging.basicConfig(level=logging.DEBUG,
format=fmt,
filename='D:\Python\logs.txt',
filemode='w',
datefmt='%a,%d%b%Y%H:%M:%S'
)
logging.debug('thisisadebuglevelmessage')
logging.info("thisisainfolevelmessage")
logging.warning("thisisawarninglevelmessage")
logging.error("thisisaerrorlevelmessage")
logging.critical("thisisacriticallevelmessage")
filename:创建一个FileHandler,使用指定的文件名,而不是使用StreamHandler。
filemode:如果指明了文件名,指明打开文件的模式(如果没有指明filemode,默认为'a')。
format:handler使用指明的格式化字符串。
原文来自:https://www.py.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容