Reputation: 4647
I like the interface of Python's print
function:
print("abc %d %s" % (12, "sdf"), 78, "some other string")
But, when I use the the default logging
package for logging the interface is different:
logger.info("abc %d %s 78 some other string", 12, "sdf")
Is there any reason they are inconsistent? Is it possible to get logging
logger
to behave print
-like?
Upvotes: 1
Views: 91
Reputation: 363083
TL;DR: there are some advantages to letting the logger format the message, rather than formatting it yourself. For print
there are no such advantages, so it's better to have the more convenient interface.
The first thing you are seeing is that the function signatures are different. The print
function accepts arbitrarily many positional arguments, and prints them all. In your example, you sent 3 positional arguments to print and they get joined by a space.
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
The logger functions accept one positional argument for the message, and arbitrarily many template variables to substitute in that message, for example:
logger.info(msg, *args, **kwargs)
Is there any reason they are inconsistent?
Yes. Here print
is just a function and, like any other function, the arguments are fully evaluated before the function argument is called. So, the templating "abc %d %s" % (12, "sdf")
happens first.
Using loggers, on the other hand, it's better to let the logger do the templating/formatting. There are a few reasons for this, but perhaps the most convincing one is that log aggregation services can easily group together the same kind of errors. Those errors from the same template, triggered with different parameters, can be seen as a whole - rather than generating thousands of individual errors.
Upvotes: 2