Log coverage analyzer

From openharmonyinsight/openharmony-skills · View interactive version

Log coverage analyzer is an AI agent skill from the GitHub repository openharmonyinsight/openharmony-skills. Analyze code repository logging coverage to ensure all function branches have LOGE/LOGI logs and identify high-frequency log risks. Supports multiple programming languages (C++, Java, Python, JavaScript, etc.)

How to use this skill

Skill file

This skill performs comprehensive log coverage analysis for code repositories. It identifies logging deficiencies in call chains and detects high-frequency log risks that may impact performance.

Analysis Principles

Log Level Definitions

| Log Level | Behavior | Use Case |

|-----------|----------|----------|

| LOGE | Always prints, never lost | Critical - Must exist on all error return paths |

| LOGI | Always prints, may be lost if high-frequency triggered at same location | Important - Success paths, key operations |

| LOGD | Only prints when debug switch enabled | Optional - Debug information only |

| LOGW | Only prints when debug switch enabled | Optional - Warning information only |

Core Analysis Rules

  1. Log Coverage Rule: Each branch in a function call chain must have LOGE or LOGI level logging
  2. High-Frequency Risk Rule: Functions that may be called frequently (loops, timers, callbacks, event handlers) with LOGE/LOGI logs pose performance risks
  3. Error Path Rule: All error return paths MUST have LOGE logging
  4. Context Rule: All logs must include sufficient context information (IDs, states, parameters)

Execution Workflow

Step 00: Create Analysis Plan

Description: Create detailed analysis plan before starting

Actions:

Output: Analysis plan created via TodoWrite tool

Step 01: Discover Source Files

Description: Find all relevant source files in the repository

Actions:

Output: List of source files to analyze

Step 02: Scan Logging Patterns

Description: Scan all source files for logging macros/functions

Actions:

Output: Log statistics per file

Step 03: Extract Functions and Call Chains

Description: Parse source files to extract function definitions and call relationships

Actions:

Output: Function list with call relationships

Step 04: Analyze Log Coverage per Branch

Description: Check each branch in call chains for required logging

Actions:

Deficiency Classification:

Output: List of log deficiencies with locations

Step 05: Detect High-Frequency Log Risks

Description: Identify functions with LOGE/LOGI that may be called frequently

Actions:

Risk Classification:

Output: List of high-frequency risks with locations

Step 06: Generate Analysis Report

Description: Create comprehensive analysis report with all findings

Actions:

1. Summary statistics

2. Log deficiencies with fix suggestions

3. High-frequency risks with fix suggestions

4. Call chain analysis

5. Detailed code examples

Output: Complete analysis report

Language-Specific Patterns

C/C++

Function Definition Patterns:

