Add encoding parameter to logging.basicConfig

How to add encoding parameter to logging.basicConfig ?

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

+7
source share
2 answers

In your case, it will be easier to avoid using basicConfig() - just create a handler and add it programmatically (ensuring that the code is executed only once), for example:

 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) 

This is more or less what basicConfig() .

+13
source

Vinay's answer was very useful, but to get it working, I had to fine-tune 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) 
+6
source

Source: https://habr.com/ru/post/916374/


All Articles