加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Python中日志模块Logging模块介绍

发布时间:2021-11-12 15:48:54 所属栏目:教程 来源:互联网
导读:Python中的日志模块,使用使用logging模块,该模块自2.3版本开始便是Python标准库的一部分。 日志的两个目的: 诊断功能: 记录与应用程序操作相关的日志,方便诊断。 审计功能: 为商业分析而记录的日志,具备审计的功能。 日志 vs 打印 当打印显示帮助文档时

Python中的日志模块,使用使用logging模块,该模块自2.3版本开始便是Python标准库的一部分。
 
日志的两个目的:
诊断功能: 记录与应用程序操作相关的日志,方便诊断。
审计功能: 为商业分析而记录的日志,具备审计的功能。
日志 vs 打印
当打印显示帮助文档时,打印无疑是个不错的选择,但是更多情况,都是日志的方式更优秀,原因如下:
 
日志事件产生的日志记录 ,包含清晰可用的诊断信息,如文件名称、路径、函数名和行号等。
包含日志模块的应用,默认可通过根记录器对应用的日志流进行访问,除非你将日志过滤了。
可通过 logging.Logger.setLevel() 方法有选择地记录日志, 或可通过设置logging.Logger.disabled 属性为True来禁用。
配置日志常用的三种方式:
方式一:使用INI格式文件
1. 配置文件config.ini
 
[loggers]
keys=root
 
[handlers]
keys=stream_handler
 
[formatters]
keys=formatter
 
[logger_root]
level=DEBUG
handlers=stream_handler
 
[handler_stream_handler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stderr,)
 
[formatter_formatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
2. 在源码中调用logging.config.fileConfig()方法
 
import logging
from logging.config import fileConfig
 
fileConfig('logging_config.ini')
logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')
3. 打印输出
 
2018-09-15 09:34:37,361 root         DEBUG    often makes a very good meal of visiting tourists
方式二:使用字典或JSON格式文件
import logging
from logging.config import dictConfig
 
logging_config = dict(
    version = 1,
    formatters = {
        'f': {'format':
              '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'}
        },
    handlers = {
        'h': {'class': 'logging.StreamHandler',
              'formatter': 'f',
              'level': logging.DEBUG}
        },
    root = {
        'handlers': ['h'],
        'level': logging.DEBUG,
        },
)
 
dictConfig(logging_config)
 
logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')
方式三:使用源码
import logging
 
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
 
logger.debug('often makes a very good meal of %s', 'visiting tourists')
几种配置文件优缺点比较:
使用INI格式文件:
 
优点: 使用 logging.config.listen() 函数监听socket,可在运行过程中更新配置
缺点: 通过源码控制日志配置较少( 例如 子类化定制的过滤器或记录器)。
使用字典或JSON格式文件:
 
优点: 除了可在运行时动态更新,在Python 2.6之后,还可通过 json 模块从其它文件中导入配置。
缺点: 很难通过源码控制日志配置。
使用源码:
 
优点: 对配置绝对的控制。
缺点: 对配置的更改需要对源码进行修改。

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读