Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

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:

Python
import logging

name = 'John'

logging.error('%s raised an error', name)

Here’s what you’ll get:

Shell
ERROR:root:John raised an error
Avatar image for Rob Black

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).

Avatar image for Rob Black

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.

Avatar image for Dillon O'Leary

Dillon O'Leary on Dec. 19, 2024

I think it’s better to use lazy string evaluation, that way we aren’t paying a performance cost to do string interpolation on logs that aren’t even written out. In practice, it looks like this:

logging.warning('%s before you %s', 'Look', 'leap!')

That’s from the python website.

Avatar image for Martin Breuss

Martin Breuss RP Team on Dec. 19, 2024

@Dillon O’Leary that’s a good point! Especially when you’re doing a lot of low-level logging, then it’s definitely worth it to use lazy string evaluation like you show here and steer clear of f-strings.

If we’re lucky, we might get t-strings soon, which give the clean syntax of f-strings but with lazy evaluation!

Become a Member to join the conversation.