Skip to content

RSPEED-2437: Add configurable log level and unify logging#1148

Open
major wants to merge 4 commits intolightspeed-core:mainfrom
major:mhayden/configurable-log-level
Open

RSPEED-2437: Add configurable log level and unify logging#1148
major wants to merge 4 commits intolightspeed-core:mainfrom
major:mhayden/configurable-log-level

Conversation

@major
Copy link
Contributor

@major major commented Feb 13, 2026

Description

Adds configurable log level via LIGHTSPEED_STACK_LOG_LEVEL environment variable and centralizes all logging through a single get_logger() function in src/log.py.

Commits

  1. feat(logging) — Introduces src/log.py with get_logger() that reads log level from the env var (defaults to INFO), validates the value with a warning on invalid input, and configures RichHandler for consistent console output. The --verbose CLI flag overrides the env var. Moves import sys to top-level in lightspeed_stack.py.

  2. refactor(logging) — Mechanical refactor replacing all logging.getLogger() calls with get_logger(__name__) across 52 modules. No logic or behavioral changes — every file gets the same two-line diff. Reviewable via --stat and spot-checking. Uvicorn logging (src/runners/uvicorn.py) is intentionally excluded.

  3. docs: a2a_protocol.md — Updates stale logger name reference from app.endpoints.handlers to app.endpoints.health.

  4. docs: CLAUDE.md — Updates dev guide logging pattern from logging.getLogger(__name__) to get_logger(__name__).

Type of change

  • Refactor
  • New feature

Tools used to create PR

  • Assisted-by: Claude (code review, fixup commits)
  • Generated by: N/A

Related Tickets & Documents

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Set LIGHTSPEED_STACK_LOG_LEVEL=DEBUG and verify all module loggers output at DEBUG level
  • Set LIGHTSPEED_STACK_LOG_LEVEL=INVALID and verify a warning is printed with fallback to INFO
  • Run with --verbose flag and verify application loggers switch to DEBUG
  • Verify uv run make verify passes (all linters/type checks clean)

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 13, 2026

Warning

Rate limit exceeded

@major has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 19 minutes and 29 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Walkthrough

This PR centralizes logging configuration by replacing the standard logging.getLogger() across ~45 modules with a custom get_logger() factory function. It adds environment-based log level configuration via constants, updates the log.py module to support dynamic log levels with validation and fallback defaults, introduces a --verbose CLI flag for runtime DEBUG logging, and updates tests to validate the new logging behavior.

Changes

