Python日志记录仅来自脚本的日志 [英] Python logging only log from script

查看:103
本文介绍了Python日志记录仅来自脚本的日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我的简单脚本中的Python日志记录模块,此刻具有以下设置.

I'm using the Python logging module in a simple script of mine with the following setup at the moment.

logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)

我的问题是,这还会捕获诸如请求之类的第三方模块,并从中获取输出info()日志消息.有什么方法可以抑制这些消息或告诉日志记录模块仅记录来自我自己的脚本的消息?

My problem is that this also catches 3rd party modules like requests and output info() log messages from them. Is there any way to suppress these messages or tell the logging module only to log messages from my own script?

推荐答案

上面的答案并不正确-它将只是将显示其他模块消息的阈值设置得更高.

The above answer is not really correct - it will just set the bar higher for messages from other modules to be shown.

一种非常快速的方法是使用这段代码:

A very quick approach would be to use this piece of code:

import logging.config
logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': True,
})

您必须在导入所有模块后进行设置-这将禁用到此为止创建的所有记录器.这在大多数情况下都会起作用,但是例如,当您创建类实例时,某些模块会创建其记录器(稍后会在代码中发生).

You have to set this after importing all modules - it will disable all loggers that were created up to this point. This will work most of the time, but some modules create their logger when you make a class instance for example (which would happen later in your code).

当您根据基本的python教程设置记录器时,它们会告诉您使用logging.basicConfig(...).这是一个问题,因为这会将处理程序(也称为日志将被路由到的处理程序)设置为logging.lastResort,这是从Python 3.2开始的stderr,用于该过程中全局 all 记录器.这意味着您现在已经为所有模块启用了完整日志记录.

When you set up loggers according to the basic python tutorial they tell you to use logging.basicConfig(...). This is a problem as this will set the handler (aka where the log will be routed to) to logging.lastResort which is stderr starting with Python 3.2 for all loggers globally in the process. This means you now have enabled full logging for all modules.

因此,更好的方法是只为您的模块创建一个不同的记录器,并为其提供一些自己的处理程序,而不是使用basicConfig().

So a better approach is to create a different logger only for your modules and give it some handlers of its own instead of using basicConfig().

有两种方法可以做到这一点:

There are two ways of doing that:

1)所有功能:

import logging

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s: %(message)s", 
                          datefmt="%Y-%m-%d - %H:%M:%S")
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
fh = logging.FileHandler("mylog.log", "w")
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(ch)
log.addHandler(fh)

这将为您提供记录器log,您可以像log.error("Error found")一样使用它.它将写入名为mylog.log的新文件,并也将其记录为sys.stdout.您当然可以随意更改.

This will give you the logger log that you can then use like log.error("Error found"). It will write to a new file called mylog.log and will also log so sys.stdout. You can change this as you like of course.

2)使用字典:

import logging
import logging.config

DEFAULT_LOGGING = {
    'version': 1,
    'formatters': { 
        'standard': {
            'format': '%(asctime)s %(levelname)s: %(message)s',
            'datefmt': '%Y-%m-%d - %H:%M:%S' },
    },
    'handlers': {
        'console':  {'class': 'logging.StreamHandler', 
                     'formatter': "standard", 
                     'level': 'DEBUG', 
                     'stream': sys.stdout},
        'file':     {'class': 'logging.FileHandler', 
                     'formatter': "standard", 
                     'level': 'DEBUG', 
                     'filename': 'live_detector.log','mode': 'w'} 
    },
    'loggers': { 
        __name__:   {'level': 'INFO', 
                     'handlers': ['console', 'file'], 
                     'propagate': False },
    }
}

logging.config.dictConfig(DEFAULT_LOGGING)
log = logging.getLogger(__name__)

这将获得与上述相同的结果,但会更长一些,但可能更易于阅读.这还将自动设置'disable_existing_loggers': True.如果您不希望这样做,则必须添加它并将其设置为False.

This will give the same result as the above, a bit longer, but maybe easier to read. This will automatically also set 'disable_existing_loggers': True. If you do not want that, you have to add it and set it to False.

这篇关于Python日志记录仅来自脚本的日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