Optional keys in string formats using % operator?

2024/10/13 4:20:33

Is is possible to have optional keys in string formats using '%' operator? I’m using the logging API with Python 2.7, so I can't use Advanced String Formatting.

My problem is as follow:

>>> import logging>>> FORMAT = '%(asctime)-15s %(message)s %(user)s'
>>> logging.basicConfig(format=FORMAT)>>> logging.warning("It works for:", extra={'user': 'me'})
2016-08-29 11:24:31,262 It works for: me>>> logging.warning("It does't work!")
Traceback (most recent call last):...
KeyError: 'user'
Logged from file <input>, line 1

I want to have an empty string for user if missing. How can I do that?

I tried with a defaultdict, but it fails:

>>> import collections
>>> extra = collections.defaultdict(unicode)
>>> logging.warning("It does't work!", extra=extra)
Traceback (most recent call last):...
KeyError: 'user'
Logged from file <input>, line 1

By contrast, with Jinja2, we can do:

>>> import jinja2
>>> jinja2.Template('name: {{ name }}, email: {{ email }}').render(name="me")
u'name: me, email: '

=> no exception here, just an empty string (for "email").

Answer

A) The defaultdict approach works fine, but only if used directly.

>>> import collections
>>> dd=collections.defaultdict(str)
>>> dd['k'] = 22
>>> '%(k)s %(nn)s' % dd
'22 '

B) The extra argument to a log function is used as described in the docs, i.e. not directly as shown above. That's why using a defaultdict instead of a regular dict does not make a difference.

The third keyword argument is extra which can be used to pass adictionary which is used to populate the dict of the LogRecordcreated for the logging event with user-defined attributes.


C) You can use a logging filter to take care of the missing extra data:

import loggingclass UserFilter:def filter(self, record):try:record.userexcept AttributeError:record.user = '<N/A>'return TrueFORMAT = '%(asctime)-15s %(message)s %(user)s'
logging.basicConfig(format=FORMAT)
logging.getLogger().addFilter(UserFilter())logging.warning("It works for:", extra={'user': 'me'})logging.warning("It doesn't work!")
# DATE TIME It doesn't work! <N/A>

Any class with a filter method is fine. It can modify the record in-place and it must return True for accepting the record or False for filtering it out.

https://en.xdnf.cn/q/118123.html

Related Q&A

HDF5 headers missing in installation of netCDF4 module for Python

I have attempted to install the netCDF4 module several times now and I keep getting the same error:Traceback (most recent call last):File "<string>", line 17, in <module>File &quo…

How to catch network failures while invoking get() method through Selenium and Python?

I am using Chrome with selenium and the test run well, until suddenly internet/proxy connection is down, then browser.get(url) get me this:If I reload the page 99% it will load fine, what is the proper…

Pandas crosstab with own function

I have a function which takes two inputs and returns a float e.g. my_func(A, B) = 0.5. I have a list of possible inputs: x = [A, B, C, D, E, F].I want to produce a square matrix (in this case 6 by 6) …

Using a custom threshold value with tf.contrib.learn.DNNClassifier?

Im working on a binary classification problem and Im using the tf.contrib.learn.DNNClassifier class within TensorFlow. When invoking this estimator for only 2 classes, it uses a threshold value of 0.5 …

How to remove certain characters from a variable? (Python)

Lets suppose I have a variable called data. This data variable has all this data and I need to remove certain parts of it while keeping most of it. Lets say I needed to remove all the , (commas) in thi…

criticism this python code (crawler with threadpool)

how good this python code ? need criticism) there is a error in this code, some times script do print "ALL WAIT - CAN FINISH!" and freeze (no more actions are happend..) but i cant find reas…

cx_Freeze executable not displaying matplotlib figures

I am using Python 3.5 and I was able to create an executable using cx_Freeze but whenever I try to run the executable it runs without error but it cannot display any matplotlib figure. I have used Tkin…

Saving variables in n Entry widgets Tkinter interface

Firstly apologises for the length of code but I wanted to show it all.I have an interface that looks like this:When I change the third Option Menu to "List" I will add in the option to have n…

Pulling the href from a link when web scraping using Python

I am scraping from this page: https://www.pro-football-reference.com/years/2018/week_1.htmIt is a list of game scores for American Football. I want to open the link to the stats for the first game. The…

Php: Running a python script using blender from a php project using cmd commands

I need to run in cmd a python script for blender from blender and print the result from a php project, but I dont get the all result. Here is my code:$script = "C:\Users\madalina\Desktop\workspace…