MCP HubMCP Hub
SKILL·20D3C8

go-observability

eduardo-sl
업데이트됨 22 days ago
4 조회
68
9
68
GitHub에서 보기
디자인apidesign

정보

이 Claude Skill은 구조화된 로깅(slog), 분산 추적(OpenTelemetry), 메트릭(Prometheus)을 사용해 Go 서비스에 포괄적인 가시성을 구현하는 데 도움을 줍니다. 코드베이스에 계측, 로깅, 추적 또는 메트릭을 추가해야 할 때 사용하세요. 이 스킬은 특히 가시성 패턴에 초점을 맞추며, 다른 스킬에서 다루는 성능 프로파일링이나 오류 처리와는 구분됩니다.

빠른 설치

Claude Code

추천
기본
npx skills add eduardo-sl/go-agent-skills -a claude-code
플러그인 명령대체
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 클론대체
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-observability

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Go Observability

Observability is not optional for production services. Every service must produce structured logs, expose metrics, and propagate trace context. Use the stdlib log/slog for logging and OpenTelemetry for tracing and metrics.

1. Structured Logging with slog

Use log/slog (Go 1.21+) as the standard logging package:

// ✅ Good — structured, leveled logging
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelInfo,
}))

logger.Info("user created",
    slog.String("user_id", user.ID),
    slog.String("email", user.Email),
    slog.Duration("latency", elapsed),
)
// ❌ Bad — unstructured printf-style logging
log.Printf("user %s created with email %s in %v", user.ID, user.Email, elapsed)

Pass logger via context or dependency injection:

// ✅ Good — logger as dependency
type UserService struct {
    logger *slog.Logger
    store  UserStore
}

func NewUserService(logger *slog.Logger, store UserStore) *UserService {
    return &UserService{
        logger: logger.With(slog.String("component", "user_service")),
        store:  store,
    }
}
// ❌ Bad — global logger
var logger = slog.Default()

Create child loggers with scoped attributes:

func (s *UserService) CreateUser(ctx context.Context, req CreateUserReq) error {
    log := s.logger.With(
        slog.String("method", "CreateUser"),
        slog.String("request_id", middleware.RequestID(ctx)),
    )

    log.Info("creating user", slog.String("email", req.Email))

    if err := s.store.Insert(ctx, req); err != nil {
        log.Error("failed to create user", slog.Any("error", err))
        return fmt.Errorf("create user: %w", err)
    }

    log.Info("user created successfully")
    return nil
}

Log levels — use them consistently:

LevelUse for
DebugVerbose diagnostic info, disabled in production
InfoNormal operations: request received, job completed
WarnRecoverable issues: retry succeeded, deprecated usage
ErrorFailures requiring attention: DB down, external call failed

NEVER log at Error level for expected conditions (e.g., user not found → Info or Warn).

Sensitive data — NEVER log:

  • Passwords, tokens, API keys
  • Full credit card numbers, SSNs
  • Raw request bodies containing PII
// ✅ Good — redacted
logger.Info("auth attempt", slog.String("user", email), slog.Bool("success", ok))

// ❌ Bad — leaks credentials
logger.Info("auth attempt", slog.String("password", password))

2. Distributed Tracing with OpenTelemetry

Initialize the tracer provider:

func initTracer(ctx context.Context, serviceName string) (*trace.TracerProvider, error) {
    exporter, err := otlptrace.New(ctx, otlptracehttp.NewClient())
    if err != nil {
        return nil, fmt.Errorf("create exporter: %w", err)
    }

    tp := trace.NewTracerProvider(
        trace.WithBatcher(exporter),
        trace.WithResource(resource.NewWithAttributes(
            semconv.SchemaURL,
            semconv.ServiceNameKey.String(serviceName),
        )),
    )
    otel.SetTracerProvider(tp)
    otel.SetTextMapPropagator(propagation.TraceContext{})

    return tp, nil
}

Create spans for significant operations:

func (s *UserService) GetUser(ctx context.Context, id string) (*User, error) {
    ctx, span := otel.Tracer("user-service").Start(ctx, "GetUser")
    defer span.End()

    span.SetAttributes(attribute.String("user.id", id))

    user, err := s.store.FindByID(ctx, id)
    if err != nil {
        span.RecordError(err)
        span.SetStatus(codes.Error, err.Error())
        return nil, fmt.Errorf("get user %s: %w", id, err)
    }

    return user, nil
}

Span naming conventions:

// ✅ Good — operation name, not function name
ctx, span := tracer.Start(ctx, "GetUser")
ctx, span := tracer.Start(ctx, "db.query")
ctx, span := tracer.Start(ctx, "http.request")

// ❌ Bad — too verbose or too generic
ctx, span := tracer.Start(ctx, "github.com/myorg/myapp/internal/user.(*Service).GetUser")
ctx, span := tracer.Start(ctx, "doStuff")

Always propagate context through the call chain:

// ✅ Good — context flows through
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context() // carries trace context from middleware
    user, err := h.service.GetUser(ctx, id)
    // ...
}

// ❌ Bad — trace context lost
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
    user, err := h.service.GetUser(context.Background(), id) // breaks trace chain
    // ...
}

3. Metrics with OpenTelemetry / Prometheus

Define metrics at package level:

var (
    requestDuration = promauto.NewHistogramVec(
        prometheus.HistogramOpts{
            Name:    "http_request_duration_seconds",
            Help:    "Duration of HTTP requests in seconds.",
            Buckets: prometheus.DefBuckets,
        },
        []string{"method", "path", "status"},
    )

    requestsTotal = promauto.NewCounterVec(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Total number of HTTP requests.",
        },
        []string{"method", "path", "status"},
    )
)

Metric naming conventions:

<namespace>_<subsystem>_<name>_<unit>

