Python logging: why printf-style string formatting may be better thanf-strings

栏目: IT技术 · 发布时间: 4年前

内容简介:Python provides more than one way to format strings:

Python provides more than one way to format strings: %-formatting , str.format() , string.Template and f-strings . What format developers use is the matter of personal aesthetic reasons rather than anything else. Still there are use cases where good old printf-style %-formatting may have advantages over other formats. Python’s logging module is one of these cases. Let’s see what are the main reasons to use %-formatting for logging in Python.

Python logging optimization: format string until it cannot be avoided

Python logging methods like debug get in message argument along with optional args and kwargs . Arguments used for message formatting. Formatting of these arguments is deferred until it cannot be avoided. That means the final message is not evaluated if its log level is below the logger’s log level. On the other hand, f-string is really an expression that evaluated at runtime and it lacks logging’s optimizations. Let’s see an example:

In [1]: import logging
   ...: logging.basicConfig(level=logging.INFO)
   ...: logger = logging.getLogger('TestLogger')

In [2]: class A:
   ...:     def __str__(self):
   ...:         print('Unnecessary slow computations are done here!')
   ...:         return self.__class__.__name__
   ...:
   ...: obj = A()

In [3]: logger.debug("log level below INFO with args: %s", obj)

In [4]: logger.debug(f"log level below INFO with f-string: {obj}")
Unnecessary slow computations are done here!

In [5]: logger.info("log level INFO with args: %s", obj)
Unnecessary slow computations are done here!
INFO:TestLogger:log level INFO with args: A

As you can see in step 3 message is not logged as root logger’s level is higher than debug . That’s why that message is not formatted. In step 4 f-string is evaluated even though it’s not getting logged either.

Logging module has other nice optimizations that worth learning.

Sentry integration with logging

Sentry is a popular error tracking solution. Sentry integrates with the Python logging module. Error aggregation is another great feature of Sentry. Sentry looks at the event’s stacktrace, exception, or message and group it with existing ones if they are the same. If you get a hundred of exceptions that are all the same they get grouped into one with nice statistics.

When integrating Sentry with Python logging, it’s important to use %-formatting , so that Sentry can group your messages. As an example, let’s log failed attempts to retrieve an URL :

logger.error("Failed to retrieve URL %s", url)

With printf-style formatting your messages will be grouped together no matter what value url variable holds. But in this case:

logger.error(f"Failed to retrieve URL {url}")

you get a separate event in Sentry for every single unique URL . If you get 1000 unique URL , your Sentry dashboard might get messy.

Conclusions

Although Python is not Perl, there’s still more than one way to do it. Which string formatting style to use is an open question. Your project may not use Sentry, or you may prefer f-strings for readability reasons. You may see deferred formatting in logging for printf-style strings as a futile micro-optimization that won’t improve your app performance. But still, there may be cases where using an oldie but goldie %-formatting is beneficial, even at price of string formatting inconsistency.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

网络英雄传

网络英雄传

郭羽、刘波 / 江苏凤凰文艺出版社 / 2018-6 / 59.80元

“商战鬼才郭羽、营销奇才刘波强强联手,凝集十年实战经验,倾力打造商战巨作。” 这是一个商业竞争和资本激战交织的惊心动魄的创业交锋故事。 由郭天宇、刘帅共同创立的在线旅游公司万全天盛凭借其出色的商业模式异军突起,与老牌巨头“51旅游网”两强相争,但国际巨头通远来势汹汹,国内在线旅游市场进入战火纷飞的“三国杀”时代,分踞杭、沪、京三地互相“搏杀”。中国新兴的互联网公司面对国际巨头的入侵,毫不退缩......一起来看看 《网络英雄传》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具