Home > Blockchain >  How to write a string and dictionary value to a Python log file
How to write a string and dictionary value to a Python log file

Time:10-22

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]

CodePudding user response:

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'])
    
  • Related