Intermediate   Chapter 169 · 30 min read · Module 13: Python Testing and Debugging

Logging

Learning objectives
  • After this chapter you can explain why logging is better than print for tracking program behaviour.
  • You can use the five standard log levels and set a threshold.
  • You can configure output with basicConfig, formatters and handlers.
  • You can create named loggers and write logs to a file.
  • You can log exceptions and values safely with lazy formatting.

When a program grows, you need a way to see what it is doing. Many beginners add print calls everywhere, then delete them later. This works for tiny scripts, but it becomes messy and slow to manage in real projects.

Python ships with the logging module in the standard library. It lets you write messages with a level of importance, decide where those messages go (screen, file, network), and change the amount of detail without touching the code that writes the messages.

In this chapter you will learn the five log levels, how to configure the output, how named loggers and handlers work together, and how to record errors in a way that helps you fix them later.

Why not just use print?

A print call always prints. You cannot turn it off for one part of the program, you cannot add the time or the file name automatically, and you cannot send it to a file without changing every call. Logging solves these problems. Each message has a level, and the logging system decides whether to show it based on a threshold that you set in one place.

Logging is also useful after the program has shipped. A server that runs for weeks cannot show you a console, but it can write a log file. When something fails at night, the file tells you what happened before the failure.

Log record: an object created each time you log a message. It holds the text, the level, the logger name, the time and more.

The five log levels

Every message is sent with one of five standard levels. Each level has a number, and a higher number means a more serious message.

LevelNumberWhen to use it
DEBUG10Detailed facts useful while developing
INFO20Normal events, such as a file was loaded
WARNING30Something unexpected, but the program continues
ERROR40A task failed
CRITICAL50The program may not be able to continue

By default the root logger shows only WARNING and above. That is why a plain logging.info(...) shows nothing until you lower the threshold. You set the threshold with level= in basicConfig or with setLevel on a logger.

Example 1: levels and the threshold
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="%(levelname)s: %(message)s", force=True)
logging.debug('reading settings')
logging.info('app started')
logging.warning('disk is almost full')
logging.error('could not save file')
logging.critical('out of memory')
logging.getLogger().setLevel(logging.WARNING)
logging.info('this is now hidden')
logging.error('this still shows')
DEBUG: reading settings INFO: app started WARNING: disk is almost full ERROR: could not save file CRITICAL: out of memory ERROR: this still shows
We pass stream=sys.stdout so the messages appear on standard output in the examples. By default logging writes to standard error. The force=True option replaces any earlier setup.

Formatting log messages

The format string controls what each line looks like. It uses names such as %(levelname)s, %(name)s, %(message)s, %(asctime)s and %(lineno)d. Time stamps change on every run, so we avoid asctime in the runnable examples, but you should use it in real programs.

When you want to include a variable, pass it as an argument instead of building the string yourself: logging.info('user %s logged in', name). This is called lazy formatting. The string is built only if the message is really going to be emitted, which saves time when the level is filtered out.

Example 2: named loggers and lazy formatting
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="%(levelname)s:%(name)s: %(message)s", force=True)
log = logging.getLogger('shop.cart')
items = 3
price = 4.5
log.info('cart has %d items', items)
log.warning('total is %.2f', items * price)
logging.getLogger('shop.pay').debug('payment module ready')
INFO:shop.cart: cart has 3 items WARNING:shop.cart: total is 13.50 DEBUG:shop.pay: payment module ready

Loggers, handlers and formatters

Logging has three main parts. A logger is what your code calls. A handler decides where the record goes, for example StreamHandler for the console or FileHandler for a file. A formatter decides how the record looks. A logger can have many handlers, and each handler can have its own level and formatter.

Logger names use dots to build a tree. The logger shop.cart is a child of shop. Child loggers pass their records up to their parents, which is called propagation. A common habit is to write log = logging.getLogger(__name__) at the top of every module, so the name matches the module.

