Skip to main content

A Python module (with the help of coloredlogs) to add color to logs.

This project has been archived.

The maintainers of this project have marked this project as archived. No new releases are expected.

Project description

SCLogging

made-with-python Documentation Status License: MIT PyPI version

A small, convenient wrapper around Python’s logging that makes it easy to:

  • Bootstrap a ready-to-use logger with sensible defaults
  • Optionally log to a rotating file in addition to the console
  • Apply per-module/per-library log levels
  • Use a simple Timer helper to measure and report elapsed time
  • Centralize configuration (including colors and formatting)

The primary entry points are:

  • get_logger(...) — create or retrieve a configured logger
  • set_config({...}) — write a simple TOML-backed configuration
  • Timer — a helper class to time code blocks and log results

Note: This README focuses on the public API and how to use it. Internal implementation details are intentionally omitted.

Full documentation: https://sclogging.readthedocs.io/en/latest/

Docs Navigation

Build Docs Locally

Install project and docs dependencies:

python -m pip install -e ".[docs]"

or, using the pinned requirements files in this repository:

python -m pip install -r requirements.txt -r docs/requirements.txt

Build Sphinx docs with warnings treated as errors:

$env:SPHINXOPTS='-W --keep-going -n'
.\docs\make.bat html

Alternative direct Sphinx command:

python -m sphinx -W -b html docs/source docs/build/html

Generated HTML is written to docs/build/html. For contributor-specific workflow details, see CONTRIBUTING.md.

Why SCLogging?

SCLogging aims to simplify common logging tasks:

  • One-liner to get a ready-to-use logger
  • Easy switch to also log to a file (with an auto-created directory if needed)
  • Uniform formatting and colorized console output for readability
  • Fine-grained control over noisy third-party libraries
  • Lightweight timing utility for quick performance measurements

Quick Start

Basic usage:

# Python
from sclogging.sclogging_main import get_logger

logger = get_logger(__name__)
logger.info("Hello from SCLogging!")
logger.warning("Heads up...")
logger.error("Something went wrong.")

Add a timed section:

# Python
from sclogging.sclogging_main import get_logger, Timer

logger = get_logger(__name__)

t = Timer(logger=logger, level="INFO")  # level is optional; INFO is a common choice
t.start_timer("Loading data")
# ... your work here ...
t.stop_timer("Loading data complete")

Configuration

You can set configuration in two ways:

  1. Programmatically via set_config:
# Python
from sclogging.sclogging_main import set_config, get_logger

set_config({
    # Write these values into a TOML settings file used by SCLogging.
    # Typical options:
    "logging_log_to_file": True,               # Whether to also log to a file
    "logging_path": "C:\\Logs",                # Where to store log files (auto-created if enabled)
    "logging_level": "INFO",                   # Default console log level
    "logging_file_level": "WARNING",           # Default file log level
    "logging_ext": "log",                      # Log file extension (e.g., .log)
    "logging_auto_create_dir": True,           # Auto-create log directory if not present

    # Visuals
    "spacer": "_",                             # Spacer used in formatted output
    "spacer_color": "LIGHTBLACK_EX",           # Color name for spacer (console)

    # Reduce noise from third-party libraries
    "specific_loggers": {
        "urllib3": "WARNING",
        "selenium": "WARNING",
        "xhtml2pdf": "WARNING",
    },
})

logger = get_logger(__name__)
logger.info("Configured and ready!")
  1. Via a settings file:
  • SCLogging looks for a TOML-based settings file that stores the same keys shown above.
  • Use set_config to generate/update this file programmatically, or manage it yourself alongside your project if preferred.

Notes:

  • Log directory auto-creation is controlled by logging_auto_create_dir.
  • When logging_log_to_file is True, logs will be written under logging_path with the extension logging_ext.
  • Per-library overrides in specific_loggers help keep the console/file outputs tidy.

