Python logging can use f-strings, but the f-string is evaluated before the logging call, even when the message will be filtered out. For routine log messages, pass values as separate arguments with %-style placeholders—such as logger.debug('value=%s', value)—so logging can defer formatting until it needs to emit the record.
The short answer: f-strings work, but are eager
This is valid Python and produces a log message as expected:
logger.info(f'User {user_id} signed in')
The trade-off is timing. Python constructs the complete f-string before it calls logger.info. If the logger’s effective level excludes INFO messages, the message is discarded only after the f-string has already been built. That usually makes little difference for a short string and a simple value, but it can waste work when a message is disabled or its expression is expensive.
The usual logging pattern is:
logger.info('User %s signed in', user_id)
Here, the first argument is the message template and the remaining arguments are values to insert. The logging system can postpone combining them until it formats a record for output. This is often called lazy or deferred formatting. It does not mean Python delays evaluating every expression passed to the logging call; it delays interpolation of the template and arguments.
How logging formats a message
Python’s standard logging module separates creating a log record from rendering its final text. A call such as logger.debug('Loaded %s rows', row_count) supplies a template and an argument tuple. If the logger accepts the event, it creates a LogRecord and passes it through the configured handlers and filters. A handler’s formatter eventually obtains the message text, applying %-style interpolation to the template and its arguments.
If the logger rejects the event because its effective level is higher than DEBUG, it normally returns without creating a record or formatting that message. The call’s Python arguments are still evaluated first, however. For example, logger.debug('State: %s', build_large_state()) calls build_large_state() whether or not DEBUG output is enabled. Deferred formatting avoids interpolation work; it cannot defer a function call that Python must evaluate to make the call.
With an f-string, both the expression and string construction happen before logging checks the level:
logger.debug(f'State: {build_large_state()}')
This version can do both the expensive computation and string construction for a message that is never shown. The same principle applies to expressions such as repr(obj), joining a large collection, or serializing data to JSON.
Choosing between f-strings and logging arguments
For conventional log records, use a fixed message template and pass changing values separately. This keeps the message construction deferred and makes the variable fields easier to recognize in code. The logging call uses %-style placeholders even if the rest of the application uses f-strings for ordinary strings.
- Prefer logging arguments for routine DEBUG, INFO, WARNING, ERROR, and CRITICAL messages:
logger.warning('Retry %d for %s', attempt, endpoint). - An f-string is reasonable when the message is guaranteed to be emitted, its expressions are cheap, or a prebuilt string is specifically needed:
message = f'Connected to {host}'. - Use a level check when preparing a diagnostic value is expensive: check
logger.isEnabledFor(logging.DEBUG)before doing that work.
For example, a guarded diagnostic can avoid the expensive call when DEBUG is off:
if logger.isEnabledFor(logging.DEBUG):
state = build_large_state()
logger.debug('State: %s', state)
Do not add such a guard around every ordinary logging call without a reason. The extra branch can make straightforward code harder to read, and a simple value passed as an argument is generally a good fit for the standard API. Reserve the check for work that would be meaningful to avoid.
What the percent sign means here
In a logging call like logger.info('Processed %d items', count), %d is a placeholder in the message template. It is not the same as writing 'Processed %d items' % count yourself. The latter performs interpolation immediately, before the logger can decide whether to emit the event. Passing the values separately gives the logging package the opportunity to defer interpolation.
The placeholder conversion should match the value: %s requests a string representation, %r requests a representation useful for debugging, and %d is for an integer-style value. For multiple values, supply multiple arguments in the same order as the placeholders:
logger.info('Request %s completed in %.3f seconds', request_id, elapsed)
Use a fixed template rather than inserting changing values into the template itself. Keeping the message stable makes records easier to search, compare, and aggregate. It also avoids confusing mistakes such as a placeholder and argument count mismatch, which can cause formatting errors when the record is rendered.
Logging call formatting is not formatter style
A common point of confusion is the style option available when configuring a logging Formatter. That option controls how the formatter’s overall output pattern is written—for example, where fields such as the level name and timestamp go. It does not change the normal message-argument convention used by calls such as logger.info(...).
For example, a formatter can use brace-style fields for the record layout:
formatter = logging.Formatter(
'{asctime} {levelname} {message}',
style='{'
)
That does not make logger.info('Hello {}', name) the standard brace-formatting form. Logging still uses %-style interpolation for a message and its separately supplied arguments. Writing logger.info('Hello %s', name) remains the conventional call, regardless of the formatter’s style. The formatter’s style and the message’s argument formatting are distinct layers.
Exceptions, tracebacks, and useful context
For an exception being handled, prefer logger.exception inside the except block when you want the message and exception information together. It records the current exception information, so there is usually no need to convert the exception to a string yourself:
try:
load_config(path)
except OSError:
logger.exception('Could not load configuration from %s', path)
The placeholder style still applies to the message. Logging the exception with logger.exception('Could not load configuration from %s', path) is clearer than putting a formatted exception string into an f-string and losing the traceback. Outside an exception handler, use logger.error(..., exc_info=True) only when there is an active exception context whose details should be attached.
Include context that helps explain the event, such as a request identifier or the relevant resource name, but do not log passwords, access tokens, or other secrets. Formatting choice does not make sensitive data safe. Also consider whether a value can contain newlines or other content that may make plain-text logs misleading; validate, escape, or structure such data according to how the logs are consumed.
Structured logging and stable messages
Separate logging arguments support deferred text formatting, but they do not automatically turn a standard log record into a structured event with named fields. In the usual call, logger.info('Order %s shipped', order_id), the value is used to create the final message. A log search tool may see the rendered text, but it does not necessarily receive a dedicated field named order_id.
When logs need machine-readable fields, use a structured logging approach supported by your application or logging setup. The standard library also allows extra attributes to be attached to a record using the extra argument, provided the formatter or handler is configured to use them. For example:
logger.info('Order shipped', extra={'order_id': order_id})
Attaching an attribute does not by itself guarantee that it appears in the output; the formatter must include it, and the chosen attribute name must not conflict with existing LogRecord attributes. If a system needs JSON output or consistent searchable fields, decide on the schema and configure the output accordingly rather than assuming an f-string or a placeholder creates structured data.
Common mistakes to avoid
- Interpolating too early:
logger.debug('Count: %s' % count)andlogger.debug(f'Count: {count}')both build the final message before calling the logger. - Expecting arguments to delay function calls:
logger.debug('Result: %s', calculate())still runscalculate()immediately. Use a level check around genuinely expensive work. - Using brace placeholders directly:
logger.info('User {}', user)does not follow the standard logging call convention. Uselogger.info('User %s', user). - Confusing formatter configuration with message syntax:
style='{'affects the formatter layout, not the placeholders in the logging call. - Building a changing template: keep the message text stable and pass variable values as arguments rather than embedding them into the template.
These patterns matter most in frequently executed code and when logs are filtered by level. For a one-off message with a cheap expression, an f-string is not inherently incorrect; the important distinction is whether eager evaluation is acceptable and whether the code benefits from the standard deferred-formatting convention.
Frequently Asked Questions
Can I use an f-string in Python logging?
Yes. It works like any other string, but Python evaluates it before calling the logger. For routine log messages, separate arguments are usually preferable because logging can defer interpolation.
Is %-style formatting faster than an f-string?
It can avoid building a message that the logger will filter out, but the practical difference depends on the message and how often that happens. It does not prevent evaluation of argument expressions, so an expensive function call still runs unless you guard it.
Can I use .format() or brace placeholders in a logging call?
You can format a string before passing it to logging, but that formatting happens eagerly. The standard message-argument convention uses %-style placeholders, such as logger.info('Hello %s', name).
Does style='{' enable f-string-style logging?
No. The formatter’s style setting controls the formatter’s record-layout pattern. It does not change how a logging call combines its message template and arguments.
Should I use f-strings for error messages?
You may, but passing values separately is still a clear default. For an exception inside an except block, use logger.exception('Operation failed for %s', item) when you want the traceback attached as well as a contextual message.
Related
- JavaScript String Split to Array: Examples and Tips
- Balance of Payments: How It Works and What It Shows
- How to Split an Array in Java: Safe Ways to Do It Cleanly
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Inventory Spreadsheets for Small Business: Setup and TipsYes—an inventory spreadsheet can work well for a small business when the product range and transaction volume are…
- Add a Picture as a Watermark in WordTo add a picture watermark in Microsoft Word, open the document in the desktop app and choose Design…
- Importing CSV Into Excel: Steps, Settings, and FixesTo import a CSV into Excel for Microsoft 365 on Windows, select Data > From Text/CSV, choose the…
- Conditional Formatting in Excel: Questions AnsweredIn Excel for Microsoft 365 on Windows, select the cells you want to format, then choose Home >…
- Change All Text to Lowercase in ExcelTo change text to lowercase in Excel, use the LOWER function in a helper column, fill it down,…
- Flash Fill Practice Sheet: Excel Drills and AnswersTo practice Flash Fill in Excel for Microsoft 365 on Windows, put source data beside an empty column,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.