Skip to main content

Python logging basicconfig format and examples

· 7 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

The logging.basicConfig() function is the easiest way to perform basic setup for the Python logging module. It sets the configuration for the root logger, which is the parent of all other loggers in your application.

This function is ideal for simple scripts, development environments, and applications where you only need a single, global logging configuration.

1. Understanding the basicConfig Parameters

logging.basicConfig() accepts several keyword arguments to define the minimum logging level, the output destination, and the structure of the log messages.

ParameterPurposeExample
levelSets the minimum severity level to handle. Logs below this level are ignored.level=logging.INFO
filenameSpecifies a file path to write logs to. If omitted, logs go to the console.filename='app.log'
filemodeSpecifies the file open mode ('a' for append, 'w' for overwrite). Default is 'a'.filemode='w'
formatDefines the exact structure and content of the log message string.format='%(asctime)s - %(levelname)s - %(message)s'
streamSpecifies an output stream (e.g., sys.stderr or sys.stdout) if filename is not used.stream=sys.stdout

2. The Log Message Format String

The format parameter is a standard Python string that contains special placeholder variables (prefixed with %(...)s). These variables are dynamically replaced with details about the logging event.

Here are the most common and useful format specifiers:

SpecifierDescriptionExample Output
%(asctime)sThe time the LogRecord was created.2025-12-14 07:05:00,123
%(levelname)sThe text logging level for the message.INFO, ERROR, DEBUG
%(name)sThe name of the logger that generated the event.MyApp.Worker1
%(message)sThe actual log message content.Processing complete.
%(module)sThe name of the module (file) where the call was made.database_module
%(lineno)dThe line number within the module where the call was made.145

Example Format String

A robust format string for production might combine several specifiers:

FORMAT = '%(asctime)s [%(levelname)s] (%(filename)s:%(lineno)d) %(message)s'

Example Output: 2025-12-14 07:05:00,123 [ERROR] (api.py:145) Failed to connect to server.


3. Basic Configuration Examples

Example A: Development Console Output

This configuration is perfect for local development. It sets the level to DEBUG and outputs a detailed, yet simple, format to the console.

import logging
import sys

# Configure for DEBUG level output to standard output (stdout)
logging.basicConfig(
level=logging.DEBUG,
stream=sys.stdout,
format='%(levelname)s: %(message)s (%(filename)s:%(lineno)d)'
)

logger = logging.getLogger("DevApp")

logger.debug("Debugging data structure creation.") # Will show
logger.info("Service initialized.") # Will show
logger.warning("Resource limits are high.") # Will show

Output:

DEBUG: Debugging data structure creation. (script_name.py:10)
INFO: Service initialized. (script_name.py:11)
WARNING: Resource limits are high. (script_name.py:12)

Example B: Production File Output

This configuration sets a higher severity level (WARNING) and directs all output to a file, using a timestamped format.

import logging

LOG_FILE = 'prod_audit.log'

# Configure for WARNING level output to a persistent file
logging.basicConfig(
level=logging.WARNING,
filename=LOG_FILE,
filemode='a', # Append to the file
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S' # Custom date format
)

logger = logging.getLogger("AuditService")

logger.info("Startup complete.") # Will NOT be written (level < WARNING)
logger.error("Critical failure during transaction.") # Will be written

Output in prod_audit.log:

2025-12-14 07:08:15 - AuditService - ERROR - Critical failure during transaction.

4. Important Gotcha: basicConfig Runs Only Once

The most crucial rule of logging.basicConfig() is that it must be called before any loggers are created or any logging calls are made.

If the root logger already has handlers attached (which happens if basicConfig() or another configuration function has been called previously), subsequent calls to basicConfig() will be silently ignored.

Incorrect Usage (The Second Call is Ignored):

import logging

# 1. First call sets INFO level
logging.basicConfig(level=logging.INFO)
logging.info("First config is active.")

# 2. Second call tries to set DEBUG level, but is IGNORED
logging.basicConfig(level=logging.DEBUG)
logging.debug("This DEBUG message will NOT show!")

Solution: Only call basicConfig() once at the very start of your application, or use the more advanced logging.config.dictConfig() method for dynamic configuration.

5. Advanced: Custom Time Formatting

The default format for %(asctime)s is ISO 8601-like, but you can specify a precise format using the datefmt parameter, which accepts standard strftime directives.

import logging
import sys

# Configure the format and the date format
logging.basicConfig(
level=logging.INFO,
stream=sys.stdout,
format='%(asctime)s - %(message)s',
datefmt='%Y/%m/%d %I:%M:%S %p' # e.g., 2025/12/14 07:08:15 AM
)

logging.info("Custom time format test.")

Sources and Further Reading

  1. Python Documentation - logging.basicConfig()
  2. Python Documentation - LogRecord Attributes (Format Specifiers)
  3. Python Documentation - strftime Directives (For datefmt)
  4. Real Python - Python Logging Guide (Basic Configuration)