Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Add Comprehensive Logging System#228

Merged
codingki merged 5 commits intodevfrom
feat/comprehensive-logging-system
Oct 30, 2025
Merged

Add Comprehensive Logging System#228
codingki merged 5 commits intodevfrom
feat/comprehensive-logging-system

Conversation

@codingki
Copy link
Member

This PR adds a comprehensive, production-ready logging system to Graz with support for multiple log levels, category filtering, performance timing, error tracking integration, and colored console output.

Features

🎯 Core Logging System

  • 5 Log Levels: ERROR, WARN, INFO, DEBUG, TRACE with intelligent filtering
  • 7 Log Categories: WALLET, TRANSACTION, QUERY, STORE, MULTICHAIN, EVENT, PERFORMANCE
  • Flexible Configuration: Single level (minimum threshold), array of levels (specific only), or undefined (all levels)
  • Dynamic Control: Enable/disable and reconfigure logger at runtime
  • Performance Timing: Automatic performance measurement for key operations
  • Error Reporter Integration: Built-in support for error tracking services (e.g., Sentry)

🎨 Developer Experience

  • Colored Console Output: Unique colors for log levels, categories, and individual functions/hooks
  • Structured Logging: Rich context data with automatic cleanup of internal keys
  • Function/Hook Tracking: Logs include the originating function or hook name
  • Multi-chain Logging: Enhanced logging for multi-chain operations with chain IDs
  • Console Grouping: Support for console.group/groupEnd for better log organization

⚙️ Configuration

  • Opt-in by Default: Logger is disabled by default, must be explicitly enabled
  • Provider Configuration: Configure via GrazProvider with logger options
  • Runtime Configuration: Use configureLogger() or getLogger() for dynamic control
  • Debug Mode Override: window.__GRAZ_DEBUG__ = true to force enable logging

📝 Implementation

  • Type-Safe: Full TypeScript support with LogLevel and LogCategory enums
  • Tree-Shakeable: Minimal bundle size impact in production builds
  • Centralized Constants: LOG_FUNCTIONS and LOG_HOOKS for consistent naming
  • Zustand Integration: Logger configuration stored in GrazInternalStore

Usage

Basic Setup

import { GrazProvider, LogLevel, LogCategory } from "graz";

<GrazProvider
  grazOptions={{
    chains: [cosmoshubChainInfo, osmosisChainInfo],
    logger: {
      enabled: true,
      level: LogLevel.DEBUG,
      categories: [LogCategory.WALLET, LogCategory.TRANSACTION],
    },
  }}
>
  <App />
</GrazProvider>;

Environment-based Configuration

const isDevelopment = process.env.NODE_ENV === "development";

<GrazProvider
  grazOptions={{
    chains: [...],
    logger: isDevelopment
      ? { enabled: true, level: LogLevel.DEBUG }
      : { enabled: true, level: LogLevel.ERROR, errorReporter },
  }}
>

Dynamic Control

import { getLogger, LogLevel } from "graz";

const logger = getLogger();

// Enable/disable
logger.enable();
logger.disable();

// Change level
logger.setLevel(LogLevel.INFO);
logger.setLevel([LogLevel.ERROR, LogLevel.WARN]);

// Change categories
logger.setCategories([LogCategory.WALLET]);

Logging Coverage

Logging has been integrated across the entire codebase:

Actions

  • connect() - Full connection lifecycle with performance timing
  • disconnect() - Disconnection tracking
  • reconnect() - Reconnection attempts and failures
  • sendTokens() - Transaction signing and broadcasting
  • sendIbcTokens() - IBC transfers
  • executeContract() - Contract execution
  • instantiateContract() - Contract instantiation
  • ✅ Chain management functions
  • ✅ Wallet adapter operations

Hooks

  • useConnect() - Connection mutation logging
  • useDisconnect() - Disconnection mutation logging
  • useSendTokens() - Transaction mutation logging
  • useExecuteContract() - Contract execution logging
  • useStargateClient() - Client creation logging
  • useCosmWasmClient() - CosmWasm client logging
  • ✅ All signing client hooks
  • ✅ Chain management hooks

Utilities

  • createMultiChainAsyncFunction() - Multi-chain operation timing and tracking
  • ✅ Wallet adapter functions
  • ✅ Event handlers (ping, reconnect, keystore changes)

Documentation

