Logging System

Logging System

The following files were used as context for generating this wiki page:

Purpose and Scope

This document describes WSHawk's centralized logging infrastructure, including custom security-focused log levels, colored terminal output, and persistent file logging. The logging system provides real-time feedback during scans and maintains audit trails for compliance and debugging.

For information about configuration of logging behavior, see Configuration System. For details on database persistence of scan results (separate from log files), see Infrastructure Persistence Layer.


System Architecture

WSHawk employs a two-tier logging architecture: a centralized logger module (wshawk/logger.py) that configures Python's standard logging facility with custom enhancements, and a convenience wrapper class (Logger) in the legacy scanner that provides static methods for backward compatibility.

Logging System Component Diagram

graph TB
    subgraph "Centralized Logger Module"
        setup_logging["setup_logging()"]
        get_logger["get_logger()"]
        LoggerPy["wshawk/logger.py"]
        StdLogging["Python logging.Logger"]
    end
    
    subgraph "Custom Enhancements"
        VULN_LEVEL["VULN_LEVEL = 35"]
        SUCCESS_LEVEL["SUCCESS_LEVEL = 25"]
        Colors["Colors Class<br/>CYAN, RED, GREEN, etc."]
        ColoredFormatter["ColoredFormatter"]
    end
    
    subgraph "Output Destinations"
        Console["sys.stdout<br/>Colored Output"]
        FileHandler["File Handler<br/>logs/wshawk.log"]
    end
    
    subgraph "Consumer Components"
        LegacyLogger["Logger Class<br/>__main__.py"]
        ScannerV2["WSHawkV2<br/>scanner_v2.py"]
        WebApp["Flask Web App<br/>web/app.py"]
        DefensiveModule["Defensive Validation<br/>modules/defensive.py"]
    end
    
    setup_logging --> StdLogging
    setup_logging --> VULN_LEVEL
    setup_logging --> SUCCESS_LEVEL
    setup_logging --> ColoredFormatter
    
    ColoredFormatter --> Colors
    
    StdLogging --> Console
    StdLogging --> FileHandler
    
    get_logger --> StdLogging
    
    LegacyLogger --> get_logger
    ScannerV2 --> get_logger
    WebApp --> get_logger
    DefensiveModule --> get_logger

Sources: wshawk/main.py:20-23, CHANGELOG.md:86-90


Custom Security Log Levels

WSHawk extends Python's standard logging levels with two custom levels tailored for security scanning workflows:

| Level Name | Numeric Value | Standard Equivalent | Purpose | |------------|---------------|---------------------|---------| | VULN_LEVEL | 35 | Between WARNING (30) and ERROR (40) | Log detected vulnerabilities with high visibility | | SUCCESS_LEVEL | 25 | Between INFO (20) and WARNING (30) | Log successful security validations and milestones | | INFO | 20 | Standard | General scan progress and configuration | | WARNING | 30 | Standard | Suspicious findings that may not be confirmed vulnerabilities | | ERROR | 40 | Standard | Scan failures and connection errors |

Log Level Flow Diagram

graph LR
    subgraph "Scan Lifecycle Events"
        ScanStart["Scan Start<br/>INFO"]
        Testing["Testing Phase<br/>INFO"]
        Detection["Detection<br/>VULN_LEVEL"]
        Validation["Validation<br/>SUCCESS_LEVEL"]
        Error["Error Condition<br/>ERROR"]
    end
    
    ScanStart --> Testing
    Testing --> Detection
    Testing --> Validation
    Testing --> Error
    
    Detection --> Report["Report Generation"]
    Validation --> Report
    Error --> Abort["Scan Abort"]

Sources: wshawk/main.py:20, CHANGELOG.md:29


Colors and Terminal Formatting

The logging system includes a Colors class that provides ANSI escape codes for terminal formatting. This enhances readability during interactive scans and CI/CD runs that support colored output.

Colors Class Definition

classDiagram
    class Colors {
        +str CYAN
        +str RED
        +str GREEN
        +str YELLOW
        +str BLUE
        +str BOLD
        +str END
    }
    
    class Logger {
        +banner()$ void
        +info(msg)$ void
        +success(msg)$ void
        +warning(msg)$ void
        +error(msg)$ void
        +vuln(msg)$ void
    }
    
    Logger ..> Colors : uses

