简体   繁体   中英

Add encoding parameter to logging.basicConfig

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.

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), eg:

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.

Update: As of Python 3.9 (still in development), basicConfig() should have encoding and errors keywords available.

You can pass a list of specific file handlers:

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)

and it works pretty well (python version == Python 3.6.8 :: Anaconda, Inc.)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM