agentleFS
jars-demojars-demo/jars-skills/skills/logging/SKILL.md

logging

Skill0 starsChanged 32 days agoMITView on GitHub

Add, improve, and fix structured logging in an application. Use when the user asks to add logging, fix noisy logs, improve log output, add structured logs, set up log levels, replace console.log with a real logger, add request tracing, or make logs parseable by a log aggregator like Datadog, CloudWatch, or Loki.

  • Reads credentials

25 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use convention-learner, opentelemetry and 6 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • codewithmukeshSkill

    convention-learner

    Detects and enforces project-specific coding conventions by analyzing existing codebase patterns. Learns naming conventions, folder structure, test organization, and coding style from the existing code. Load when: "conventions", "coding standards", "project patterns", "enforce style", "detect patterns", "learn conventions", "code consistency".

    Also in 3 projects that use this

  • codewithmukeshSkill

    opentelemetry

    OpenTelemetry observability for .NET 10 applications. Covers traces, metrics, and logs using the OpenTelemetry SDK with OTLP export. Includes custom ActivitySource, IMeterFactory metrics, resource configuration, and Aspire Dashboard integration. Load this skill when setting up distributed tracing, custom metrics, OTLP export, or when the user mentions "OpenTelemetry", "OTLP", "traces", "spans", "Activity", "ActivitySource", "metrics", "IMeterFactory", "Meter", "Counter", "Histogram", "Gauge", "telemetry", "observability", "distributed tracing", "OTEL", or "Aspire Dashboard".

    Also in 3 projects that use this

  • MovGP0Skill

    modern-csharp

    Modern C# style guidance for Bendex and MicroSea code changes, including primary constructors, expression-bodied members, var usage, target-typed new, lambdas, and pattern matching.

    Also in 3 projects that use this

  • junhjangSkill

    configuration

    Adding a new config file, adding a field, or wiring a config consumer. Enforces schema validation at startup (no permissive defaults), env-var indirection for secrets, layered config (defaults / per-env / operator-override), hot-reload explicit per field.

    Also in 4 projects that use this

  • MicrosoftSkill

    resilience

    Apply resilience patterns (retry, backoff, circuit breaking) when writing or reviewing code that makes outbound HTTP/REST calls, database operations, or any I/O that can experience transient failures. Use this skill when: (1) writing new code that calls external services or APIs, (2) reviewing code that uses fetch, HTTP clients, or service-to-service calls, (3) adding queue consumers or workers that interact with remote systems, (4) debugging intermittent failures in production.

    Also in 3 projects that use this

  • hongyuancSkill

    vertical-slice

    Build and evaluate a production-quality vertical slice before advancing from Pre-Production to Production.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

10 rules. 0 are common, 6 are distinctive, and 4 are very specific to this project.

  • 0

    Common

    Most of the 20 edited versions we read keep these.

  • 6

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Add logs that help you diagnose production incidents in minutes, not hours.

    line 8
  2. Distinctive:

    Read the codebase before adding logs: Check what logger is already in use.

    line 13
  3. Distinctive:

    Logs are for operators, not developers: Write messages that help someone who didn't write the code understand what happened and why.

    line 21
  4. Distinctive:

    If a logger exists, use it.

    line 38
  5. Very specific:

    Never use string interpolation: logger.info("User " + id + " logged in") — that's unparseable.

    line 82
  6. Distinctive:

    Don't log the same error multiple times as it bubbles up the call stack — one log per error at the boundary where you decide what to do …

    line 220
  7. Distinctive:

    Always include context: IDs, operation names, relevant input values (scrubbed).

    line 222
  8. Very specific:

    Use your logger's redact option (pino) or a scrubber middleware rather than manually checking every log call.

    line 237
  9. Very specific:

    When you find raw console.log or print calls, replace them:

    line 244
  10. Very specific:

    Do this incrementally — replace a file at a time, verify the output, commit.

    line 256

“Common” is measured: kept by at least 6 in 10 of the 20 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Logging

