How to write a string and dictionary value to a Python log file

Question:

I tried this, but it does not seem like you can log a string together with a variable. How can I write a string and dictionary value to a Python log file?

import logging
logging.basicConfig(level=logging.DEBUG, filemode='w', format='%(asctime)s - %(levelname)s - %(message)s (Line: %(lineno)d)', filename='testlog.log')

logger = logging.getLogger()

sample_dict = {
  "vegetable": "carrot",
  "fruit": "orange",
  "chocolate": "kitkat"
}

try:
  print(dsdsd)
except:
  logger.info('Lorem ipsum', sample_dict['fruit'])

Traceback:

--- Logging error ---
Traceback (most recent call last):
  File "C:UsersadminDesktoptest.py", line 13, in <module>
    print(dsdsd)
NameError: name 'dsdsd' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersadminAppDataLocalProgramsPythonPython310liblogging__init__.py", line 1100, in emit
    msg = self.format(record)
  File "C:UsersadminAppDataLocalProgramsPythonPython310liblogging__init__.py", line 943, in format
    return fmt.format(record)
  File "C:UsersadminAppDataLocalProgramsPythonPython310liblogging__init__.py", line 678, in format
    record.message = record.getMessage()
  File "C:UsersadminAppDataLocalProgramsPythonPython310liblogging__init__.py", line 368, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
  File "C:UsersadminDesktoptest.py", line 15, in <module>
    logger.info('Lorem ipsum', sample_dict['fruit'])
Message: 'Lorem ipsum'
Arguments: ('orange',)
[Finished in 156ms]
Asked By: Arete

||

Answers:

Have a look at: https://docs.python.org/3/library/logging.html#logging.debug

You have two options:

  1. You can pass a dictionary of ‘extra’ values as well as the main string. You will then need a custom log formatter to do something with the extra keys, as I think by default they will not be output. e.g.:

    logger.info('Lorem ipsum', extra={"fruit": sample_dict['fruit']})
    
  2. Or alternatively use %s string formatting in your main string, pass your variables as args and the logger will substitute your vars into the string e.g.:

    logger.info('Lorem ipsum, with fruit: %s', sample_dict['fruit'])
    
Answered By: Anentropic
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.