The Colors class attributes are used to wrap log messages with appropriate ANSI codes. The Logger.banner() method demonstrates extensive use of color formatting to display the WSHawk ASCII art banner with gradient effects.

Example color usage from banner:

  • Header: Colors.CYAN + Colors.BOLD
  • Version: Colors.YELLOW
  • Attribution: Colors.CYAN
  • Separator: Colors.BLUE

Sources: wshawk/main.py:28-38


Logger Wrapper Class API

The Logger static class in wshawk/main.py:25-58 provides a simplified interface to the underlying centralized logger. All methods delegate to get_logger() which returns the configured logging.Logger instance.

Method Reference

| Method | Log Level | Purpose | Example Use Case | |--------|-----------|---------|------------------| | Logger.banner() | N/A | Display ASCII art banner | Scan initialization | | Logger.info(msg) | INFO (20) | General information | "Testing WebSocket connection..." | | Logger.success(msg) | SUCCESS_LEVEL (25) | Positive outcome | "WebSocket connection established" | | Logger.warning(msg) | WARNING (30) | Potential issue | "Origin bypass successful with: evil.com" | | Logger.error(msg) | ERROR (40) | Failure condition | "Connection failed: timeout" | | Logger.vuln(msg) | VULN_LEVEL (35) | Vulnerability detected | "SQL Injection detected: ' OR '1'='1" |

Usage Pattern Flow

sequenceDiagram
    participant Scanner as WSHawk Scanner
    participant Logger as Logger Class
    participant GetLogger as get_logger()
    participant StdLog as logging.Logger
    participant Output as Console/File
    
    Scanner->>Logger: Logger.info("Starting scan")
    Logger->>GetLogger: get_logger()
    GetLogger-->>Logger: logger instance
    Logger->>StdLog: logger.info("Starting scan")
    StdLog->>Output: Formatted output with colors
    
    Scanner->>Logger: Logger.vuln("XSS detected")
    Logger->>GetLogger: get_logger()
    GetLogger-->>Logger: logger instance
    Logger->>StdLog: logger.log(VULN_LEVEL, msg)
    StdLog->>Output: Formatted output (red/bold)

Sources: wshawk/main.py:25-58


File Persistence and Log Rotation

The centralized logging system writes logs to persistent files in addition to console output. This enables post-scan analysis, audit trails, and debugging.

File Structure

project_root/
├── logs/                      # Log directory (auto-created)
│   ├── wshawk.log            # Main log file
│   ├── wshawk.log.1          # Rotated log (if rotation enabled)
│   └── wshawk.log.2          # Older rotated log
├── wshawk_report_*.html      # HTML reports (separate from logs)
└── scans.db                  # SQLite database (separate persistence)

Log File Format

Log entries follow standard Python logging format with additional context:

[TIMESTAMP] [LEVEL] [MODULE:FUNCTION] Message content

Example entries:

[2026-02-18 14:23:01] [INFO] [scanner_v2:run_heuristic_scan] Starting heuristic scan on ws://target.com
[2026-02-18 14:23:15] [VULN] [scanner_v2:test_xss] XSS reflection detected: <script>alert(1)</script>
[2026-02-18 14:23:45] [SUCCESS] [scanner_v2:run_heuristic_scan] Scan complete in 44.23s

Log File Lifecycle

stateDiagram-v2
    [*] --> Setup: setup_logging()
    Setup --> Active: Logger created
    Active --> Writing: Log messages received
    Writing --> Active: Continue logging
    Active --> Rotation: Size limit reached
    Rotation --> Active: New file created
    Active --> [*]: Scan complete
    
    note right of Writing
        Writes to logs/wshawk.log
        Colored output to console
        Plain text to file
    end note

Sources: CHANGELOG.md:29, .gitignore:45-48


Integration with Scanner Components

The logging system is imported and used throughout WSHawk's architecture. Below are the key integration points:

Import Pattern

All scanner modules follow this pattern:

from .logger import setup_logging, get_logger, VULN_LEVEL, SUCCESS_LEVEL, Colors
logger = setup_logging()  # Or get_logger() for existing logger

