otel-logging-patterns
Implements OpenTelemetry (OTEL) logging with trace context correlation and structured logging. Use when setting up production logging with OTEL exporters, structlog/loguru integration, trace context propagation, and comprehensive test patterns. Covers Python implementations for FastAPI, Kafka consumers, and background jobs. Includes OTLP, Jaeger, and console exporters.
What this skill does
# OpenTelemetry Logging Patterns
## Table of Contents
- [Purpose](#purpose)
- [Quick Start](#quick-start)
- [Instructions](#instructions)
- [Step 1: Configure OTEL Logging Provider](#step-1-configure-otel-logging-provider)
- [Step 2: Integrate Structured Logging Library](#step-2-integrate-structured-logging-library)
- [Step 3: Add Trace Context Propagation](#step-3-add-trace-context-propagation)
- [Step 4: Set Up Log Exporters](#step-4-set-up-log-exporters)
- [Step 5: Implement Instrumentation](#step-5-implement-instrumentation)
- [Step 6: Add Error and Exception Logging](#step-6-add-error-and-exception-logging)
- [Requirements](#requirements)
- [Common Patterns](#common-patterns)
- [Testing OTEL Logging](#testing-otel-logging)
- [Troubleshooting](#troubleshooting)
- [Supporting Resources](#supporting-resources)
## Purpose
This skill provides production-grade OpenTelemetry logging patterns for Python applications. It covers:
- **OTEL Logging Architecture**: Provider and processor configuration
- **Trace Correlation**: Automatic trace context injection into logs
- **Structured Logging**: Integration with structlog for context preservation
- **Log Exporters**: OTLP, Jaeger, console, and file exporters
- **Error Handling**: Comprehensive exception and error logging
- **Testing Patterns**: Unit and integration tests for logging infrastructure
- **Performance**: Optimization tips to minimize logging overhead
This enables production observability where logs, traces, and metrics are correlated through trace IDs for efficient debugging and monitoring.
## Quick Start
**For this project**, use the authoritative OTEL logging module. Get started in 3 simple steps:
1. **Initialize OTEL at application startup** (once):
```python
from app.core.monitoring.otel_logger import initialize_otel_logger
# Call once at app startup
initialize_otel_logger(
log_level="INFO",
enable_console=True,
enable_otlp=True,
otlp_endpoint="localhost:4317"
)
```
2. **Get logger and tracer in each module**:
```python
from app.core.monitoring.otel_logger import logger, get_tracer
# Module-level initialization
logger = logger(__name__)
tracer = get_tracer(__name__)
```
3. **Use trace_span for operations**:
```python
from app.core.monitoring.otel_logger import trace_span, logger
logger = logger(__name__)
# Logs automatically include trace_id and span_id
with trace_span("process_order", order_id="12345") as span:
logger.info("processing_order", order_id="12345")
# Do work...
logger.info("order_processed", result_count=5)
```
That's it! All logs automatically include trace context, and spans are created with attributes.
**Key Benefits**:
- ✅ Single entry point: `app/core/monitoring/otel_logger.py`
- ✅ No direct imports of structlog or opentelemetry needed
- ✅ Automatic trace context propagation
- ✅ Automatic exception handling in spans
- ✅ Works with async and sync functions
## Instructions
### Step 1: Configure OTEL Logging Provider
Set up the core OpenTelemetry logging infrastructure with provider and exporter configuration.
**Basic setup** (console exporter for development):
```python
# app/shared/otel_config.py
from opentelemetry import logs
from opentelemetry.sdk.logs import LoggerProvider
from opentelemetry.sdk.logs.export import ConsoleLogExporter, SimpleLogRecordExporter
from opentelemetry.sdk.resources import Resource
def setup_console_logging(service_name: str) -> LoggerProvider:
"""Set up OTEL logging with console exporter."""
resource = Resource.create({"service.name": service_name})
logger_provider = LoggerProvider(resource=resource)
exporter = ConsoleLogExporter()
processor = SimpleLogRecordExporter(exporter)
logger_provider.add_log_record_processor(processor)
logs.set_logger_provider(logger_provider)
return logger_provider
```
**For production OTLP/Jaeger setup**, see [references/advanced-patterns.md](references/advanced-patterns.md#otelconfig-class)
### Step 2: Integrate Structured Logging Library
Set up structlog with OTEL trace context integration:
```python
# app/shared/logging_setup.py
import structlog
from opentelemetry.instrumentation.logging import LoggingInstrumentor
def setup_structlog() -> None:
"""Configure structlog with OTEL trace context integration."""
# Enable OTEL logging instrumentation
LoggingInstrumentor().instrument()
# Configure structlog
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.ExceptionRenderer(),
structlog.processors.JSONRenderer(),
],
logger_factory=structlog.logging.LoggerFactory(),
cache_logger_on_first_use=True,
)
def get_logger(name: str):
"""Get a logger instance with trace context support."""
return structlog.logger(name)
```
**For advanced structlog configuration**, see [references/advanced-patterns.md](references/advanced-patterns.md#structlog-configuration)
### Step 3: Add Trace Context Propagation
Ensure trace context flows through logs automatically:
```python
# app/shared/observability.py
from contextvars import ContextVar
from opentelemetry import trace
# Context variables for request tracking
request_id_var: ContextVar[str | None] = ContextVar("request_id", default=None)
user_id_var: ContextVar[str | None] = ContextVar("user_id", default=None)
class ObservabilityContext:
"""Manage observability context (trace IDs, request IDs, user IDs)."""
@staticmethod
def set_request_id(request_id: str) -> None:
"""Set request ID in context."""
request_id_var.set(request_id)
@staticmethod
def get_tracer(name: str):
"""Get tracer instance."""
return trace.get_tracer(name)
@staticmethod
def set_span_attribute(key: str, value: any) -> None:
"""Set attribute on current span."""
span = trace.get_current_span()
if span.is_recording():
span.set_attribute(key, value)
```
**For complete ObservabilityContext class**, see [references/advanced-patterns.md](references/advanced-patterns.md#observability-context)
### Step 4: Set Up Log Exporters
Configure different exporters for different environments:
```python
# app/config.py
from pydantic import Field
from pydantic_settings import BaseSettings
class Config(BaseSettings):
"""Configuration for OTEL logging."""
otel_enabled: bool = Field(default=True)
otel_exporter_type: str = Field(default="console") # 'otlp', 'jaeger', or 'console'
otel_otlp_endpoint: str = Field(default="localhost:4317")
otel_jaeger_host: str = Field(default="localhost")
otel_jaeger_port: int = Field(default=6831)
```
Then use config in main:
```python
# main.py
from app.config import Config
from app.shared.logging_setup import setup_structlog, get_logger
from app.shared.otel_config import OTELConfig
async def main() -> None:
"""Main entry point."""
config = Config()
setup_structlog()
if config.otel_enabled:
otel_config = OTELConfig(
service_name="my-service",
exporter_type=config.otel_exporter_type,
otlp_endpoint=config.otel_otlp_endpoint,
)
otel_config.setup_logging()
otel_config.setup_tracing()
logger = get_logger(__name__)
logger.info("service_started")
```
**For complete exporter configuration**, see [references/advanced-patterns.md](references/advanced-patterns.md#exporter-configuration)
### Step 5: Implement Instrumentation
Add tracing and logging to key application flows:
```python
# app/use_cases/extract_orders.py
from opentelemetry import trace
from app.shared.logging_setup import get_logger
class ExtractOrdersUseCase:
"""Use case with observability."""
def __init__(self, gateway, publisher) -> None:
self.gateway = gateway
self.publisher = publisher
self.logRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.