[return_type] [class::]function_name([parameters]) {
[\w\s:*,]*\{

Log Patterns:

Java

Function Definition Patterns:

(public|private|protected)?(\s+static)?\s+\w+\s+\w+\s*\(.*\)\s*(throws\s+[\w\s,]+)?\s*\{

Log Patterns:

Python

Function Definition Patterns:

def\s+\w+\s*\(.*\)\s*->?\s*.*:

Log Patterns:

JavaScript/TypeScript

Function Definition Patterns:

function\s+\w+\s*\(.*\)\s*\{
|\w+\s*\([^)]*\)\s*(=>|\{)

Log Patterns:

Fix Recommendations

For Log Deficiencies

Error Return Path (Must Fix):

// BEFORE:
if (remote == nullptr) {
    return ERR_NULL_OBJECT;  // ❌ No LOGE
}

// AFTER:
if (remote == nullptr) {
    HILOGE("FunctionName: remote is null, context=%{public}d", context);
    return ERR_NULL_OBJECT;
}

Success Path (Should Fix):

// BEFORE:
int32_t CreateSession(...) {
    // ... initialization code
    return ERR_OK;  // ❌ No LOGI on success
}

// AFTER:
int32_t CreateSession(...) {
    // ... initialization code
    HILOGI("CreateSession: success, sessionId=%{public}d, name=%{public}s", id, name);
    return ERR_OK;
}

For High-Frequency Risks

Remove High-Frequency LOGI:

// BEFORE:
void OnPacketReceived(int socketId, const void* data, uint32_t len) {
    HILOGI("packet received: socket=%{public}d, len=%{public}u", socketId, len);  // ⚠️ Per-packet
    // ... process packet
}

// AFTER:
void OnPacketReceived(int socketId, const void* data, uint32_t len) {
    // Removed per-packet LOGI
    static std::atomic<uint64_t> packetCount{0};
    if (++packetCount % 1000 == 1) {
        HILOGI("Packet stats: count=%{public}llu, socket=%{public}d",
            packetCount.load(), socketId);
    }
    // ... process packet
}

Use Throttled LOGE for Errors:

// BEFORE:
void ProcessPacket(const Packet* pkt) {
    if (pkt == nullptr) {
        HILOGE("packet is null");  // ⚠️ Per-packet error
        return;
    }
}

// AFTER:
void ProcessPacket(const Packet* pkt) {
    if (pkt == nullptr) {
        static std::atomic<uint32_t> errorCount{0};
        if (++errorCount % 100 == 1) {
            HILOGE("ProcessPacket: null packet, count=%{public}u", errorCount.load());
        }
        return;
    }
}

Output Format

================================================================================
Log Coverage Analysis Report
================================================================================

Repository: <repository_path>
Analysis Date: <timestamp>
Files Analyzed: <count>

## Summary Statistics

| Metric | Count |
|--------|-------|
| Total Source Files | <number> |
| Total Functions | <number> |
| Functions Analyzed | <number> |
| Log Deficiencies | <number> |
| High-Frequency Risks | <number> |

## Log Deficiencies

### [High/Medium/Low] Priority

**File**: `<file_path>`
**Function**: `<function_name>`
**Lines**: `<line_range>`
**Issue**: `<description>`

**Evidence**:

<code snippet>


**Impact**:
<explain impact on debugging/troubleshooting>

**Fix**:

<fixed code>


---

## High-Frequency Risks

### [High/Medium/Low] Risk

**File**: `<file_path>`
**Function**: `<function_name>`
**Lines**: `<line_range>`
**Risk**: <description>

**Evidence**:

<code snippet>


**Analysis**:
<explain why this is high-frequency>

**Fix**:

<fixed code with throttling/statistics>


---

## Call Chain Analysis

### Call Chain: <chain_name>

<function_1>()

↓ [✓/✗/⚠️] <log_status>

<function_2>()

↓ [✓/✗/⚠️] <log_status>

<function_3>()

├─ [✓/✗/⚠️] branch_1

├─ [✓/✗/⚠️] branch_2

└─ [✓/✗/⚠️] branch_3


Legend:
- ✓ : Has required LOGE/LOGI
- ✗ : Missing required logging
- ⚠️ : Has high-frequency log risk

---

## Recommendations

### Immediate Actions (P0)
<list of critical items>

### Follow-up Actions (P1)
<list of important items>

### Long-term Improvements (P2)
<list of improvement suggestions>

================================================================================

Parameters

| Parameter | Required | Description |

|-----------|----------|-------------|

| --path | No | Repository path (default: current directory) |

| --exclude-tests | No | Exclude test files (default: true) |

| --lang | No | Language filter (cpp, java, python, js, all) |

| --output | No | Output report path |

Usage Examples

# Analyze current directory
/log-coverage-analyzer

# Analyze specific repository
/log-coverage-analyzer --path /path/to/repo

# Analyze C++ code only
/log-coverage-analyzer --lang cpp --path /path/to/repo

# Include test files in analysis
/log-coverage-analyzer --exclude-tests false

# Custom output location
/log-coverage-analyzer --output /path/to/report.md

Tips

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.