Cohort / File(s) Summary
Logger import migration
src/a2a_storage/*, src/app/database.py, src/app/endpoints/*, src/authentication/*, src/authorization/*, src/client.py, src/configuration.py, src/llama_stack_configuration.py, src/models/config.py, src/observability/splunk.py, src/utils/*
Replaced logging.getLogger() with get_logger() from a centralized log module. Removed import logging and added from log import get_logger in each file. No functional changes to logging behavior.
Cache logger name updates
src/cache/cache_factory.py, src/cache/in_memory_cache.py, src/cache/noop_cache.py, src/cache/postgres_cache.py, src/cache/sqlite_cache.py
Updated logger initialization to use __name__ instead of hard-coded logger names (e.g., "cache.cache_factory"), improving logging metadata consistency across cache modules.
Log level configuration
src/constants.py, src/log.py
Added LIGHTSPEED_STACK_LOG_LEVEL_ENV_VAR and DEFAULT_LOG_LEVEL constants. Enhanced get_logger() to read environment-based log level with validation and fallback logic; added RichHandler detection to avoid reconfiguration.
Verbose CLI support
src/lightspeed_stack.py
Introduced --verbose flag that sets log level to DEBUG at runtime; reads LIGHTSPEED_STACK_LOG_LEVEL_ENV_VAR with fallback to DEFAULT_LOG_LEVEL in logging.basicConfig; added validation warning for invalid levels; enabled force=True in config setup.
Startup optimization
src/app/main.py
Removed redundant get_logger("app.endpoints.handlers") call from lifespan startup sequence.
Test coverage
tests/unit/test_log.py, tests/unit/authorization/test_azure_token_manager.py
Added parametrized tests for dynamic log level mapping, environment variable fallback behavior, and invalid level handling. Updated azure token manager test to manage logger propagation for caplog capture.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested labels

ok-to-test

Suggested reviewers

  • tisnik
  • asimurka
  • are-ces
🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Merge Conflict Detection ⚠️ Warning ❌ Merge conflicts detected (56 files):

⚔️ src/a2a_storage/in_memory_context_store.py (content)
⚔️ src/a2a_storage/postgres_context_store.py (content)
⚔️ src/a2a_storage/sqlite_context_store.py (content)
⚔️ src/a2a_storage/storage_factory.py (content)
⚔️ src/app/database.py (content)
⚔️ src/app/endpoints/a2a.py (content)
⚔️ src/app/endpoints/authorized.py (content)
⚔️ src/app/endpoints/config.py (content)
⚔️ src/app/endpoints/conversations_v1.py (content)
⚔️ src/app/endpoints/conversations_v2.py (content)
⚔️ src/app/endpoints/feedback.py (content)
⚔️ src/app/endpoints/health.py (content)
⚔️ src/app/endpoints/info.py (content)
⚔️ src/app/endpoints/mcp_auth.py (content)
⚔️ src/app/endpoints/models.py (content)
⚔️ src/app/endpoints/providers.py (content)
⚔️ src/app/endpoints/query.py (content)
⚔️ src/app/endpoints/rags.py (content)
⚔️ src/app/endpoints/rlsapi_v1.py (content)
⚔️ src/app/endpoints/root.py (content)
⚔️ src/app/endpoints/shields.py (content)
⚔️ src/app/endpoints/streaming_query.py (content)
⚔️ src/app/endpoints/tools.py (content)
⚔️ src/app/main.py (content)
⚔️ src/authentication/__init__.py (content)
⚔️ src/authentication/jwk_token.py (content)
⚔️ src/authentication/k8s.py (content)
⚔️ src/authentication/rh_identity.py (content)
⚔️ src/authorization/azure_token_manager.py (content)
⚔️ src/authorization/middleware.py (content)
⚔️ src/authorization/resolvers.py (content)
⚔️ src/cache/cache_factory.py (content)
⚔️ src/cache/in_memory_cache.py (content)
⚔️ src/cache/noop_cache.py (content)
⚔️ src/cache/postgres_cache.py (content)
⚔️ src/cache/sqlite_cache.py (content)
⚔️ src/client.py (content)
⚔️ src/configuration.py (content)
⚔️ src/constants.py (content)
⚔️ src/lightspeed_stack.py (content)
⚔️ src/llama_stack_configuration.py (content)
⚔️ src/log.py (content)
⚔️ src/models/config.py (content)
⚔️ src/observability/splunk.py (content)
⚔️ src/utils/llama_stack_version.py (content)
⚔️ src/utils/mcp_auth_headers.py (content)
⚔️ src/utils/mcp_headers.py (content)
⚔️ src/utils/query.py (content)
⚔️ src/utils/responses.py (content)
⚔️ src/utils/shields.py (content)
⚔️ src/utils/token_counter.py (content)
⚔️ src/utils/tool_formatter.py (content)
⚔️ src/utils/transcripts.py (content)
⚔️ tests/unit/authentication/test_rh_identity.py (content)
⚔️ tests/unit/authorization/test_azure_token_manager.py (content)
⚔️ tests/unit/test_log.py (content)

These conflicts must be resolved before merging into main.
Resolve conflicts locally and push changes to this branch.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'RSPEED-2437: Add configurable log level and unify logging' accurately and concisely summarizes the PR's primary objectives: adding environment-variable-controlled log levels and centralizing logging across the codebase via get_logger().
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/app/endpoints/health.py (1)

18-29: ⚠️ Potential issue | 🟡 Minor

Update documentation reference to new endpoint logger names.

The logger name change from shared "app.endpoints.handlers" to per-module names (e.g., "app.endpoints.health") is reflected in code, but documentation in docs/a2a_protocol.md still references the old logger name. Update this reference to ensure monitoring and log filtering guidance remains accurate for users checking endpoint logs.

No Python code actively references the old logger name, so the change is localized to configuration and documentation updates.

🧹 Nitpick comments (4)
src/utils/token_counter.py (1)

4-6: Coding guideline deviation: get_logger(__name__) replaces the mandated logging.getLogger(__name__) pattern.

The project coding guidelines specify: "Use logger = logging.getLogger(__name__) pattern for module logging". This PR intentionally replaces that pattern across ~45 modules. The new get_logger wrapper internally delegates to logging.getLogger(name), so it's functionally compatible, but the guideline text should be updated to reflect the new convention (e.g., in CLAUDE.md or equivalent) to avoid confusion in future reviews.

This applies to all 8 files in this PR and the ~35 other modules mentioned in the commit description.

As per coding guidelines: Use logger = logging.getLogger(__name__) pattern for module logging.

tests/unit/authorization/test_azure_token_manager.py (1)

139-147: Correct workaround for propagate=False, but consider extracting a reusable fixture.

The try/finally to toggle propagate is necessary because get_logger disables propagation (which prevents caplog from capturing log records). This is correct, but if other tests face the same issue, a shared pytest fixture (or context manager) that temporarily enables propagation would reduce boilerplate and risk of copy-paste errors.

♻️ Optional: reusable context manager
# conftest.py or a test utility module
from contextlib import contextmanager
import logging

`@contextmanager`
def propagate_logger(name: str):
    """Temporarily enable propagation on a logger so caplog can capture records."""
    log = logging.getLogger(name)
    log.propagate = True
    try:
        yield log
    finally:
        log.propagate = False

Usage:

with propagate_logger("authorization.azure_token_manager"):
    with caplog.at_level("WARNING"):
        result = token_manager.refresh_token()
        assert result is False
        assert "Failed to retrieve Azure access token" in caplog.text
src/lightspeed_stack.py (2)

22-34: Duplicate log-level validation logic with src/log.py.

Lines 22–32 replicate the same env-var read → getattr validate → fallback flow that get_logger() in src/log.py (lines 32–42) already performs. If the validation rules ever diverge (e.g., supporting custom level names), you'd need to update both places.

Consider extracting a shared helper (e.g., resolve_log_level() -> int) in log.py that both call sites can use.


26-31: Move import sys to the top of the file.

Placing a stdlib import inside a conditional block at module level is unconventional. Since this code runs unconditionally at import time (module-level if), sys should be with the other imports at the top.

Proposed fix
 import logging
 import os
+import sys
 from argparse import ArgumentParser

Then at line 26–27:

-    import sys
-
     print(

…VEL env var

This commit introduces runtime-configurable logging via the LIGHTSPEED_STACK_LOG_LEVEL environment variable, allowing deployment-time control of log verbosity without code changes.

Key changes:
- Added LIGHTSPEED_STACK_LOG_LEVEL_ENV_VAR and DEFAULT_LOG_LEVEL constants
- Modified get_logger() to read log level from environment with defensive validation
- Updated lightspeed_stack.py basicConfig() to respect the environment variable
- Added force=True to basicConfig() to override llama_stack_client's early logging setup
- Revived --verbose CLI flag to set DEBUG level and update all existing loggers
- Added comprehensive unit tests covering default, custom, case-insensitive, invalid, and all valid log levels

The --verbose flag now provides a convenient CLI shortcut for enabling debug logging, while the environment variable enables fine-grained control in containerized deployments.

Signed-off-by: Pavel Tišnovský <ptisnovs@redhat.com>
Signed-off-by: Major Hayden <major@redhat.com>
@major major force-pushed the mhayden/configurable-log-level branch 2 times, most recently from ca3b5ad to 121dfcc Compare February 13, 2026 15:59
All 43+ modules now use the centralized get_logger() function from log.py, ensuring consistent log level configuration via the LIGHTSPEED_STACK_LOG_LEVEL environment variable. Non-standard logger names have been standardized to __name__ for clarity and consistency across the codebase.

Signed-off-by: Major Hayden <major@redhat.com>
Signed-off-by: Major Hayden <major@redhat.com>
Signed-off-by: Major Hayden <major@redhat.com>
@major major force-pushed the mhayden/configurable-log-level branch from 121dfcc to c5aed53 Compare February 13, 2026 15:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant