更改已设置的日志记录'basicConfig'

Abh*_*ogi 30 python logging

我在python中使用日志记录模块:

import logging, sys
logger= logging.getLogger(__file__)
logging.basicConfig(stream = sys.stderr, level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s')
logger.debug("Hello World")
Run Code Online (Sandbox Code Playgroud)

现在,在我设置了基本配置之后line 3,我希望有一个命令行参数,可以将输出流从sys.stderr更改为文件.

我已经阅读了文档,它说如果两者filename同时stream存在,那么它stream就会被忽略.

现在,我想知道怎么流更改到文件后,我已经做了basicConfig的事line 3

Aus*_*ips 55

如果您查看Python源代码logging/__init__.py,您将看到basicConfig()通过调用在根记录器对象上设置处理程序addHandler().如果您想从头开始,可以删除所有现有的处理程序,然后basicConfig()再次调用.

# Example to remove all root logger handlers and reconfigure. (UNTESTED)
import logging

# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

# Reconfigure logging again, this time with a file.
logging.basicConfig(filename = 'myfile.log', level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s')
Run Code Online (Sandbox Code Playgroud)

  • @KevinGuan列表理解用于构建列表.如果要在循环中运行语句,请使用循环. (26认同)
  • 从 Python 3.8 开始,“basicConfig”现在接受 [``force``](https://docs.python.org/3.8/library/logging.html?highlight=logging#logging.basicConfig) 参数来删除现有的根处理程序。 (6认同)
  • @Spack,你是说我们可以删除上面的第 5+6 行并将第 9 行设置为类似 `logging.basicConfig(filename='myfile.log', ..., force = True)` ? (4认同)

Ath*_*oud 15

他的评论归属于Spack。我只是在正确的答案中扩展这个想法

在2022年,使用Python 3.8,我们可以使用方法force的输入basicConfig

根据 Python文档

力量

如果此关键字参数指定为 true,则在执行其他参数指定的配置之前,将删除并关闭附加到根记录器的任何现有处理程序。

基于OP代码示例,只需添加以下行

logging.basicConfig(filename = 'my_file.log', level = logging.DEBUG, format = '%(filename)s:%(lineno)s %(levelname)s:%(message)s', force = True)
Run Code Online (Sandbox Code Playgroud)