Topics

Python Logging Variable Data

Welcome to a tutorial on Logging Variable Data in Python.

During coding, you might decide to add some dynamic information forms your application in the logs.

Recall from previous examples, we have printed strings in logs, and we can as well format and create strings by simply adding variable values to them. We can also do this within the logging methods like debug(), warning(), and so on.

Also, in other to log the variable data, we can use a string to describe the event and then append the variable data as arguments. Check out the example below:

import logging

logging.warning('%s before you %s', 'Think', 'speak!')

Output:

WARNING:root: Think before you speak!

From the above example, there is a merging of variable data into the event description message by making use of the old, %s style of string formatting. More so, the arguments that are passed to the method would be included as variable data in the message.

 

Let’s do the above in Another way

You already know that in any formatting style, in Python 3.6, the f-strings introduced are an interesting way to format strings as with their help the formatting becomes short and easy to read.

Check out the example:

import logging
name = 'Thomas'

logging.error(f'{name} raised an error in his code')

Output:

ERROR:root: Thomas raised an error in his code