OB

obsidian-observability

Implements structured logging, performance metrics, and debug panels within Obsidian plugins for easier observability.

Install

mkdir -p .claude/skills/obsidian-observability && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/1217" && unzip -o skill.zip -d .claude/skills/obsidian-observability && rm skill.zip

Installs to .claude/skills/obsidian-observability

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement structured logging, metrics, error tracking, and a debug panel
72 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Implement structured logging with levels and history
  • Collect metrics including counters, gauges, and timers
  • Track errors with deduplication and occurrence counts
  • Display real-time observability in a debug sidebar panel
  • Export a full debug bundle as JSON

How it works

The skill provides copy-pasteable TypeScript components that integrate into an Obsidian plugin to capture logs, metrics, and errors, and display them in a custom sidebar.

Inputs & outputs

You give it
TypeScript code snippets for logger, metrics, error tracker, and debug panel components
You get back
An Obsidian plugin with integrated logging, metrics, error tracking, and a debug sidebar

When to use obsidian-observability

  • Add debug logging to plugins
  • Track plugin performance metrics
  • Build a diagnostics sidebar
  • Report plugin errors

About this skill

Obsidian Observability

Overview

Implement production observability for Obsidian plugins: a structured logger with levels and ring buffer history, a metrics collector with counters/gauges/timers, an error tracker with deduplication, and a debug sidebar panel that displays all of it in real time. Every component is copy-pasteable and uses only Obsidian's built-in APIs.

Prerequisites

  • Working Obsidian plugin (see obsidian-core-workflow-a)
  • TypeScript strict mode enabled
  • Familiarity with ItemView for the debug panel

Instructions

Step 1: Structured Logger with Levels and History

// src/services/logger.ts
type LogLevel = 'debug' | 'info' | 'warn' | 'error';

const LEVEL_PRIORITY: Record<LogLevel, number> = {
  debug: 0, info: 1, warn: 2, error: 3,
};

interface LogEntry {
  timestamp: number;
  level: LogLevel;
  message: string;
  data?: unknown;
}

export class Logger {
  private history: LogEntry[] = [];
  private maxHistory = 200;
  private level: LogLevel;
  private prefix: string;

  constructor(pluginId: string, level: LogLevel = 'info') {
    this.prefix = `[${pluginId}]`;
    this.level = level;
  }

  setLevel(level: LogLevel) { this.level = level; }

  debug(msg: string, data?: unknown) { this.log('debug', msg, data); }
  info(msg: string, data?: unknown)  { this.log('info', msg, data); }
  warn(msg: string, data?: unknown)  { this.log('warn', msg, data); }
  error(msg: string, data?: unknown) { this.log('error', msg, data); }

  /** Start a timer, returns a function that stops it and logs duration */
  time(label: string): () => number {
    const start = performance.now();
    return () => {
      const ms = performance.now() - start;
      this.debug(`${label} (${ms.toFixed(2)}ms)`);
      return ms;
    };
  }

  /** Get last N log entries */
  getHistory(count?: number): LogEntry[] {
    return count ? this.history.slice(-count) : [...this.history];
  }

  /** Export history as JSON string */
  export(): string {
    return JSON.stringify(this.history, null, 2);
  }

  private log(level: LogLevel, message: string, data?: unknown) {
    if (LEVEL_PRIORITY[level] < LEVEL_PRIORITY[this.level]) return;

    const entry: LogEntry = { timestamp: Date.now(), level, message, data };
    this.history.push(entry);
    if (this.history.length > this.maxHistory) {
      this.history.splice(0, this.history.length - this.maxHistory);
    }

    const fn = level === 'debug' ? console.debug
             : level === 'warn' ? console.warn
             : level === 'error' ? console.error
             : console.log;
    if (data !== undefined) {
      fn(this.prefix, message, data);
    } else {
      fn(this.prefix, message);
    }
  }
}

Step 2: Metrics Collector with Counters, Gauges, and Timers

// src/services/metrics.ts
interface TimerStats {
  count: number;
  total: number;
  min: number;
  max: number;
  values: number[]; // last 100 values for percentile calculation
}

export class MetricsCollector {
  private counters = new Map<string, number>();
  private gauges = new Map<string, number>();
  private timers = new Map<string, TimerStats>();

  // Counters — monotonically increasing
  increment(name: string, amount = 1) {
    this.counters.set(name, (this.counters.get(name) ?? 0) + amount);
  }

  getCounter(name: string): number {
    return this.counters.get(name) ?? 0;
  }