Add logs that help you diagnose production incidents in minutes, not hours. Logs that are too noisy are as useless as no logs — the goal is the right information at the right level.

Ground rules

  • Read the codebase before adding logs. Check what logger is already in use. Never introduce a second logging library into a project that already has one.
  • Use structured logging. Key-value pairs or JSON, not interpolated strings. Aggregators (Datadog, CloudWatch, Loki, Splunk) can filter and alert on fields; they cannot parse sentences.
  • Never log secrets, PII, or credentials. Scrub before logging: passwords, tokens, full credit card numbers, SSNs, raw request bodies that may contain any of the above.
  • Pick the right level. A miscategorised level destroys the signal-to-noise ratio.
  • Logs are for operators, not developers. Write messages that help someone who didn't write the code understand what happened and why.

Step 0: Check what's already there

# Find the existing logger
grep -r "require.*logger\|import.*logger\|from.*logging\|winston\|pino\|bunyan\|log4j\|zap\|slog\|sentry" \
  --include="*.ts" --include="*.js" --include="*.py" --include="*.go" -l | head -10

# Check for raw console/print usage that should be replaced
grep -rn "console\.log\|console\.error\|print(\|fmt\.Print" \
  --include="*.ts" --include="*.js" --include="*.py" --include="*.go" | head -20

If a logger exists, use it. Read its configuration before adding anything.


Log levels — when to use each

LevelUse it for
ERRORSomething failed and a human needs to act. Unexpected exceptions, failed payments, data corruption.
WARNSomething unexpected happened but the system recovered. Deprecated API usage, retried operations, config fallbacks.
INFONormal significant events. Service started, user logged in, job completed, request served.
DEBUGDetail useful during development or incident investigation. Query params, intermediate values, branch decisions. Off in production by default.
TRACEVery fine-grained: every function call, loop iteration, raw payloads. Never on in production.

The most common mistake: using ERROR for expected user errors (validation failures, 404s) and INFO for every line of code. Both destroy the signal.


Structured logging patterns

Node.js — pino (preferred) or winston

// Setup — do this once, export the logger
import pino from "pino";

export const logger = pino({
  level: process.env.LOG_LEVEL ?? "info",
  // In production, output raw JSON. In dev, use pino-pretty for human output.
  transport:
    process.env.NODE_ENV !== "production"
      ? { target: "pino-pretty", options: { colorize: true } }
      : undefined,
  // Redact sensitive fields wherever they appear in log objects
  redact: ["req.headers.authorization", "body.password", "body.token", "*.creditCard"],
});

// Usage
logger.info({ userId: user.id, plan: user.plan }, "User upgraded plan");
logger.error({ err, orderId }, "Payment failed");  // pino serializes err automatically
logger.debug({ query, params }, "Running query");

Never use string interpolation: logger.info("User " + id + " logged in") — that's unparseable. Always pass a context object as the first argument.

Python — structlog (preferred) or standard logging

# Setup
import structlog
import logging

logging.basicConfig(
    format="%(message)s",
    level=logging.getLevelName(os.getenv("LOG_LEVEL", "INFO")),
)

structlog.configure(
    processors=[
        structlog.contextvars.merge_contextvars,
        structlog.stdlib.add_log_level,
        structlog.stdlib.add_logger_name,
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.JSONRenderer(),   # swap for ConsoleRenderer() in dev
    ],
    wrapper_class=structlog.make_filtering_bound_logger(logging.root.level),
    logger_factory=structlog.stdlib.LoggerFactory(),
)

log = structlog.get_logger()

# Usage
log.info("user.plan_upgraded", user_id=user.id, plan=user.plan)
log.error("payment.failed", order_id=order_id, error=str(e))
log.debug("db.query", sql=query, params=params)

Go — slog (stdlib, Go 1.21+) or zap

// Setup with slog (no dependency)
import "log/slog"

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelInfo,
}))
slog.SetDefault(logger)

// Usage
slog.Info("user.plan_upgraded", "user_id", userID, "plan", plan)
slog.Error("payment.failed", "order_id", orderID, "err", err)
slog.Debug("db.query", "sql", query)

