在日志记录函数中使用惰性%格式 pylint 错误消息

ash*_*han 17 python error-handling formatting logging pylint

我有一个 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}))
Run Code Online (Sandbox Code Playgroud)

tde*_*ney 31

假设该线是

logging.exception("ModifyResponseError: {}".format(e))
Run Code Online (Sandbox Code Playgroud)

警告是

W1202: Use lazy % formatting in logging functions (logging-format-interpolation)
Run Code Online (Sandbox Code Playgroud)

应向日志记录函数传递格式字符串和参数,而不是已格式化的字符串。否则,您可能会面临格式化操作本身在记录发生之前引发异常的风险。这些是老式printf 风格的格式字符串。出于同样的原因,pylint 也会抱怨 f 字符串。

linter 会很高兴

logging.exception("ModifyResponseError: %s", e)
Run Code Online (Sandbox Code Playgroud)

logging.debug详情请参阅。