Added Files

  1. docs/docs/guides/logging-and-debugging.md (478 lines)

    • Complete guide to logging system
    • Quick start examples
    • Configuration reference
    • Troubleshooting guide
    • Best practices
  2. packages/graz/src/types/logger.ts (99 lines)

    • LogLevel enum
    • LogCategory enum
    • Logger interface
    • LoggerOptions interface
    • ErrorReporter interface
  3. packages/graz/src/utils/logger.ts (317 lines)

    • GrazLogger class implementation
    • Singleton pattern with getLogger() and configureLogger()
    • Color schemes for console output
    • Performance timing
    • Error reporter integration
  4. packages/graz/src/constant.ts (updated)

    • LOG_CATEGORIES constant
    • LOG_FUNCTIONS constant (all function names)
    • LOG_HOOKS constant (all hook names)

Testing

Test Coverage

41 tests covering all logger functionality

✓ src/utils/__tests__/logger.test.ts (41 tests) 11ms

Test Categories:

  • Initialization (6 tests)
  • Log Level Filtering (10 tests)
  • Category Filtering (4 tests)
  • Dynamic Configuration (6 tests)
  • Context Data (4 tests)
  • Error Reporter Integration (3 tests)
  • Performance Timing (3 tests)
  • Grouping (3 tests)
  • Edge Cases (4 tests)
  • Singleton Behavior (2 tests)

Note: Tests use a standalone TestGrazLogger class to work around Vitest 2.x SSR bug with enum imports.

Breaking Changes

⚠️ Logger is Opt-in

Previous Behavior: No logging system existed

New Behavior: Logger exists but is disabled by default

  • Logs will NOT appear unless explicitly enabled via configuration
  • Set logger: { enabled: true } in grazOptions to enable
  • Override with window.__GRAZ_DEBUG__ = true for debugging

This is intentional to give developers full control over logging in their applications.

Examples

Development Logging

<GrazProvider
  grazOptions={{
    chains: [...],
    logger: {
      enabled: true,
      level: LogLevel.DEBUG,
    }
  }}
>

Production Error Tracking

import * as Sentry from "@sentry/react";

<GrazProvider
  grazOptions={{
    chains: [...],
    logger: {
      enabled: true,
      level: LogLevel.ERROR,
      errorReporter: {
        captureException: (error, context) => {
          Sentry.captureException(error, { extra: context });
        },
      },
    }
  }}
>

Filtered Logging

<GrazProvider
  grazOptions={{
    chains: [...],
    logger: {
      enabled: true,
      level: [LogLevel.ERROR, LogLevel.WARN],
      categories: [LogCategory.WALLET, LogCategory.TRANSACTION],
    }
  }}
>

Visual Output

Logs appear in the browser console with colored formatting:

[graz] INFO [wallet] [connect] Connection successful
  { walletType: "keplr", chainCount: 2, chainIds: ["cosmoshub-4", "osmosis-1"] }

[graz] ERROR [wallet] [connect] Connection failed
  { error: "User rejected request", walletType: "keplr" }

[graz] DEBUG [multichain] [useStargateClient] Starting parallel operations
  { chainCount: 3, concurrency: 3, chainIds: [...] }

[graz] DEBUG [performance] ⏱️ connect: 1234.56ms

Migration Guide

No breaking changes for existing users. The logger is opt-in and requires explicit configuration to enable.

To Enable Logging

// Add logger configuration to your GrazProvider
<GrazProvider
  grazOptions={{
    chains: [...], // existing config
    logger: { enabled: true }, // add this
  }}
>

Checklist

  • Core logger implementation
  • Integration across all actions
  • Integration across all hooks
  • Integration across all wallet adapters
  • Multi-chain operation logging
  • Colored console output
  • Performance timing
  • Error reporter integration
  • Configuration via GrazProvider
  • Configuration via configureGraz
  • Dynamic runtime control
  • TypeScript types and enums
  • Centralized function/hook naming
  • Comprehensive documentation
  • Unit tests (41 tests, 100% pass rate)
  • Build verification
  • Example integration

Related Issues

Closes #[issue-number] (if applicable)

Additional Notes

The logger system is designed to be:

  • Non-intrusive: Opt-in by default, zero impact when disabled
  • Performant: Minimal overhead, tree-shakeable in production
  • Developer-friendly: Rich colors, structured data, easy configuration
  • Production-ready: Error tracking integration, flexible filtering
  • Extensible: Easy to add new categories or customize behavior

This provides a solid foundation for debugging and monitoring Graz applications in both development and production environments.

@changeset-bot
Copy link

changeset-bot bot commented Oct 30, 2025

🦋 Changeset detected

Latest commit: 9969ec9

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
graz Patch
@project/example-playground Patch
@project/example-vite Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@codingki codingki merged commit 114b8b5 into dev Oct 30, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant