Skip to main content

Python Logging Basic Configuration

Know how configure python logging module

Published 7 min readMarkdown
Part of seriesThe Definitive Guide to Python Logging Series

Basic configuration in python logging module is done through basicConfig function. basicConfig function accepts parameters through which handlers are created and configured. Configuration done through basicConfig is applied to all logging objects. It is the most efficient and effective way of configuring logging in simple python application.

Log Level

By default python logging module records messages from WARING level. In order to record INFO or DEBUG level logs, it is to be configured. basicConfig function accepts level parameter that sets the logging level.

import logging

logging.info('hello') # Does nothing

logging.basicConfig(
    level=logging.INFO
)

logging.info('hello') 
# Log record
# INFO:root:hello

If developer wants to log DEBUG level message then log level has to be set as logging.DEBUG.

Format Message

Developer can format log records by passing string to the format parameter. The format parameter accepts a string that can be formatted later for generating the records. So string-formatter is the underlying concept here.

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
)

logging.info('hello')

# Log record
# 2025-09-20 22:45:53,612 [INFO] - hello - root

In the table below all the inbuilt acceptable attribute names for log formatting is given (The table is copied directly from python documentation link)

Attribute nameFormatDescription
asctime%(asctime)sHuman-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).
created%(created)fTime when the LogRecord was created (as returned by time.time_ns() / 1e9).
exc_infoYou shouldn’t need to format this yourself.Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
filename%(filename)sFilename portion of pathname.
funcName%(funcName)sName of function containing the logging call.
levelname%(levelname)sText logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
levelno%(levelno)sNumeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
lineno%(lineno)dSource line number where the logging call was issued (if available).
message%(message)sThe logged message, computed as msg % args. This is set when Formatter.format() is invoked.
module%(module)sModule (name portion of filename).
msecs%(msecs)dMillisecond portion of the time when the LogRecord was created.
name%(name)sName of the logger used to log the call.
pathname%(pathname)sFull pathname of the source file where the logging call was issued (if available).
process%(process)dProcess ID (if available).
processName%(processName)sProcess name (if available).
relativeCreated%(relativeCreated)dTime in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
stack_infoYou shouldn’t need to format this yourself.Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.
thread%(thread)dThread ID (if available).
threadName%(threadName)sThread name (if available).
taskName%(taskName)sasyncio.Task name (if available).

Format Styling

As string formatting is used, developer can use either of three styles of python string formatting. Be default logging module uses the % style. Here attributes are written as %(atribute_name)s. The other two styles are { and $.

First see an example with { style

import logging

logging.basicConfig(
    level=logging.INFO,
    format='{asctime} [{levelname}] - {message} - {name}',
    style='{'
)

logging.info('hello')

# Log record
# 2025-09-20 22:58:34,441 [INFO] - hello - root

Example of $ style

import logging

logging.basicConfig(
    level=logging.INFO,
    format='$asctime [$levelname] - $message - $name',
    style='$'
)

logging.info('hello')

# Log record
# 2025-09-20 22:58:34,441 [INFO] - hello - root

Date-format

In python logging module developer can change the how asctime is formatted. It uses the standard ISO 8601 date format. Logging module accepts datefmt parameter to format the asctime date.

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S'
)

logging.info('hello')

# Log record
# 20-09-2025 23:07:05 [INFO] - hello - root

Handlers

When no handler is specified basicConfig creates a stream handler and assigns it to the root logger. But a developer can assign a custom handler to the root logger. Handler will be discussed in detail later. But this example shows how a developer can assign one or multiple to the logger through basicConfig.

import logging
import sys

class PrintLog(logging.Handler):
    """Prints log record in console"""
    def emit(self, record):
        data = self.format(record)
        sys.stdout.write(data + '\n')

class StoreLogInFile(logging.Handler):
    """Writes log record in access.log file"""
    def emit(self, record):
        data = self.format(record)
        with open('access.log', 'a') as file:
            file.write(data + '\n')

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S',
    handlers=[PrintLog(), StoreLogInFile()]
)

