Add encoding parameter to logging.basicConfig
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.
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)
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.)