Python 将编码参数添加到logging.basicConfig

Python 将编码参数添加到logging.basicConfig,python,logging,Python,Logging,如何将编码参数添加到 我发现,这说明现在对于Python3.3是可能的。对于Python 2.7,我需要这个,错误报告说要使用自定义对象,但我无法让它工作。在您的情况下,避免使用basicConfig()会更容易-只需创建处理程序并以编程方式添加它(确保代码只运行一次),例如: 这或多或少就是basicConfig()所做的 更新:从Python 3.9(仍在开发中)开始,basicConfig()应该有编码和错误关键字可用。Vinay的回答非常有帮助,但为了让它工作,我必须调整语法: root

如何将
编码
参数添加到


我发现,这说明现在对于Python3.3是可能的。对于Python 2.7,我需要这个,错误报告说要使用自定义对象,但我无法让它工作。

在您的情况下,避免使用
basicConfig()
会更容易-只需创建处理程序并以编程方式添加它(确保代码只运行一次),例如:

这或多或少就是
basicConfig()
所做的


更新:从Python 3.9(仍在开发中)开始,
basicConfig()
应该有
编码
错误
关键字可用。

Vinay的回答非常有帮助,但为了让它工作,我必须调整语法:

root_logger= logging.getLogger()
root_logger.setLevel(logging.DEBUG) # or whatever
handler = logging.FileHandler('test.log', 'w', 'utf-8') # or whatever
formatter = logging.Formatter('%(name)s %(message)s') # or whatever
handler.setFormatter(formatter) # Pass handler as a parameter, not assign
root_logger.addHandler(handler)

您可以传递特定文件处理程序的列表:

import logging

logging.basicConfig(handlers=[logging.FileHandler(filename="./log_records.txt", 
                                                 encoding='utf-8', mode='a+')],
                    format="%(asctime)s %(name)s:%(levelname)s:%(message)s", 
                    datefmt="%F %A %T", 
                    level=logging.INFO)

而且它工作得很好(python版本==Python3.6.8::Anaconda,Inc.)

它不是
handler.setFormatter(logging.Formatter('%(name)s%(message)s'))
import logging

logging.basicConfig(handlers=[logging.FileHandler(filename="./log_records.txt", 
                                                 encoding='utf-8', mode='a+')],
                    format="%(asctime)s %(name)s:%(levelname)s:%(message)s", 
                    datefmt="%F %A %T", 
                    level=logging.INFO)