logging.info('hello')

# Log record
# 20-09-2025 23:14:36 [INFO] - hello - root

access.log

20-09-2025 23:14:36 [INFO] - hello - root

The format and style mentioned is followed by both the handlers.

File Handler

By default logging module uses StreamHandler to print logs on terminal. But developer can store the log records in a file as well. basicConfig accepts a file path in filename parameter. If the file does not exist, it is created at runtime.

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S',
    filename='access.log'
)

logging.info('hello') # Store log record in access.log file

access.log

20-09-2025 23:14:36 [INFO] - hello - root

File Mode

By default the file is opened in append mode. So new lines are added with new log records. But a developer can also use

ModeDescription
wOpen file in write mode. Rewrites the file with every log record
aAppends new record in new line
xExclusive creation. If the mentioned file exists, logging fails.

There is not need to change the file mode, default mode append should be feasible for almost all the scenarios.

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S',
    filename='access.log',
    filemode='a'
)

logging.info('hello')

Encoding

Using basicConfig developer can configure which encoding technique is used to write the record in file. Most effective one is utf-8. Other common encoding are

  • utf-8 - Universal, supports all Unicode characters (recommended)

  • ascii - Basic English characters only (0-127)

  • latin-1 (iso-8859-1) - Western European characters

  • cp1252 - Windows Western European (superset of latin-1)

  • cp1251 - Windows Cyrillic

  • shift_jis - Japanese

Encoding works if filename is provided. This means encoding is not applied for StreamHandler assigned to the root logger by default.

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S',
    filename='access.log',
    filemode='a',
    encoding='latin-1'
)

logging.info('Windows-specific: … † ‡ • ‰')

access.log

20-09-2025 23:39:58 [INFO] - Windows-specific: \u2026 \u2020 \u2021 \u2022 \u2030 - root

Errors

Errors specify how to handle encoding errors when writing log record on to a file. This works only with filename provided. Default errors value is backslashreplace. But other options are

Error handlerDescriptionExample
ignoreSkip invalid characters"café" → "caf"
replaceReplace with ? or �"café" → "caf?"
strictRaise UnicodeEncodeErrorThrows Exception
xmlcharrefreplaceXML character references"café" → "café"
backslashreplacePython escape sequences"café" → "caf\xe9"
import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S',
    filename='access.log',
    filemode='a',
    encoding='latin-1',
    errors='replace'
)

logging.info('Windows-specific: … † ‡ • ‰')

access.log

20-09-2025 23:46:43 [INFO] - Windows-specific: ? ? ? ? ? - root

Stream

Python logging module is so configurable that developer can customize the default StreamHandler with a desired stream. Stream can be stdout or StringIO.

import logging
import sys

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S',
    stream=sys.stdout
)

logging.info('Windows-specific: … † ‡ • ‰')

# Log record
# 20-09-2025 23:51:20 [INFO] - Windows-specific: … † ‡ • ‰ - root
import logging
import sys
from io import StringIO

si = StringIO()

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s - %(name)s',
    datefmt='%d-%m-%Y %H:%M:%S',
    stream=si
)

logging.info('Windows-specific: … † ‡ • ‰') # Does not print line on terminal
logging.info('A new line') # Does not print line on terminal

si.seek(0)

print(si.read()) # prints both the log record

About the author

  • As a seasoned senior web developer with a wealth of experience in Python, Javascript, web development, MySQL, MongoDB, and React, I am passionate about crafting exceptional digital experiences that delight users and drive business success.

No comments yet. Be the first to comment.

The Definitive Guide to Python Logging Series

Part 3 of 4

This blog series is a comprehensive guide to Python's logging module, explaining core concepts and best practices.

Up nextPython Logging Dict ConfigurationLearn how to use logging.cofig.dictConfig in your application