Security Notes

  • SCLogging rejects unsafe log directories (for example home/root/project-critical paths) before creating or clearing logs.
  • Logger names are sanitized before they are used in log filenames, which helps prevent path traversal through caller_name.
  • Log directories/files are created with best-effort restrictive permissions (700 for directories and 600 for files when the platform supports it).
  • set_config() writes to src/sclogging/settings.toml; config writes are guarded to avoid writes outside the module settings directory or through symlinks.
  • These checks are guardrails, not a full sandbox: still avoid passing untrusted input directly into logging/config APIs.

API Overview

  • get_logger(name: str, ...) -> logging.Logger

    • Returns a logger configured according to your settings. Typically called with name to inherit the calling module’s name.
  • set_config(config_data: dict) -> None

    • Writes configuration into the project’s SCLogging settings file (TOML). Accepts keys such as:
      • logging_log_to_file: bool
      • logging_path: str
      • logging_level: str
      • logging_file_level: str
      • logging_ext: str
      • logging_auto_create_dir: bool
      • spacer: str
      • spacer_color: str
      • specific_loggers: dict[str, str]
  • class Timer(logger=None, level="INFO", ...)

    • start_timer(context: str | None = None) -> None
    • stop_timer(context: str | None = None) -> None
    • A simple timing helper. Call start_timer before the work you want to measure and stop_timer when done. If a logger is provided, timing information is logged automatically at the configured level.

Additional helpers exist internally to handle formatting, name filtering, and color output to keep logs readable.

Practical Examples

  • Minimal setup for a script:
# Python
from sclogging.sclogging_main import get_logger

log = get_logger(__name__)
log.info("Starting script...")
# ... work ...
log.info("Done.")
  • Enable file logging and tune third-party verbosity once for the whole app:
# Python
from sclogging.sclogging_main import set_config, get_logger

set_config({
    "logging_log_to_file": True,
    "logging_auto_create_dir": True,
    "logging_path": "C:\\Logs",
    "logging_level": "INFO",
    "logging_file_level": "WARNING",
    "logging_ext": "log",
    "specific_loggers": {"urllib3": "WARNING", "selenium": "WARNING"},
})

app_log = get_logger("my_app")
app_log.info("Application start")
  • Timing a function call:
# Python
from sclogging.sclogging_main import get_logger, Timer

log = get_logger(__name__)

def compute():
    t = Timer(logger=log, level="INFO")
    t.start_timer("compute()")
    # heavy work here...
    t.stop_timer("compute() completed")

compute()

Tips

  • Use name as the logger name to get a hierarchical logger corresponding to your module path.
  • Lower the verbosity of noisy dependencies with specific_loggers to keep outputs focused.
  • If you enable file logging, ensure logging_path is accessible and, if needed, let SCLogging create it for you via logging_auto_create_dir.

License

This project is released under the terms of its included LICENSE. See the LICENSE file for details.

Contributing

Issues and contributions that improve documentation, configuration options, or ergonomics are welcome. Before submitting changes, please ensure your updates maintain backwards compatibility and include concise examples when applicable.

Security

Please see SECURITY.md for guidelines on reporting vulnerabilities.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sclogging-1.3.0.tar.gz (13.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sclogging-1.3.0-py3-none-any.whl (17.0 kB view details)

Uploaded Python 3

File details

Details for the file sclogging-1.3.0.tar.gz.

File metadata

  • Download URL: sclogging-1.3.0.tar.gz
  • Upload date:
  • Size: 13.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for sclogging-1.3.0.tar.gz
Algorithm Hash digest
SHA256 bc7090a66982afc7211f9541bf2a25b17859b601d52fc8cac700682f84581df2
MD5 eefe35c318ee912c2417d629fc198ece
BLAKE2b-256 c99e223cb13e16fe9a4ac12538a535394e60379483bff69b350ead4ec2fcc6bb

See more details on using hashes here.

File details

Details for the file sclogging-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: sclogging-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 17.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for sclogging-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6270f6a284939be6eb7236e11d22a0450815db0cdaf193be83af6339663f197e
MD5 8435c280047df5fdb4bd49e3b1cb801a
BLAKE2b-256 b8e5478d12b7903a715e36b8188264c1e7578728dfa1c5dd55b043f176481978

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page