Skip to content
Ame edited this page Jun 12, 2025 · 5 revisions

Usage

This page provides instructions and examples on how to use the akeoott_logging_config library to configure logging in your Python application.

Quick Start

The core of the library is the LogConfig class. You instantiate it and then call the setup() method to configure your logger.

It's recommended to place your logging configuration in a separate file (e.g., logging_setup.py) and import the configured logger into other parts of your application.

logging_setup.py

# logging_setup.py for configuring logging via the akeoott_logging_config library.

from akeoott_logging_config import LogConfig
import logging

def setup_main_logger():
    """Configures and returns the main application logger."""
    # 1. Create a LogConfig instance. 
    # Giving it a unique name allows for separate configurations if you use multiple loggers.
    log_config = LogConfig(logger_name="MainAppLogger")

    # 2. Configure the logger using the setup() method.
    log_config.setup(
        print_log=True,         # Log to the console
        save_log=False,         # Do not save logs to a file
        log_level=logging.INFO  # Set the minimum level to INFO
    )

    # 3. Return the configured logger instance.
    return log_config.logger

# Create the logger instance to be imported by other modules
log = setup_main_logger()

main.py

# Import the configured logger from your setup file.
from logging_setup import log

def main():
    log.info("Application has started.")
    # ... your application logic ...
    log.debug("This is a debug message and will not be shown because the level is INFO.")
    log.warning("Something potentially unexpected happened.")
    # ... more logic ...
    log.info("Application is shutting down.")

if __name__ == "__main__":
    main()

Output

INFO (2025-06-12 08:52:49.123)     [MainAppLogger] Logging to console activated. [Line: 88 in logging_config.py - setup]
INFO (2025-06-12 08:52:49.123)     [MainAppLogger] Logging configured. Level: INFO [Line: 122 in logging_config.py - setup]
INFO (2025-06-12 08:52:49.124)     Application has started. [Line: 5 in main.py - main]
WARNING (2025-06-12 08:52:49.124)   Something potentially unexpected happened. [Line: 8 in main.py - main]
INFO (2025-06-12 08:52:49.124)     Application is shutting down. [Line: 10 in main.py - main]

Detailed Configuration

The LogConfig class is initialized with a logger_name, and its behavior is defined by the parameters passed to the setup() method.

LogConfig(logger_name)

  • logger_name (str): A unique name for the logger instance. If you create multiple LogConfig objects with the same name, they will all configure the same underlying logging.Logger object. Defaults to "AkeoottLogger".

setup() Parameters

The setup() method configures the logger instance.

  • activate_logging (bool): Enables or disables all logging for this instance. If False, no messages will be processed. Defaults to True.
  • print_log (bool): If True, logs are sent to the console (sys.stderr). Defaults to True.
  • save_log (bool): If True, logs are written to a file. Defaults to False.
  • log_file_path (str | Path | None): Specifies the directory or full path for the log file.
    • If None (default), the log file is saved in the current working directory.
    • If a directory path (e.g., "./logs"), the file will be created inside that directory with the name specified by log_file_name.
    • If 'script_dir', the log file is saved in the same directory as the main execution script (sys.modules['__main__']). This is useful for keeping logs with your application source.
  • log_file_name (str): The name of the log file. Defaults to "logs.log".
  • log_level (int): The minimum level of messages to log (e.g., logging.DEBUG, logging.INFO, logging.WARNING). Defaults to logging.INFO.
  • log_format (str): The format string for log records. See Python's logging documentation for attributes. Defaults to '%(levelname)s (%(asctime)s.%(msecs)03d) %(message)s [Line: %(lineno)d in %(filename)s - %(funcName)s]'.
  • date_format (str): The format string for the date and time in log records. Defaults to '%Y-%m-%d %H:%M:%S'.
  • log_file_mode (str): The mode for opening the log file. Use 'a' to append (default) or 'w' to overwrite the file on each run.
  • thirdparty_logger_target (str | None): The name of a third-party logger (e.g., from an imported library) that you want to silence or control.
  • thirdparty_logger_level (int): The logging level to set for the targeted third-party logger. The default (logging.CRITICAL + 1) effectively disables it.

Examples

Logging to a File

This example configures the logger to save all messages of level DEBUG and higher to a file named app.log in a logs subdirectory.

from akeoott_logging_config import LogConfig
import logging
from pathlib import Path

# Ensure the log directory exists
Path("logs").mkdir(exist_ok=True)

log_config = LogConfig(logger_name="FileLogger")
log_config.setup(
    print_log=False,                # Disable console logging
    save_log=True,                  # Enable file logging
    log_file_path="logs",           # Directory to save the file in
    log_file_name="app.log",        # Name of the log file
    log_file_mode='w',              # Overwrite the log on each run
    log_level=logging.DEBUG         # Log everything from DEBUG upwards
)

log = log_config.logger

log.debug("This is a detailed debug message for the file.")
log.info("The application is running smoothly.")

Using Multiple Loggers

You can configure different loggers for different parts of your application by using distinct logger_name values.

from akeoott_logging_config import LogConfig
import logging

# Configure the main application logger
app_log_config = LogConfig(logger_name="MyApplication")
app_log_config.setup(print_log=True, log_level=logging.INFO)
app_logger = app_log_config.logger

# Configure a separate logger for a specific component, like networking
net_log_config = LogConfig(logger_name="Networking")
net_log_config.setup(
    print_log=True, 
    save_log=True, 
    log_file_name="network.log", 
    log_level=logging.DEBUG
)
net_logger = net_log_config.logger


app_logger.info("Main application has started.")
net_logger.debug("Establishing connection to server...")
net_logger.info("Connection successful.")
app_logger.info("Main application is now shutting down.")

Silencing Third-Party Loggers

If a library you are using (e.g., requests) is producing too much log output, you can silence it.

from akeoott_logging_config import LogConfig
import logging
import requests # A library that does its own logging

# The requests library uses a logger named 'urllib3' which can be very verbose
log_config = LogConfig(logger_name="MyApp")
log_config.setup(
    print_log=True,
    log_level=logging.INFO,
    thirdparty_logger_target="urllib3", # Target the noisy logger
    thirdparty_logger_level=logging.WARNING # Only show WARNING and above from it
)

log = log_config.logger

log.info("Making a web request.")
# You will not see the DEBUG logs from urllib3, only your own log messages
# and any warnings/errors from urllib3.
try:
    requests.get("https://www.google.com")
    log.info("Request successful.")
except requests.exceptions.RequestException as e:
    log.error(f"Request failed: {e}")
Clone this wiki locally