python中如何用logging把日志输出到文件和控制台?

1,886次阅读
没有评论

python中如何用logging把日志输出到文件和控制台?

还记得小编小时候,发生什么事情,遇到什么委屈或者高兴的事情,喜欢写在QQ日志中表达自己的情绪。虽然QQ日志现在已经不使用,但是日志的作用还在发挥。在计算机里,我们可以日志里记录自己的日常琐事或者是写的代码。那你知道如和将写好的日志输出到文件和控制台,便于我们存储使用吗?本文小编将简单向大家介绍python中通用的日志系统logging模块,并向大家演示用logging模块把日志输出到文件和控制台的过程。

1、python的logging模块

python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。

2、logging模块基本使用

import logging
logging.basicConfig()
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

3、将日志输出到文件和控制台

import logging
LOG_FILE = 'mylog.log'
file_handler = logging.FileHandler(LOG_FILE) #输出到文件
console_handler = logging.StreamHandler()  #输出到控制台
file_handler.setLevel('ERROR')     #error以上才输出到文件
console_handler.setLevel('INFO')   #info以上才输出到控制台
fmt = '%(asctime)s - %(funcName)s - %(lineno)s - %(levelname)s - %(message)s'  
formatter = logging.Formatter(fmt) 
file_handler.setFormatter(formatter) #设置输出内容的格式
console_handler.setFormatter(formatter)
logger = logging.getLogger('updateSecurity')
logger.setLevel('DEBUG')     #设置了这个才会把debug以上的输出到控制台
logger.addHandler(file_handler)    #添加handler
logger.addHandler(console_handler)

以上就是对python的logging模块的介绍和用logging模块把日志输出到文件和控制台的过程,希望能对你有所帮助哦~

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-16发表,共计1245字。
新手QQ群:570568346,欢迎进群讨论 Python51学习