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
Most recently taken up by
- ku5ic/claude-kittheir own version, first seen Nov 4, 2026
- decebals/claude-code-javaedited, first seen Nov 1, 2026
- piomin/claude-ai-quarkusedited, first seen Oct 25, 2026
- mvonline/claude-skillsedited, first seen Oct 11, 2026
- Abdox-menara/guard-skillstheir own version, first seen Aug 24, 2026
- techdeveloper-org/mcp-jenkins-citheir own version, first seen Aug 12, 2026
Who's talking about piomin/claude-ai-spring-boot
- sudosubin/agents.nix“claude-code-marketplaces.github.piomin.claude-ai-spring-boot: 1.2.0 → 1.2.1”GitHub · Nov 8, 2026
- sudosubin/agents.nix“agent-skills.github.piomin.claude-ai-spring-boot: 1.2.0 → 1.2.1”GitHub · Nov 8, 2026
- sudosubin/agents.nix“claude-code-plugins.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-28 → 1.2.0”GitHub · Oct 30, 2026
- sudosubin/agents.nix“agent-skills.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-27 → 1.2.0”GitHub · Oct 30, 2026
- sudosubin/agents.nix“claude-code-marketplaces.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-28 → 1.2.0”GitHub · Oct 30, 2026
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
- Nov 8, 2026claude-code-marketplaces.github.piomin.claude-ai-spring-boot: 1.2.0 → 1.2.1 — sudosubin/agents.nix0 reactions
- Nov 8, 2026agent-skills.github.piomin.claude-ai-spring-boot: 1.2.0 → 1.2.1 — sudosubin/agents.nix0 reactions
- Oct 30, 2026claude-code-plugins.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-28 → 1.2.0 — sudosubin/agents.nix0 reactions
- Oct 30, 2026agent-skills.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-27 → 1.2.0 — sudosubin/agents.nix0 reactions
- Oct 30, 2026claude-code-marketplaces.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-28 → 1.2.0 — sudosubin/agents.nix0 reactions
12 more on GitHub
- Oct 29, 2026agent-skills.github.piomin.claude-ai-spring-boot: 9f16f8d → 1f0e36f — sudosubin/agents.nix0 reactions
- Oct 28, 2026claude-code-plugins.github.piomin.claude-ai-spring-boot: init at 0-unstable-2026-10-28 — sudosubin/agents.nix0 reactions
- Oct 28, 2026claude-code-marketplaces.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-27 → 0-unstable-2026-10-28 — sudosubin/agents.nix0 reactions
- Oct 28, 2026claude-code-marketplaces.github.piomin.claude-ai-spring-boot: init at 0-unstable-2026-10-27 — sudosubin/agents.nix0 reactions
- Oct 27, 2026agent-skills.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-18 → 0-unstable-2026-10-27 — sudosubin/agents.nix0 reactions
- Oct 27, 2026Retrospective: align the plugin with spring-person-api-claude 3.4.3 and crud-ui-blueprint 1.2.3 — mmartofel/claude-ai-spring-boot0 reactions · 3 comments
- Oct 18, 2026agent-skills.github.piomin.claude-ai-spring-boot: 0d23826 → cf876a1 — sudosubin/agents.nix0 reactions
- Oct 18, 2026agent-skills.github.piomin.claude-ai-spring-boot: 0-unstable-2026-10-16 → 0-unstable-2026-10-18 — sudosubin/agents.nix0 reactions
- Oct 16, 2026agent-skills.github.piomin.claude-ai-spring-boot: 0-unstable-2026-04-27 → 0-unstable-2026-10-16 — sudosubin/agents.nix0 reactions
- Oct 1, 2026agent-skills.github.piomin.claude-ai-spring-boot: init at 0-unstable-2026-04-27 — sudosubin/agents.nix0 reactions
- Mar 29, 2026Create workspace-template SKILL.md with wizard flow — riccardomerolla/llm4zio0 reactions · 1 comment
- Mar 21, 2026feat: support GitHub tree URLs in GitInstaller — neovateai/neovate-desktop0 reactions · 1 comment
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.
zavierSkilljava-code-review
Java代码审查技能,通过比较两个git分支进行自动化代码审查
Also in 3 projects that use this
Other versions10 projects use a version of this.
Word for word · 0
None found.
Edited · 5
- decebals/claude-code-java★ 76344% same
- piomin/claude-ai-quarkus★ 740% same
- iCesofT/awesome-ai★ 144% same
- piomin/spring-boot-app-with-claudecode★ 188% same
- mvonline/claude-skills★ 045% same
Wrote their own version · 5
- DIL8654/claude-code-dotnet-template★ 8same name
- ku5ic/claude-kit★ 2same name
- Abdox-menara/guard-skills★ 0same name
- Nadav011/apex-skills★ 0same name
- techdeveloper-org/mcp-jenkins-ci★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository7 other files it gives its agents.
- code-qualitySkill
- conventionsSkill
- design-patternsSkill
- java-modernSkill
- jpa-patternsSkill
- spring-bootSkill
- testing-patternsSkill
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
- Distinctive: line 82
When asking AI to analyze logs:
- Distinctive: line 97
Follow request flow via requestId
- Very specific: line 124
When Micrometer Tracing is on the classpath, traceId and spanId are automatically included in every JSON log line.
- Distinctive: line 349
Don't log full request/response bodies in production
“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.
Files
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}| Aspect | Text | JSON |
| Parsing | Regex/interpretation | Direct field access |
| Token usage | Higher (repeated patterns) | Lower (structured) |
| Error extraction | Parse stack trace text | exception field |
| Filtering | grep patterns | jq 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-logsLog 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 requeststep- track progress through flowduration_ms- identify slow operationslevel- 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:
- Parse JSON directly (no guessing)
- Follow request flow via requestId
- Identify exactly where errors occurred
- 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 FormatOpenTelemetry 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-logsSetup 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/Cookieheaders, card data, national IDs, health data, PII (email, phone, address, birth date) - Records print every component in
toString()- log the ID or overridetoString()for records carrying PII - Don't log full request/response bodies in production
Log Levels Guide
| Level | When to use |
ERROR | Something broke — action needed. Failed payment, unrecoverable state |
WARN | Something unexpected but handled. Retry succeeded, fallback used |
INFO | Business events. Order created, user logged in, job completed |
DEBUG | Technical details. SQL queries, HTTP requests, cache hits |
TRACE | Verbose 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
| Pattern | Use |
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: logstash | Enable JSON (Spring Boot 4.x) |
kv("field", value) | Structured argument (Logstash encoder) |
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
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.