Example 3: a file handler with its own format
import logging, sys
log = logging.getLogger('app')
log.setLevel(logging.DEBUG)
log.propagate = False
fh = logging.FileHandler('app.log')
fh.setLevel(logging.INFO)
fh.setFormatter(logging.Formatter('%(levelname)s|%(message)s'))
log.addHandler(fh)
log.debug('not written, handler wants INFO')
log.info('saved record 1')
log.error('failed record 2')
fh.close()
print(open('app.log').read().strip())
INFO|saved record 1 ERROR|failed record 2

Logging errors and exceptions

Inside an except block, call logger.exception('message'). It logs at ERROR level and adds the full traceback, which is exactly what you need to find the bug. You can get the same traceback from any level by passing exc_info=True.

Example 4: logging a caught error
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="%(levelname)s: %(message)s", force=True)
def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        logging.error('divide failed: %s', e)
        return None

print(divide(8, 2))
print(divide(1, 0))
4.0 ERROR: divide failed: division by zero None

In this example the error message is recorded, the function returns None, and the program carries on. The traceback is not shown here because we used error, not exception.

Never log passwords, tokens or personal data. Log files are often copied and shared, so treat them as public.

Python syntax

Syntax
import logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logging.info('text %s', value)
Syntax
log = logging.getLogger(__name__)
handler = logging.FileHandler('app.log')
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
log.addHandler(handler)
Syntax
try:
    risky()
except Exception:
    log.exception('risky failed')

Real-world applications

  • Web servers record requests and errors in log files.
  • Data pipelines log how many rows each step processed.
  • Desktop and mobile apps log crashes so developers can fix them.
  • Scheduled scripts log their start, end and failures because nobody is watching them.

Common mistakes

Mistake: Calling basicConfig after other logging calls and wondering why it has no effect.
Fix: Call basicConfig once, at the start of the program, or pass force=True.
Mistake: Expecting logging.info to print with the default settings.
Fix: The default level is WARNING. Set level=logging.INFO or lower.
Mistake: Building messages with f-strings inside every call.
Fix: Use lazy formatting, logging.info('x=%s', x), so work is skipped when the level is filtered.
Mistake: Adding the same handler many times, which makes every line appear repeated.
Fix: Add handlers once, for example only when logger.handlers is empty.
Mistake: Logging secrets such as passwords.
Fix: Log identifiers only, and mask or leave out sensitive values.

Important tips

  • Use getLogger(__name__) in each module.
  • Configure logging only in the main entry point, not inside library code.
  • Use DEBUG during development and INFO or WARNING in production.
  • Include the time stamp and level in the format.

Key points summary

  • Logging has five levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
  • The default threshold is WARNING.
  • Loggers create records, handlers send them, formatters style them.
  • logger.exception adds the traceback.
  • Use lazy formatting with %s arguments.

Exam and interview points

  • Know the order of levels and their numbers.
  • The root logger's default level is WARNING.
  • basicConfig does nothing if the root logger already has handlers, unless force=True.
  • Records propagate from child loggers to parent loggers.

Quick revision

  • DEBUG < INFO < WARNING < ERROR < CRITICAL.
  • basicConfig sets level, format and stream or filename.
  • getLogger(name) returns the same logger each time.
  • Handlers choose the destination; formatters choose the look.
  • exception() = error() + traceback.

Frequently asked questions

Is logging slower than print?

Slightly, but it can be faster in practice because filtered messages cost very little, especially with lazy formatting.

Where do logs go by default?

The default handler writes to standard error, not standard output.

Can I log to the console and a file together?

Yes. Add both a StreamHandler and a FileHandler to the same logger, each with its own level if you wish.

What does __name__ do in getLogger?

It gives the logger the module name, so you can see which module wrote each message and control them by name.

When should I use exception instead of error?

Use exception inside an except block when you want the traceback saved with the message.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters