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), 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.
Update: In Python 3.9 and later versions, basicConfig() has encoding and errors keyword parameters 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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With