python 数据库变量
Sometimes you would want to include some dynamic information from your application in the logs.
有时,您可能希望在日志中包含来自应用程序的一些动态信息 。
As we have seen in examples till now, we print strings in logs, and we can easily format and create strings by adding variable values to it. This can also be done within the logging methods like debug()
, warning()
, etc.
到目前为止,我们在示例中已经看到,我们在日志中打印字符串,并且可以通过向其添加变量值来轻松格式化和创建字符串。 这也可以在诸如debug()
, warning()
等日志记录方法中完成。
To log the variable data, we can use a string to describe the event and then append the variable data as arguments. Let us see how we will do this with the help of an example given below:
要记录变量数据,我们可以使用字符串描述事件 ,然后将变量数据附加为参数 。 让我们看看如何在以下示例的帮助下做到这一点:
例 (Example)
import logging
logging.warning('%s before you %s', 'Think', 'speak!')
WARNING:root: Think before you speak!
警告:root:说话前请三思!
In the above code, there is merging of variable data into the event description message using the old, %s
style of string formatting.
在上面的代码中,使用旧的%s
字符串格式样式将变量数据合并到事件描述消息中 。
Also, the arguments that are passed to the method would be included as variable data in the message.
另外,传递给该方法的参数将作为变量数据包含在message中 。
还有另一种方式 (There is Another way)
As you can use any formatting style, the f-strings introduced in Python 3.6 are also an amazing way to format strings as with their help the formatting becomes short and easy to read:
由于您可以使用任何格式设置样式,因此Python 3.6中引入的f字符串也是一种格式化字符串的绝妙方法,因为借助其帮助,格式变得简短易懂:
Here is a code example:
这是一个代码示例:
import logging
name = 'Thomas'
logging.error(f'{name} raised an error in his code')
ERROR:root: Thomas raised an error in his code
错误:root:Thomas在他的代码中提出了一个错误
翻译自: https://www.studytonight.com/python/python-logging-variable-data
python 数据库变量