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. How do I add an encoding parameter to logging.basicConfig?,Update: As of Python 3.9 (still in development), basicConfig() should have encoding and errors keywords available.,Connect and share knowledge within a single location that is structured and easy to search.
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)
Answer by Prince English
Help Tracker Documentation Tracker Development Report Tracker Problem
Yes, you could just make a custom logging.FileHandler object, but this way is much easier for those who are following the basic logging tutorial.
Answer by Emerie Moran
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.,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.
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)
Answer by Aliyah Medina
You may also want to check out all available functions/classes of the module logging , or try the search function .
def init_logging(log_file=None, append=False, console_loglevel=logging.INFO): """Set up logging to file and console.""" if log_file is not None: if append: filemode_val = 'a' else: filemode_val = 'w' logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(threadName)s %(name)s %(message)s", # datefmt='%m-%d %H:%M', filename=log_file, filemode=filemode_val) # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(console_loglevel) # set a format which is simpler for console use formatter = logging.Formatter("%(message)s") console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) global LOG LOG = logging.getLogger(__name__)
Answer by Alexandra Montgomery
import logging import sys logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s', '%m-%d-%Y %H:%M:%S') stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(logging.DEBUG) stdout_handler.setFormatter(formatter) file_handler = logging.FileHandler('logs.log') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.addHandler(stdout_handler)
Answer by Idris Schultz
I don’t know why this happens because by default, strings in Python2 are supposed to be bytes, not unicode. This is because of from __future__ import unicode_literals at the top of util.py,The strange thing is that when I apply the fix from the commit to your reproducer (converting log_msg_* to str explicitly to circumvent unicode_literals) then it fixes the issue:,What happens is that string formatting tries to implicitly convert the arguments to unicode:,I’m running Python 2.7. There’s a chance this might not happen in Python 3 due to improved unicode support, however, changing the version is sadly not a possibility for me.
Traceback (most recent call last): File "/usr/lib/python2.7/logging/__init__.py", line 851, in emit msg = self.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 724, in format return fmt.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 464, in format record.message = record.getMessage() File "/usr/lib/python2.7/logging/__init__.py", line 328, in getMessage msg = msg % self.args UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3207: ordinal not in range(128) Logged from file util.py, line 465