Add encoding parameter to logging.basicConfig

2019-04-07 08:10发布

How do I add an encoding parameter to logging.basicConfig?

I have found this bug report that states that this is now possible for Python 3.3. I need this for Python 2.7 and the bug report says to use a custom logging.FileHandler object, but I can't get it to work.

2条回答
闹够了就滚
2楼-- · 2019-04-07 08:22

It will be easier to avoid using basicConfig() in your case - just create the handler and add it programmatically (ensuring that the code runs just once), e.g.:

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

That's more or less what basicConfig() does.

查看更多
\"骚年 ilove
3楼-- · 2019-04-07 08:33

Vinay's response was very helpful, but to get it working I had to tweak the syntax:

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)
查看更多
登录 后发表回答