Skip to content

pick the earliest-occurring level keyword in detect_log_level - #23

Open
HrachShah wants to merge 4 commits into
mainfrom
fix/detect-log-level-pick-earliest-match
Open

pick the earliest-occurring level keyword in detect_log_level#23
HrachShah wants to merge 4 commits into
mainfrom
fix/detect-log-level-pick-earliest-match

Conversation

@HrachShah

@HrachShah HrachShah commented Jun 25, 2026

Copy link
Copy Markdown
Owner

What

utils.detect_log_level returns the first regex match in a hardcoded
CRITICAL > ERROR > WARNING > INFO > DEBUG > TRACE order, regardless of
where the keyword actually appears in the line.

Repro

Summary by Sourcery

Update log level detection to choose the earliest-occurring level keyword in a log line and add unit tests to cover the new behavior and edge cases.

Bug Fixes:

  • Fix misclassification of log lines that contain multiple log level keywords by selecting the leftmost match instead of a fixed severity order.

Tests:

  • Add unit tests for detect_log_level covering earliest-match selection, case insensitivity, timestamped lines, non-level lines, and ignoring substring matches.

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of JSON input by rejecting non-object values that cannot represent valid log records.
    • Added support for timestamps with fractional seconds and timezone offsets, including UTC Z notation.
    • Improved log-level detection when multiple levels appear in the same line by selecting the earliest matching keyword.
    • Prevented log-level detection from matching keywords embedded within larger words.
  • Tests

    • Expanded coverage for invalid JSON records, timestamp formats, and log-level detection scenarios.

detect_log_level walked a hardcoded list of (regex, level) tuples in
CRITICAL > ERROR > WARNING > INFO > DEBUG > TRACE order and returned
the first patternprecedence — whichever keyword appears first in the line is the
intent of the line. Without this, '2024-01-15 10:23:45 WARNING cannot
connect to CRITICAL service' was classified as CRITICAL even though
the line is a WARNING. The fix runs every level regex, finds the
leftmost match across all of them, and returns the level that owns
that match. A new tests/test_utils.py pins the new contract: the
leftmost keyword wins, embedded levels in later words do not
override, and words like 'ERROR_RATE' or 'CRITICAL_ERROR' (which
contain the level as a prefix of a longer identifier) are correctly
ignored because the pattern uses \b boundaries.
@sourcery-ai

sourcery-ai Bot commented Jun 25, 2026

Copy link
Copy Markdown

Reviewer's Guide

Update log level detection to choose the earliest-occurring level keyword in a line instead of a fixed severity order, and add unit tests covering the new behavior and existing edge cases.

Flow diagram for updated detect_log_level logic

flowchart TD
    A[detect_log_level line] --> B[Convert line to uppercase line_upper]
    B --> C[Initialize earliest_level = None]
    C --> D[Initialize earliest_index = infinity]
    D --> E[Iterate level_patterns]
    E --> F[re.finditer pattern line_upper]
    F --> G{Any matches?}
    G -->|No| H{More patterns?}
    H -->|Yes| E
    H -->|No| I{earliest_level is not None?}
    G -->|Yes| J[Take first_match.start]
    J --> K{first_match.start < earliest_index?}
    K -->|Yes| L[Update earliest_index and earliest_level]
    K -->|No| H
    L --> H
    I -->|Yes| M[Return earliest_level]
    I -->|No| N[Return UNKNOWN]
Loading

File-Level Changes

Change Details Files
Change log level detection to select the leftmost matching level keyword rather than the first match in a fixed severity-ordered pattern list.
  • Update detect_log_level docstring to describe earliest-occurring keyword behavior.
  • Introduce tracking variables earliest_level and earliest_index initialized to None and infinity, respectively.
  • Replace re.search with re.finditer to collect all matches for each level pattern in the input line.
  • Choose the level whose first match has the smallest start index across all patterns and return it if any match was found.
  • Preserve UNKNOWN as the default return value when no level keyword is present.
