Skip to content

Basic Usage Example

This example demonstrates how to use siddiqsoft::ScopeTrace for scope tracing, nested scope timing (nest()), info, trace, warning, and error logging, exception capture, and string formatting.

#include <iostream>
#include <thread>
#include <stdexcept>
#include <siddiqsoft/ScopeTrace.hpp>

void worker()
{
    // Create nested scope from process singleton
    auto scope = siddiqsoft::ScopeTrace::CreateInstance().nest("worker", siddiqsoft::LogLevel::trace);
    scope.info("Worker starting task with ID={}", 42);
    scope.trace("Low-level trace details for worker setup");

    // Create a child nested scope ("worker/subtask") with warning threshold
    auto sub = scope.nest("subtask", siddiqsoft::LogLevel::warning);
    std::this_thread::sleep_for(std::chrono::milliseconds(10));

    sub.warn("Resource usage reached {}%", 85);
}

void perform_operation()
{
    auto scope = siddiqsoft::ScopeTrace::CreateInstance().nest("perform_operation", siddiqsoft::LogLevel::trace);
    worker();

    try {
        throw std::runtime_error("Simulated failure in sub-system");
    }
    catch (const std::exception& e) {
        // Exception handler shortcut with custom formatted contextual details
        scope.exp(e, "Error encountered during operation execution");
    }
}

int main()
{
    // Obtain process-wide singleton ScopeTrace instance
    auto& scope = siddiqsoft::ScopeTrace::CreateInstance("main", siddiqsoft::LogLevel::trace);
    scope.info("Application initialization complete");

    perform_operation();

    return 0;
}

Sample Console Output & Coloring

Executing the example above outputs formatted log entries to std::cerr with dynamic depth spaces, ISO 8601 UTC timestamps, and ANSI colors:

Console Output (std::cerr)
  Creating NEW SCOPE main:6
2026-08-15T20:49:27.060564Z  [info  ] main - Application initialization complete
  Creating NEW SCOPE perform_operation:6
  Creating NEW SCOPE worker:6
2026-08-15T20:49:27.060600Z  [info  ]     worker - Worker starting task with ID=42
2026-08-15T20:49:27.060620Z  [trace ]     worker - Low-level trace details for worker setup
  Creating NEW SCOPE worker/subtask:3
2026-08-15T20:49:27.070800Z  [warn  ]       worker/subtask - Resource usage reached 85%
2026-08-15T20:49:27.070850Z  [debug ]       worker/subtask - COMPLETED: time:10210us
2026-08-15T20:49:27.070900Z  [debug ]     worker - COMPLETED: time:10310us
2026-08-15T20:49:27.071000Z  [except]   perform_operation - std::runtime_error - Simulated failure in sub-system - Error encountered during operation execution
2026-08-15T20:49:27.071050Z  [debug ]   perform_operation - COMPLETED: time:10500us
2026-08-15T20:49:27.071120Z  [debug ] main - COMPLETED: time:10620us