Request logging (HTTP)

Log every inbound request at INFO with: method, path, status code, duration, and a request/trace ID. Do not log request bodies by default — they may contain PII.

Express / Node.js

import { randomUUID } from "crypto";

app.use((req, res, next) => {
  const requestId = (req.headers["x-request-id"] as string) ?? randomUUID();
  const start = Date.now();

  // Attach a child logger with the request ID bound to every log in this request
  req.log = logger.child({ requestId });

  res.on("finish", () => {
    req.log.info(
      {
        method: req.method,
        path: req.path,
        status: res.statusCode,
        durationMs: Date.now() - start,
      },
      "request completed"
    );
  });

  next();
});

FastAPI / Python

import time, uuid
from fastapi import Request

@app.middleware("http")
async def log_requests(request: Request, call_next):
    request_id = request.headers.get("x-request-id", str(uuid.uuid4()))
    start = time.perf_counter()

    with structlog.contextvars.bound_contextvars(request_id=request_id):
        response = await call_next(request)
        log.info(
            "request.completed",
            method=request.method,
            path=request.url.path,
            status=response.status_code,
            duration_ms=round((time.perf_counter() - start) * 1000, 2),
        )

    return response

Error logging

Log errors with the full stack trace and enough context to reproduce:

// Node.js — pino serialises err correctly when passed as a field
try {
  await processOrder(orderId);
} catch (err) {
  logger.error({ err, orderId, userId }, "Order processing failed");
  throw err;   // re-throw; don't swallow unless you have a recovery path
}
# Python — structlog + exc_info captures the traceback
try:
    process_order(order_id)
except Exception:
    log.error("order.processing_failed", order_id=order_id, exc_info=True)
    raise

Rules:

  • Log at the point where the error is handled, not where it propagates.
  • Don't log the same error multiple times as it bubbles up the call stack — one log per error at the boundary where you decide what to do with it.
  • Always include context: IDs, operation names, relevant input values (scrubbed).

What not to log

Don't logReason
Passwords, tokens, API keysSecrets in logs are a security incident
Full credit card numbers, SSNsPII / compliance (PCI-DSS, GDPR)
Raw request/response bodiesMay contain any of the above
Every function entry/exit at INFONoise that buries real events
Stack traces at DEBUGUse ERROR or WARN for exceptions
IDs that are UUIDs at TRACE everywhereOnly useful if a bug is already known

Use your logger's redact option (pino) or a scrubber middleware rather than manually checking every log call.


Replacing console.log / print

When you find raw console.log or print calls, replace them:

// Before
console.log("Starting job", jobId);
console.error("Failed:", err);

// After
logger.info({ jobId }, "Job started");
logger.error({ err, jobId }, "Job failed");

Do this incrementally — replace a file at a time, verify the output, commit. Don't replace every console.log in the repo in one pass.


Log aggregator output format

For Datadog, CloudWatch, Loki, or any aggregator, output must be JSON on stdout:

{"level":"info","time":"2024-01-15T10:30:00.123Z","requestId":"abc-123","userId":"42","msg":"User upgraded plan","plan":"pro"}

Key fields every line should have:

  • level — string (info, error, etc.)
  • time — ISO 8601 timestamp
  • msg — human-readable description of the event
  • service — name of the service (set once at logger init, not per call)
  • Any IDs relevant to the operation (userId, orderId, requestId)

Checklist

  • Existing logger found and used — no second library introduced
  • All console.log / print replaced with structured logger calls
  • Context object passed as first arg, message as second (logger.info({...}, "msg"))
  • Log levels match severity — no ERROR for 404s, no INFO for every function call
  • redact or scrubber configured for passwords, tokens, PII
  • Every HTTP request logs method, path, status, duration, and request ID
  • Errors logged with full context at the handling boundary, not at every layer
  • Output is JSON in production, human-readable in development
  • LOG_LEVEL configurable via environment variable

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.