src/log_analyzer_cli/utils.py
Add unit tests to validate the new earliest-match behavior and guard existing behaviors like case-insensitivity and word-boundary matching.
  • Add tests for simple level keyword detection, including abbreviations like WARN, CRIT, and ERR.
  • Add tests for timestamp-prefixed log lines to ensure detection after leading timestamps.
  • Add tests verifying that when multiple level keywords are present, the earliest (leftmost) one is chosen, including cases where it is higher severity.
  • Add tests ensuring lines without level keywords return UNKNOWN, including empty and whitespace-only strings.
  • Add tests confirming that word-boundary-based patterns do not match level substrings inside other identifiers and that detection remains case-insensitive.
tests/test_utils.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • You don't need to materialize all matches with list(re.finditer(...)); using next(re.finditer(...), None) and checking that single result would avoid unnecessary allocations while still letting you compare positions.
  • Consider avoiding float('inf') for earliest_index and instead initializing it to None and adjusting the comparison logic, which can make the intent clearer and removes reliance on magic sentinel values.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- You don't need to materialize all matches with `list(re.finditer(...))`; using `next(re.finditer(...), None)` and checking that single result would avoid unnecessary allocations while still letting you compare positions.
- Consider avoiding `float('inf')` for `earliest_index` and instead initializing it to `None` and adjusting the comparison logic, which can make the intent clearer and removes reliance on magic sentinel values.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The changes validate JSON parser inputs, expand timezone-aware timestamp formats, and update log-level detection to choose the earliest keyword match. Unit tests cover non-record JSON values, timestamp offsets, UTC markers, keyword precedence, case handling, and word boundaries.

Changes

Log parsing behavior

Layer / File(s) Summary
JSON record validation
src/log_analyzer_cli/parsers/json_log.py, tests/test_parsers.py
JSONLogParser.parse now returns None for non-dictionary JSON values, with tests for arrays, null, numbers, and strings.
Timestamp and level detection
src/log_analyzer_cli/utils.py, tests/test_utils.py
Timestamp parsing accepts fractional timezone offsets, while log-level detection selects the earliest matching keyword and is covered by unit tests for precedence, case, boundaries, and unknown lines.

Estimated code review effort: 3 (Moderate) | ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: detect_log_level now chooses the earliest-occurring log level keyword.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/detect-log-level-pick-earliest-match

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/log_analyzer_cli/utils.py (1)

148-154: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Optimize first-match discovery to prevent scanning the entire line.

Using list(re.finditer(...)) forces the regex engine to parse the entire line for all occurrences and allocates a list, even though only the first match is needed. Using re.search(...) achieves the exact same result but stops scanning at the first match, significantly improving performance on long log lines.

♻️ Proposed refactor
-    for pattern, level in level_patterns:
-        matches = list(re.finditer(pattern, line_upper))
-        if matches:
-            first_match = matches[0]
-            if first_match.start() < earliest_index:
-                earliest_index = first_match.start()
-                earliest_level = level
+    for pattern, level in level_patterns:
+        match = re.search(pattern, line_upper)
+        if match and match.start() < earliest_index:
+            earliest_index = match.start()
+            earliest_level = level

(Optional: For even greater performance, consider combining the keywords into a single module-level compiled regex like re.compile(r'\b(CRITICAL|ERROR|...)\b') to find the absolute earliest match in a single pass without iterating through multiple patterns.)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/log_analyzer_cli/utils.py` around lines 148 - 154, Replace
list(re.finditer(pattern, line_upper)) in the level-pattern matching logic with
re.search(pattern, line_upper), then use the returned match directly to update
earliest_index and earliest_level while preserving the existing earliest-match
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/log_analyzer_cli/utils.py`:
- Around line 148-154: Replace list(re.finditer(pattern, line_upper)) in the
level-pattern matching logic with re.search(pattern, line_upper), then use the
returned match directly to update earliest_index and earliest_level while
preserving the existing earliest-match behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2d78550e-bb6f-40b9-8dc3-0a5904ae7fcc

📥 Commits

Reviewing files that changed from the base of the PR and between e93757f and ba38bfa.

📒 Files selected for processing (4)
  • src/log_analyzer_cli/parsers/json_log.py
  • src/log_analyzer_cli/utils.py
  • tests/test_parsers.py
  • tests/test_utils.py

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