Skip to content

Basic Usage Example

This example demonstrates how to use siddiqsoft::ScopeTrace for scope tracing, nested scope timing (sub_scope()), 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::GetInstance().sub_scope("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.sub_scope("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::GetInstance().sub_scope("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::GetInstance("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)
2026-08-15T20:49:27.060564Z|[info  ]|main|Application initialization complete
2026-08-15T20:49:27.060600Z|[info  ]|main/worker|Worker starting task with ID=42
2026-08-15T20:49:27.060620Z|[trace ]|main/worker|Low-level trace details for worker setup
2026-08-15T20:49:27.070800Z|[warn  ]|main/worker/subtask|Resource usage reached 85%
2026-08-15T20:49:27.070850Z|[debug ]|main/worker/subtask|COMPLETED: time:10210us
2026-08-15T20:49:27.070900Z|[debug ]|main/worker|COMPLETED: time:10310us
2026-08-15T20:49:27.071000Z|[except]|main/perform_operation|std::runtime_error - Simulated failure in sub-system - Error encountered during operation execution
2026-08-15T20:49:27.071050Z|[debug ]|main/perform_operation|COMPLETED: time:10500us
2026-08-15T20:49:27.071120Z|[debug ]|main|COMPLETED: time:10620us