Logging Variable Data
In most cases, you would want to include dynamic information from your application in the logs. You have seen that the logging methods take a string as an argument, and it might seem natural to format a string with variable data in a separate line and pass it to the log method. But this can actually be done directly by using a format string for the message and appending the variable data as arguments. Here’s an example:
import logging
name = 'John'
logging.error('%s raised an error', name)
Here’s what you’ll get:
ERROR:root:John raised an error
00:00 In most cases, we want to include information about the variables in our program within our logs. We can add variable data into our logs using any formatting style, like the f-strings introduced in Python 3.6.
00:16
In this example, I’ve defined a variable called name
and it’s holding the string 'John'
. Then I log a new event with the level ERROR
and I give it the message of f'{name} raised an error'
. When we run this, we’ll see that John raised an error
.
00:34
We didn’t change the formatting of the output at all, so we’re still seeing the default logger name of root
.
Rob Black on July 29, 2019
Hi all. I should have submitted my previous comment via the Feedback button instead of posting here. Sorry for the noise.
Become a Member to join the conversation.
Rob Black on July 29, 2019
The name argument to the log message in this example (i.e. John) should not be confused with the name string in the format argument of the basicConfig call in the previous example (i.e. root).