New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

Python Logging Variable Data

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.

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:


import logging

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

WARNING:root: Think before you speak!

In the above code, there is merging of variable data into the event description message using the old, %s style of string formatting.

Also, the arguments that are passed to the method would be included as variable data in the 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:

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