  // Gauges — point-in-time values
  setGauge(name: string, value: number) {
    this.gauges.set(name, value);
  }

  getGauge(name: string): number {
    return this.gauges.get(name) ?? 0;
  }

  // Timers — track duration distributions
  recordTime(name: string, ms: number) {
    let stats = this.timers.get(name);
    if (!stats) {
      stats = { count: 0, total: 0, min: Infinity, max: 0, values: [] };
      this.timers.set(name, stats);
    }
    stats.count++;
    stats.total += ms;
    stats.min = Math.min(stats.min, ms);
    stats.max = Math.max(stats.max, ms);
    stats.values.push(ms);
    if (stats.values.length > 100) stats.values.shift();
  }

  /** Wrap an async function with automatic timing */
  async timeAsync<T>(name: string, fn: () => Promise<T>): Promise<T> {
    const start = performance.now();
    try {
      return await fn();
    } finally {
      this.recordTime(name, performance.now() - start);
    }
  }

  getTimerStats(name: string): { avg: number; p95: number; min: number; max: number; count: number } | null {
    const stats = this.timers.get(name);
    if (!stats || stats.count === 0) return null;
    const sorted = [...stats.values].sort((a, b) => a - b);
    const p95Index = Math.floor(sorted.length * 0.95);
    return {
      avg: stats.total / stats.count,
      p95: sorted[p95Index] ?? sorted[sorted.length - 1],
      min: stats.min,
      max: stats.max,
      count: stats.count,
    };
  }

  /** Get all metrics as a plain object for serialization */
  snapshot(): Record<string, unknown> {
    const result: Record<string, unknown> = {};
    for (const [k, v] of this.counters) result[`counter.${k}`] = v;
    for (const [k, v] of this.gauges) result[`gauge.${k}`] = v;
    for (const [k] of this.timers) {
      const s = this.getTimerStats(k);
      if (s) result[`timer.${k}`] = s;
    }
    return result;
  }
}

Step 3: Error Tracker with Deduplication

// src/services/error-tracker.ts
interface TrackedError {
  name: string;
  message: string;
  stack?: string;
  count: number;
  firstSeen: number;
  lastSeen: number;
}

export class ErrorTracker {
  private errors = new Map<string, TrackedError>();

  /** Record an error, deduplicating by name+message */
  track(err: Error) {
    const key = `${err.name}:${err.message}`;
    const existing = this.errors.get(key);
    if (existing) {
      existing.count++;
      existing.lastSeen = Date.now();
    } else {
      this.errors.set(key, {
        name: err.name,
        message: err.message,
        stack: err.stack,
        count: 1,
        firstSeen: Date.now(),
        lastSeen: Date.now(),
      });
    }
  }

  /** Wrap an async function — catch and track errors, then rethrow */
  async wrapAsync<T>(label: string, fn: () => Promise<T>): Promise<T | undefined> {
    try {
      return await fn();
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String(e));
      err.message = `[${label}] ${err.message}`;
      this.track(err);
      return undefined;
    }
  }

  getErrors(): TrackedError[] {
    return [...this.errors.values()].sort((a, b) => b.lastSeen - a.lastSeen);
  }

  getErrorCount(): number {
    let total = 0;
    for (const e of this.errors.values()) total += e.count;
    return total;
  }

  clear() { this.errors.clear(); }
}

Step 4: Debug Sidebar Panel

// src/views/debug-view.ts
import { ItemView, WorkspaceLeaf } from 'obsidian';
import type { Logger } from '../services/logger';
import type { MetricsCollector } from '../services/metrics';
import type { ErrorTracker } from '../services/error-tracker';

export const DEBUG_VIEW_TYPE = 'plugin-debug-view';

export class DebugView extends ItemView {
  private refreshTimer: number | null = null;

  constructor(
    leaf: WorkspaceLeaf,
    private logger: Logger,
    private metrics: MetricsCollector,
    private errorTracker: ErrorTracker,
  ) {
    super(leaf);
  }

  getViewType() { return DEBUG_VIEW_TYPE; }
  getDisplayText() { return 'Plugin Debug'; }
  getIcon() { return 'bug'; }

  async onOpen() {
    this.render();
    // Auto-refresh every 3 seconds
    this.refreshTimer = window.setInterval(() => this.render(), 3000);
  }

  async onClose() {
    if (this.refreshTimer) clearInterval(this.refreshTimer);
  }

