agentleFS
piominpiomin/claude-ai-spring-boot/skills/logging-patterns/SKILL.md

logging-patterns

Skill1.4k starsChanged 5 days agoApache-2.0View on GitHub

Java logging best practices with SLF4J, structured logging (JSON), and MDC for request tracing. Includes AI-friendly log formats for AI coding assistant debugging. Use when user asks about logging, debugging application flow, or analyzing logs.

10 other projects use a version of this, 5 of them edited.

Adopted by

Steady: 0 new projects took it in the last 4 weeks, none the 4 weeks before.thin data

Week of Sep 13: 0 new projectsWeek of Sep 20: 0 new projectsWeek of Sep 27: 0 new projectsWeek of Oct 4: 0 new projectsWeek of Oct 11: 0 new projectsWeek of Oct 18: 0 new projectsWeek of Oct 25: 0 new projectsWeek of Nov 1: 0 new projects
Sep 2026Oct 2026Nov 2026
New projects taking a version of this file each week, over the 8 weeks our latest run read: only 0 in all, so this is a hint, not a trend.

Most recently taken up by

Who's talking about piomin/claude-ai-spring-boot

The biggest 5 of 17 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 17

Talked about on GitHub (17 times).

On GitHub · 17

12 more on GitHub

Used with

Projects with it also use java-code-review.

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.
  • zavierSkill

    java-code-review

    Java代码审查技能,通过比较两个git分支进行自动化代码审查

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 9 edited versions we read keep these.

  • 3

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When asking AI to analyze logs:

    line 82
  2. Distinctive:

    Follow request flow via requestId

    line 97
  3. Very specific:

    When Micrometer Tracing is on the classpath, traceId and spanId are automatically included in every JSON log line.

    line 124
  4. Distinctive:

    Don't log full request/response bodies in production

    line 349

“Common” is measured: kept by at least 6 in 10 of the 9 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 Patterns Skill

Rule: JSON is the default log format. Plain text logging is only for local development with human-logs profile. Production, CI/CD, and Kubernetes environments must use structured JSON.

When to Use

  • User says "add logging" / "improve logs" / "debug this"
  • Analyzing application flow from logs
  • Setting up structured logging (JSON)
  • Request tracing with correlation IDs
  • An AI coding assistant needs to analyze application behavior

AI-Friendly Logging

Key insight: JSON logs are better for AI analysis - faster parsing, fewer tokens, direct field access.

Why JSON for AI coding assistants?

# Text format - AI must "interpret" the string
2026-01-29 10:15:30 INFO OrderService - Order 12345 created for user-789, total: 99.99

# JSON format - AI extracts fields directly
{"timestamp":"2026-01-29T10:15:30Z","level":"INFO","orderId":12345,"userId":"user-789","total":99.99}
AspectTextJSON
ParsingRegex/interpretationDirect field access
Token usageHigher (repeated patterns)Lower (structured)
Error extractionParse stack trace textexception field
Filteringgrep patternsjq queries

Recommended Setup for AI-Assisted Development

# application.yml - JSON by default
logging:
  structured:
    format:
      console: logstash  # Spring Boot 4.x

# When YOU need to read logs manually:
# Option 1: Use jq
# tail -f app.log | jq .

# Option 2: Switch profile temporarily
# java -jar app.jar --spring.profiles.active=human-logs

Log Format Optimized for AI Analysis

{
  "timestamp": "2026-01-29T10:15:30.123Z",
  "level": "INFO",
  "logger": "pl.piomin.services.OrderService",
  "message": "Order created",
  "requestId": "req-abc123",
  "traceId": "trace-xyz",
  "orderId": 12345,
  "userId": "user-789",
  "duration_ms": 45,
  "step": "payment_completed"
}

Key fields for AI debugging:

  • requestId - group all logs from same request
  • step - track progress through flow
  • duration_ms - identify slow operations
  • level - quick filter for errors

Reading Logs with AI coding assistants

When asking AI to analyze logs:

# Get recent errors
cat app.log | jq 'select(.level == "ERROR")' | tail -20

# Follow specific request
cat app.log | jq 'select(.requestId == "req-abc123")'

# Find slow operations
cat app.log | jq 'select(.duration_ms > 1000)'

