Reputation: 11
I can use the code below to record the log:
# method 1
>>> import logging
>>> user = "Jim"
>>> logging.warning("This is a warning from %s", user)
WARNING:root:This is a warning from Jim
However, I can also use the code blow to do the same thing:
# method 2
>>> import logging
>>> user = "Jim"
>>> logging.warning("This is a warning from %s" %user)
WARNING:root:This is a warning from Jim
It seems that I can always use method 2 to record the log and the args
in method warning
of class Logger
is unnecessary?
Can someone tell me what is the difference between method 1 and method 2?
Upvotes: 1
Views: 65
Reputation: 9714
By using the separate args parameter means those arguments are included in the LogRecord that is passed to the filters, and you (or someone else) could write a filter which uses one or more of the args, or kwargs.
Edit : The answer above by Mad Physicist is also correct that using args defers interpolation until the string is actually needed.
Upvotes: 2
Reputation: 114440
The logging framework lets you turn levels on and off based on the level, where the message to going, etc.
The first method accepts a string and a tuple of objects. If your log entry is not going to be logged based on whatever criteria you have enabled, the string in not interpolated at all.
The second method interpolates the string immediately and passes the result to the logging framework. This may be expensive, since calling str
and repr
on arbitrary objects can execute any code. This is not efficient if, for example, your logging level is turned off.
The content of the string will be the same either way. The main difference is in when the arguments are interpolated, not how. Deferred interpolation (passing the args to the logger instead of doing it yourself) is much more efficient, when some logging levels or destinations are disabled.
Upvotes: 3
Reputation: 231
In method1, warning will format the string for you. In method2, you will format the string yourself
Upvotes: 0