http_request_duration_seconds     ✅ (unit in name)
http_requests_total               ✅ (counter with _total suffix)
db_connections_active             ✅ (gauge, no suffix needed)
user_signups                      ❌ (missing _total for counter)
requestLatency                    ❌ (camelCase, no unit)

Instrument HTTP middleware:

func MetricsMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        ww := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}

        next.ServeHTTP(ww, r)

        duration := time.Since(start).Seconds()
        status := strconv.Itoa(ww.statusCode)

        requestDuration.WithLabelValues(r.Method, r.URL.Path, status).Observe(duration)
        requestsTotal.WithLabelValues(r.Method, r.URL.Path, status).Inc()
    })
}

Use histograms for latencies, counters for totals, gauges for current state:

TypeUse forExample
CounterMonotonically increasing valuesRequests total, errors total
GaugeValues that go up and downActive connections, queue depth
HistogramDistribution of valuesRequest latency, response size

Keep cardinality low — avoid high-cardinality labels:

// ✅ Good — bounded label values
requestsTotal.WithLabelValues(r.Method, routePattern, status)

// ❌ Bad — unbounded cardinality (user IDs, request IDs)
requestsTotal.WithLabelValues(r.Method, r.URL.Path, userID)

4. Connecting Logs, Traces, and Metrics

Inject trace ID into log entries:

func LogWithTrace(ctx context.Context, logger *slog.Logger) *slog.Logger {
    spanCtx := trace.SpanContextFromContext(ctx)
    if !spanCtx.IsValid() {
        return logger
    }
    return logger.With(
        slog.String("trace_id", spanCtx.TraceID().String()),
        slog.String("span_id", spanCtx.SpanID().String()),
    )
}

// Usage in handlers/services:
func (s *Service) Process(ctx context.Context) error {
    log := LogWithTrace(ctx, s.logger)
    log.Info("processing started") // log includes trace_id and span_id
    // ...
}

5. Graceful Shutdown of Telemetry

func main() {
    ctx := context.Background()

    tp, err := initTracer(ctx, "my-service")
    if err != nil {
        log.Fatalf("init tracer: %v", err)
    }

    // Ensure all spans are flushed on shutdown
    defer func() {
        shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        if err := tp.Shutdown(shutdownCtx); err != nil {
            log.Printf("tracer shutdown: %v", err)
        }
    }()

    // ... start server
}

Verification Checklist

  1. All logging uses log/slog with structured key-value pairs, not fmt.Printf or log.Printf
  2. Logger is injected as a dependency, not used as a global
  3. No sensitive data (passwords, tokens, PII) in log output
  4. Trace context is propagated through all function calls via context.Context
  5. Spans are created for significant operations (DB calls, HTTP requests, business logic)
  6. Spans record errors with span.RecordError(err) and set error status
  7. Metrics follow naming conventions: _seconds, _total, _bytes
  8. No high-cardinality labels (user IDs, request IDs) in metrics
  9. Telemetry providers are shut down gracefully on service exit
  10. Trace IDs are included in log entries for correlation

GitHub 저장소

eduardo-sl/go-agent-skills
경로: skills/(safety)/go-observability
0
FAQ

자주 묻는 질문

go-observability Skill이란 무엇인가요?

go-observability은(는) eduardo-sl이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 go-observability 관련 작업을 수행할 수 있게 합니다.

go-observability은(는) 어떻게 설치하나요?

이 페이지의 설치 명령을 사용하세요. go-observability을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.

go-observability은(는) 어떤 카테고리에 속하나요?

go-observability은(는) 디자인 카테고리에 속합니다.

go-observability은(는) 무료로 사용할 수 있나요?

네. go-observability은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.

연관 스킬

executing-plans
디자인

executing-plans 스킬은 검토 체크포인트가 포함된 통제된 배치로 실행할 완전한 구현 계획이 있을 때 사용합니다. 이 스킬은 계획을 불러와 비판적으로 검토한 후, 소규모 배치(기본값 3개 작업)로 작업을 실행하면서 각 배치 사이에 진행 상황을 아키텍트 검토를 위해 보고합니다. 이를 통해 내재된 품질 관리 체크포인트를 갖춘 체계적인 구현이 보장됩니다.

스킬 보기
requesting-code-review
디자인

이 스킬은 코드 변경 사항을 요구 사항에 따라 분석하기 위해 코드 리뷰어 하위 에이전트를 호출합니다. 작업 완료 후, 주요 기능 구현 후, 또는 메인 브랜치에 병합하기 전에 사용해야 합니다. 이 리뷰는 현재 구현체와 원래 계획을 비교하여 문제를 조기에 발견하는 데 도움이 됩니다.

스킬 보기
connect-mcp-server
디자인

이 스킬은 개발자들이 HTTP, stdio 또는 SSE 전송 방식을 통해 MCP 서버를 Claude Code에 연결하는 포괄적인 가이드를 제공합니다. GitHub, Notion 및 사용자 정의 API와 같은 외부 서비스를 통합하기 위한 설치, 구성, 인증 및 보안을 다룹니다. MCP 통합 설정, 외부 도구 구성 또는 Claude의 모델 컨텍스트 프로토콜 작업 시 활용하세요.

스킬 보기
web-cli-teleport
디자인

이 스킬은 작업 분석을 기반으로 개발자가 Claude Code 웹 인터페이스와 CLI 인터페이스 중 선택할 수 있도록 돕고, 두 환경 간 원활한 세션 텔레포트를 가능하게 합니다. 웹, CLI 또는 모바일 환경 전환 시 세션 상태와 컨텍스트를 관리하여 워크플로를 최적화합니다. 다양한 단계에서 서로 다른 도구가 필요한 복잡한 프로젝트에 사용하세요.

스킬 보기