AI can then:

  1. Parse JSON directly (no guessing)
  2. Follow request flow via requestId
  3. Identify exactly where errors occurred
  4. Measure timing between steps

Quick Setup (Spring Boot 4.x)

Native Structured Logging

Spring Boot 4.x has built-in JSON logging — no extra dependencies required.

# application.yml — this is the REQUIRED default for every app
logging:
  structured:
    format:
      console: logstash    # or "ecs" for Elastic Common Schema

# Supported formats:
#   logstash - JSON (most common, compatible with ELK and OpenTelemetry Collector)
#   ecs      - Elastic Common Schema (native Elastic/Kibana integration)
#   gelf     - Graylog Extended Log Format

OpenTelemetry Integration

When Micrometer Tracing is on the classpath, traceId and spanId are automatically included in every JSON log line. This allows OTel Collector to correlate logs with distributed traces.

# application.yml — tracing + structured logging together
management:
  tracing:
    sampling:
      probability: 1.0

logging:
  structured:
    format:
      console: logstash
  pattern:
    level: "%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]"

Output:

{"@timestamp":"2026-01-29T10:15:30.123Z","level":"INFO","logger_name":"pl.piomin.services.OrderService","message":"Order created","traceId":"abc123def456","spanId":"789xyz","service.name":"order-service"}

The traceId field in JSON logs is the same trace ID visible in Jaeger, Tempo, or any OTel-compatible backend — enabling direct log-to-trace correlation.

Profile-Based Switching

# application.yml (default - JSON for AI/prod)
spring:
  profiles:
    default: json-logs

---
spring:
  config:
    activate:
      on-profile: json-logs
logging:
  structured:
    format:
      console: logstash

---
spring:
  config:
    activate:
      on-profile: human-logs
# No structured format = human-readable default
logging:
  pattern:
    console: "%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n"

Usage:

# Default: JSON (for AI, CI/CD, production)
./mvnw spring-boot:run

# Human-readable when needed
./mvnw spring-boot:run -Dspring.profiles.active=human-logs

Setup for Spring Boot < 3.4 (Legacy)

Logstash Logback Encoder

pom.xml:

<dependency>
    <groupId>net.logstash.logback</groupId>
    <artifactId>logstash-logback-encoder</artifactId>
    <version>7.4</version>
</dependency>

logback-spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <!-- JSON (default) -->
    <springProfile name="!human-logs">
        <appender name="JSON" class="ch.qos.logback.core.ConsoleAppender">
            <encoder class="net.logstash.logback.encoder.LogstashEncoder">
                <includeMdcKeyName>requestId</includeMdcKeyName>
                <includeMdcKeyName>userId</includeMdcKeyName>
            </encoder>
        </appender>
        <root level="INFO">
            <appender-ref ref="JSON"/>
        </root>
    </springProfile>

    <!-- Human-readable (optional) -->
    <springProfile name="human-logs">
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n</pattern>
            </encoder>
        </appender>
        <root level="INFO">
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>

</configuration>

Adding Custom Fields (Logstash Encoder)

import static net.logstash.logback.argument.StructuredArguments.kv;

// Fields appear as separate JSON keys
log.info("Order created",
    kv("orderId", order.getId()),
    kv("userId", user.getId()),
    kv("total", order.getTotal()),
    kv("step", "order_created")
);

// Output:
// {"message":"Order created","orderId":123,"userId":"u-456","total":99.99,"step":"order_created"}

SLF4J Basics

Logger Declaration

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    // use `log` directly for logging
}

Parameterized Logging

// ✅ GOOD: Evaluated only if level enabled
log.debug("Processing order {} for user {}", orderId, userId);

// ❌ BAD: Always concatenates
log.debug("Processing order " + orderId + " for user " + userId);

// ✅ For expensive operations
if (log.isDebugEnabled()) {
    log.debug("Order details: {}", order.toDetailedString());
}

Exception Logging

// ✅ GOOD: Pass exception as last argument
try {
    processOrder(order);
} catch (PaymentException e) {
    log.error("Payment failed for order {}", order.getId(), e);
}

// ❌ BAD: Loses stack trace
log.error("Payment failed: " + e.getMessage());

// ❌ BAD: Exception in placeholder (toString only)
log.error("Payment failed for order {}: {}", order.getId(), e);

