这篇文章介绍了 Python 的 logging 模块。
![图片[1]-python怎么记录日志-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5d69dc4eacbdf494.jpg)
为什么使用 logging 模块?
也许会有开发者会问,为什么不是简单的 print 语句呢? Logging 模块有很多优势,包括:
多线程支持
通过不同级别的日志分类
灵活性和可配置性
将如何记录日志与记录什么内容分离
最后一点,将我们记录内容从记录方式中真正分离,保证了软件不同部分的合作。举个例子,它允许一个框架或库的开发者增加日志并且让系统管理员或负责运行配置的人员决定稍后应该记录什么。
使用起来还是很方便的。
#!/usr/bin/envpython
#-*-coding:utf-8-*-
importlogging
#createalogfile
logger=logging.getLogger('atp_log')
logger.setLevel(logging.DEBUG)
#createahandler,writetheloginfointoit
fh=logging.FileHandler('atp.log')
fh.setLevel(logging.DEBUG)
#createanotherhandleroutputthelogthoughconsole
ch=logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#定义handler的输出格式
formatter=logging.Formatter('%(asctime)s-%(levelname)s-%(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
#给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)
#记录一条日志
logger.info('foorbar')
logger.error('foorbar')
之后,我们队logger输入info warning或者error都可以,而且会被记录在日志文件里面。当然,上面的代码中,我们在设置
fh=logging.FileHandler('atp.log')
这个文件的logger也创建了一个从console的日志显示的地方。
ch=logging.StreamHandler()
之后,我们就可以看到在文件和console中都会有相应的信息出现。
原文来自:https://www.py.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容