  private render() {
    const container = this.containerEl.children[1];
    container.empty();
    container.addClass('plugin-debug-view');

    // Metrics section
    container.createEl('h4', { text: 'Metrics' });
    const snapshot = this.metrics.snapshot();
    const metricsTable = container.createEl('table');
    for (const [key, value] of Object.entries(snapshot)) {
      const row = metricsTable.createEl('tr');
      row.createEl('td', { text: key, cls: 'debug-key' });
      row.createEl('td', {
        text: typeof value === 'object' ? JSON.stringify(value) : String(value),
      });
    }

    // Errors section
    const errors = this.errorTracker.getErrors();
    container.createEl('h4', { text: `Errors (${this.errorTracker.getErrorCount()})` });
    if (errors.length === 0) {
      container.createEl('p', { text: 'No errors recorded.', cls: 'debug-empty' });
    } else {
      for (const err of errors.slice(0, 10)) {
        const el = container.createEl('div', { cls: 'debug-error' });
        el.createEl('strong', { text: `${err.name} (x${err.count})` });
        el.createEl('p', { text: err.message });
      }
    }

    // Recent logs section
    container.createEl('h4', { text: 'Recent Logs' });
    const logs = this.logger.getHistory(20);
    for (const entry of logs.reverse()) {
      const el = container.createEl('div', { cls: `debug-log debug-${entry.level}` });
      const time = new Date(entry.timestamp).toLocaleTimeString();
      el.createEl('span', { text: `${time} [${entry.level}]`, cls: 'debug-time' });
      el.createEl('span', { text: ` ${entry.message}` });
    }

    // Export button
    const btn = container.createEl('button', { text: 'Export Debug Bundle' });
    btn.addEventListener('click', () => {
      const bundle = {
        timestamp: new Date().toISOString(),
        metrics: snapshot,
        errors: errors,
        recentLogs: this.logger.getHistory(50),
      };
      navigator.clipboard.writeText(JSON.stringify(bundle, null, 2));
      new (require('obsidian').Notice)('Debug bundle copied to clipboard');
    });
  }
}

Step 5: Wire Everything into the Plugin

// src/main.ts
import { Plugin } from 'obsidian';
import { Logger } from './services/logger';
import { MetricsCollector } fro

---

*Content truncated.*

Prerequisites

Working Obsidian pluginTypeScript strict mode enabledFamiliarity with ItemView for the debug panel

Limitations

  • Requires a working Obsidian plugin
  • Requires TypeScript strict mode
  • Debug panel relies on `ItemView`

How it compares

This skill offers a complete, integrated observability solution specifically for Obsidian plugins, unlike manual console logging or external monitoring tools.

Compared to similar skills

obsidian-observability side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
obsidian-observability (this skill)525dReviewIntermediate
obsidian-performance-tuning625dReviewAdvanced
obsidian-rate-limits525dNo flagsIntermediate
codex-code-review17moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

obsidian-performance-tuning

jeremylongshore

Optimize Obsidian plugin performance for smooth operation. Use when experiencing lag, memory issues, or slow startup, or when optimizing plugin code for large vaults. Trigger with phrases like "obsidian performance", "obsidian slow", "optimize obsidian plugin", "obsidian memory usage".

640

obsidian-rate-limits

jeremylongshore

Handle Obsidian file system operations and throttling patterns. Use when processing many files, handling bulk operations, or preventing performance issues from excessive operations. Trigger with phrases like "obsidian rate limit", "obsidian bulk operations", "obsidian file throttling", "obsidian performance limits".

533

codex-code-review

tyrchen

Perform comprehensive code reviews using OpenAI Codex CLI. This skill should be used when users request code reviews, want to analyze diffs/PRs, need security audits, performance analysis, or want automated code quality feedback. Supports reviewing staged changes, specific files, entire directories, or git diffs.

16

azure-monitor-opentelemetry-ts

microsoft

Instrument applications with Azure Monitor and OpenTelemetry for JavaScript (@azure/monitor-opentelemetry). Use when adding distributed tracing, metrics, and logs to Node.js applications with Application Insights.

11

debug

hta218

Instrument web/web-app code with structured debug logging via a global variable (window.__debug_logs). Produces a clean JSON timeline for reproducing and diagnosing bugs. Use when user wants to debug a feature or track down a bug.

00

reviewing-nextjs-16-patterns

djankies

Review code for Next.js 16 compliance - security patterns, caching, breaking changes. Use when reviewing Next.js code, preparing for migration, or auditing for violations.

11106

Search skills

Search the agent skills registry