// ❌ BAD: No context - useless when reading logs later
log.error("Error occurred", e);

// ✅ GOOD: Key-value pairs become separate JSON fields (SLF4J 2 fluent API)
log.atError()
    .addKeyValue("orderId", orderId)
    .addKeyValue("step", "payment")
    .setCause(e)
    .log("Order processing failed");

Log Once, at the Boundary

// ❌ BAD: Log-and-rethrow - the same stack trace appears once per layer
try {
    paymentClient.charge(order);
} catch (PaymentException e) {
    log.error("Payment failed", e);
    throw e;
}

// ✅ GOOD: Wrap with context and rethrow, no log
try {
    paymentClient.charge(order);
} catch (PaymentException e) {
    throw new OrderProcessingException("Payment failed for order " + order.id(), e);
}

The @RestControllerAdvice handler (or message listener / scheduled job) that ends the flow logs the exception once. Expected business errors (404, validation) are WARN or DEBUG without stack trace; only unexpected failures are ERROR with the throwable.

What NOT to Log

// ❌ NEVER
log.info("Login user={} password={}", username, password);  // credentials
log.debug("Calling API with token {}", jwt);                 // tokens, API keys, session IDs
log.info("Payment card={}", cardNumber);                     // full card number / CVV
log.info("Created customer {}", customer);                   // toString() may dump email, address, IBAN

// ✅ Identify, don't expose
log.info("Login attempted userId={}", userId);
log.info("Payment authorised cardLast4={}", last4);
log.info("Created customer customerId={}", customer.id());
  • Sensitive: passwords, secrets, tokens, Authorization/Cookie headers, card data, national IDs, health data, PII (email, phone, address, birth date)
  • Records print every component in toString() - log the ID or override toString() for records carrying PII
  • Don't log full request/response bodies in production

Log Levels Guide

LevelWhen to use
ERRORSomething broke — action needed. Failed payment, unrecoverable state
WARNSomething unexpected but handled. Retry succeeded, fallback used
INFOBusiness events. Order created, user logged in, job completed
DEBUGTechnical details. SQL queries, HTTP requests, cache hits
TRACEVerbose internals. Method entry/exit, loop iterations

MDC (Mapped Diagnostic Context)

MDC attaches context (request ID, user ID) to every log line in the current thread automatically.

Request Filter for Correlation IDs

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MdcFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String requestId = httpRequest.getHeader("X-Request-Id");
            if (requestId == null) {
                requestId = UUID.randomUUID().toString().substring(0, 8);
            }
            MDC.put("requestId", requestId);
            MDC.put("clientIp", httpRequest.getRemoteAddr());

            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }
}

MDC in Service Layer

@Service
public class OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    public Order createOrder(OrderRequest request) {
        MDC.put("userId", request.userId());
        MDC.put("orderId", String.valueOf(request.orderId()));

        log.info("Creating order");
        // All subsequent log lines in this thread automatically include userId and orderId

        return processOrder(request);
    }
}

MDC with Virtual Threads

Virtual threads don't inherit MDC from parent threads. Use TaskDecorator to propagate:

@Configuration
public class AsyncConfig {

    @Bean
    public TaskDecorator mdcTaskDecorator() {
        return runnable -> {
            Map<String, String> context = MDC.getCopyOfContextMap();
            return () -> {
                if (context != null) {
                    MDC.setContextMap(context);
                }
                try {
                    runnable.run();
                } finally {
                    MDC.clear();
                }
            };
        };
    }
}

The decorator only applies to Spring-managed executors (@Async, injected ThreadPoolTaskExecutor). CompletableFuture.supplyAsync(...) without an executor runs on the common pool and loses MDC - always pass the Spring executor.


Quick Reference

PatternUse
LoggerFactory.getLogger(MyClass.class)Declare logger (no @Slf4j)
log.info("msg {}", var)Parameterized logging
log.error("msg {}", var, exception)Log with stack trace
MDC.put("key", "value")Add context to all logs in thread
MDC.clear()Clean up in finally block
log.atInfo().addKeyValue("k", v).log("msg")Key-value pairs as JSON fields
logging.structured.format.console: logstashEnable JSON (Spring Boot 4.x)
kv("field", value)Structured argument (Logstash encoder)

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.