Component Integration Map

graph TB
    subgraph "Core Modules"
        Main["__main__.py<br/>Legacy Scanner"]
        ScannerV2["scanner_v2.py<br/>WSHawkV2"]
        Defensive["modules/defensive.py<br/>Blue Team Tests"]
    end
    
    subgraph "Web Interface"
        WebApp["web/app.py<br/>Flask Dashboard"]
        WebAPI["web/api.py<br/>REST API"]
    end
    
    subgraph "Verification Modules"
        Playwright["modules/playwright_xss.py<br/>Browser Verification"]
        OAST["modules/oast_provider.py<br/>interact.sh"]
        Session["modules/session_tester.py<br/>Session Tests"]
    end
    
    subgraph "Logging Infrastructure"
        LoggerModule["wshawk/logger.py"]
    end
    
    Main --> LoggerModule
    ScannerV2 --> LoggerModule
    Defensive --> LoggerModule
    WebApp --> LoggerModule
    WebAPI --> LoggerModule
    Playwright --> LoggerModule
    OAST --> LoggerModule
    Session --> LoggerModule

Sources: wshawk/main.py:20-23, CHANGELOG.md:86-90


Typical Scan Log Sequence

The following diagram illustrates the log messages produced during a typical vulnerability scan, demonstrating the use of different log levels throughout the scan lifecycle:

sequenceDiagram
    participant User
    participant Scanner as WSHawk Scanner
    participant Log as Logging System
    
    User->>Scanner: wshawk ws://target.com
    Scanner->>Log: banner() [ANSI Colors]
    Scanner->>Log: info("Target: ws://target.com")
    Scanner->>Log: info("Testing WebSocket connection...")
    Scanner->>Log: success("WebSocket connection established")
    
    Scanner->>Log: info("Testing SQL injection (1000 payloads)...")
    Scanner->>Log: vuln("SQL Injection detected: ' OR '1'='1")
    Scanner->>Log: vuln("SQL Injection detected: 1' UNION SELECT...")
    
    Scanner->>Log: info("Testing XSS injection (2500 payloads)...")
    Scanner->>Log: vuln("XSS reflection detected: <script>alert(1)")
    
    Scanner->>Log: info("Testing command injection (500 payloads)...")
    Scanner->>Log: warning("Possible command injection (timing-based)")
    
    Scanner->>Log: info("Testing origin validation bypass (CSWSH)...")
    Scanner->>Log: warning("Origin bypass with: null")
    Scanner->>Log: warning("Origin bypass with: http://evil.com")
    
    Scanner->>Log: success("Scan complete in 127.45s")
    Scanner->>Log: info("Messages sent: 4521")
    Scanner->>Log: info("Messages received: 4489")
    Scanner->>Log: info("Vulnerabilities found: 47")
    Scanner->>Log: success("HTML report saved to: wshawk_report_*.html")
    
    Scanner-->>User: Exit code 0 (vulnerabilities found)

Sources: wshawk/main.py:863-901


Thread Safety and Async Compatibility

Python's logging module is thread-safe by default, which is important for WSHawk's concurrent testing capabilities. The centralized logger can safely be called from:

  1. Asyncio coroutines - Scanner uses asyncio for concurrent payload testing
  2. ThreadPoolExecutor - Playwright browser automation may spawn threads
  3. Flask request handlers - Web dashboard serves multiple concurrent requests

The setup_logging() function should only be called once at application startup, typically in wshawk/main.py:23. Other modules use get_logger() to retrieve the already-configured logger instance.

Sources: wshawk/main.py:20-23, CHANGELOG.md:16-17


Log Level Configuration

While the logging system is centralized in wshawk/logger.py, the specific configuration (verbosity level, file paths, rotation settings) can be controlled through:

  1. Environment variables (e.g., WSHAWK_LOG_LEVEL=DEBUG)
  2. Configuration file (wshawk.yaml - see Configuration System)
  3. CLI arguments (if supported in future versions)

The default configuration provides INFO-level console output with colored formatting and DEBUG-level file output for comprehensive audit trails.

Sources: CHANGELOG.md:26