【问题标题】:Use lazy % formatting in logging functions pylint error message在记录函数 pylint 错误消息中使用惰性 % 格式
【发布时间】:2021-04-07 20:02:45
【问题描述】:

我有一个python函数如下,当启用pylint进行代码扫描时,它会抛出一个惰性格式化错误。

def modify_response(data):
    try:
        response = {}
        response["User_ID"] = data[0]["User_ID"]["S"]
        response["Triggered_Timestamp"] = data[0]["Triggered_Timestamp"]["S"]
        return response
    except Exception as e:
        logging.exception("ModifyResponseError: {}".format(e))
        raise ModifyResponseError(json.dumps({"httpStatus": 501,"message": internal_error_message}))

【问题讨论】:

  • 最佳实践是使用 f-string。换成logging.exception(f"ModifyResponseError: {e}")
  • stackoverflow-lint 警告:问题没有指出哪一行失败。问题不会发布错误消息。
  • @K.Mat 你对 f-strings 有同样的问题。请参阅 tdelaney 的答案。

标签: python logging error-handling formatting pylint


【解决方案1】:

假设这条线是

logging.exception("ModifyResponseError: {}".format(e))

警告是

W1202: Use lazy % formatting in logging functions (logging-format-interpolation)

日志记录函数应该传递一个格式字符串和参数,而不是一个已经格式化的字符串。否则,您将冒着格式化操作本身在日志记录发生之前引发异常的风险。这些都是老派printf style format strings。出于同样的原因,pylint 也会抱怨 f-strings。

linter 会很高兴的

logging.exception("ModifyResponseError: %s", e)

详情请见logging.debug

【讨论】:

  • 除了从格式化异常中保存之外,它还使您免于评估可能根本不使用的字符串。示例 log.debug(f"This is {bigfunc(foo, bar)}") - 假设调试日志没有记录在 prod 中,这将导致不必要的字符串评估,只是被丢弃。
猜你喜欢
  • 2016-04-09
  • 2011-05-08
  • 2020-12-23
  • 1970-01-01
  • 2012-02-11
  • 2017-09-02
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
相关资源
最近更新 更多