Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add encoding parameter to logging.basicConfig

Tags:

python

logging

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.

like image 443
BioGeek Avatar asked May 22 '12 16:05

BioGeek


3 Answers

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.

like image 106
Vinay Sajip Avatar answered Nov 16 '22 16:11

Vinay Sajip


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.)

like image 19
Jesus Gebrial Avatar answered Nov 16 '22 16:11

Jesus Gebrial


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)
like image 11
Sjobeek Avatar answered Nov 16 '22 17:11

Sjobeek