How does the log format string work?

QuestionsQuestions8 SkillsProDec, 19 2025
0110

That's a great question! The format string in logging.basicConfig() acts like a template. It tells Python exactly which pieces of "metadata" to include in every log entry.

In your code, you used:
format=' %(asctime)s - %(levelname)s - %(message)s'

Here is the breakdown of those special "placeholders":

1. %(asctime)s (The Timestamp)

  • What it does: Inserts the current date and time when the log was created.
  • Why it's useful: Without this, you might know what happened, but you wouldn't know when or in what order relative to other system events.

2. %(levelname)s (The Importance)

  • What it does: Inserts the level of the log (e.g., DEBUG, INFO, WARNING, ERROR).
  • Why it's useful: It allows you to quickly skim your logs and ignore the "noise" of DEBUG messages while looking for a specific ERROR.

3. %(message)s (Your Content)

  • What it does: Inserts the actual string you passed into the function, like 'Start of program' or 'i is 1'.
  • Why it's useful: This is the core data you are actually tracking.

Other Useful formatters

You can add even more detail if your project gets bigger:

  • %(filename)s: Shows which Python file the log came from.
  • %(lineno)d: Shows the exact line number where the log was triggered.
  • %(threadName)s: Useful in advanced programming to see which part of the CPU is running the code.

Example comparison:

  • Simple: format='%(message)s'
    • Output: Start of program
  • Pro Version: format='[%(levelname)s] Line:%(lineno)d - %(message)s'
    • Output: [DEBUG] Line:3 - Start of program

Try this experiment:
Go back to your factorial_log.py file and change the format string to:
format='Line %(lineno)d - %(levelname)s: %(message)s'

Run it again, and you'll see exactly which lines in your code are generating each log message! Should I explain how to change the time format too, or are you ready for the next step?

0 Comments

no data
Be the first to share your comment!