Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:\Users\admin\Desktop\test.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:\Users\admin\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 1100, in emit
    msg = self.format(record)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 943, in format
    return fmt.format(record)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 678, in format
    record.message = record.getMessage()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 368, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
  File "C:\Users\admin\Desktop\test.py", line 15, in <module>
    logger.info('Lorem ipsum', sample_dict['fruit'])
Message: 'Lorem ipsum'
Arguments: ('orange',)
[Finished in 156ms]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'])
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading