Java Spring Boot 日志:日志级别,日志备份,JSON日志和生产最佳做法

2026年8月8日1 次浏览来源:Dev.to阅读原文

正文保留英文原文(机翻易破坏代码与排版),标题/摘要已提供中文

Production-Grade Logging in Spring Boot: A Complete Guide to Logging Levels, Files, JSON Logs, Correlation IDs, and Best Practices Logging is one of the most important parts of a production backend system.

When everything works, you may not think much about logs.

But when production starts returning 500 errors at 2 AM, a customer reports that an API is failing, or a payment request behaves unexpectedly, logs become one of your most important debugging tools.

Poor logging makes production debugging painful.

Good logging helps you answer: What happened?

When did it happen?

Which user triggered it?

Which request caused it?

Which service handled it?

How long did it take?

What failed?

Why did it fail?

What should we investigate next?

In this article, we will build a production-grade logging strategy for a Java Spring Boot application.

1.

What Does Production-Grade Logging Mean?

Production-grade logging is not simply: Production logging should be: Structured Searchable Consistent Secure Configurable Environment-aware Correlated across requests Useful during debugging Suitable for monitoring and alerting A good logging architecture might look like this: The goal is not to log everything.

The goal is to log the right information at the right level.

2.

Understanding Log Levels Spring Boot uses SLF4J as the logging abstraction and commonly uses Logback as the underlying logging implementation.

The most common log levels are: The order represents increasing severity.

TRACE TRACE is the most detailed logging level.

Example: Use TRACE for very detailed diagnostic information.

Usually: Avoid keeping TRACE enabled globally in production because it can generate huge amounts of logs.

3.

DEBUG DEBUG is useful for developers.

Example: Another example: DEBUG logs are useful when troubleshooting a specific feature.

A common production strategy is:

4.

INFO INFO should contain important application events.

For example: Or: Good INFO logs might include: But don't log every line of your application at INFO.

5.

WARN WARN indicates something unexpected or potentially problematic.

Example: Another example: WARN means: "The application is still functioning, but someone should pay attention." Examples: Retry occurred External API is slow Deprecated API was called Configuration is missing but has a fallback Login failed repeatedly Database connection pool is close to its limit

6.

ERROR ERROR represents a failure that needs investigation.

Example: Notice that the exception is passed separately: Instead of: The first approach preserves the stack trace.

7.

Never Log Sensitive Information One of the most important production logging rules is: Logs should never become a source of sensitive data leakage.

Never log: Bad: Good: Even better, depending on your privacy requirements, avoid logging email addresses or other personal identifiers unless there is a clear operational reason.

8.

Use Parameterized Logging Avoid string concatenation.

Don't do this: Prefer: For multiple values: Parameterized logging is cleaner and avoids unnecessary string construction.

9.

Create a Centralized Logging Configuration Spring Boot makes it easy to configure Logback.

You can create: A basic configuration: Now the application produces readable logs such as:

10.

Different Log Files for Different Levels For a production application, you may want separate files.

For example: This makes troubleshooting easier.

For example: contains general application events. contains ERROR events. contains important security/business events. contains HTTP request information.

11.

Creating an ERROR Log File Example: Now ERROR logs can be stored separately.

12.

Why Log Rotation Matters Imagine your application generates: and you never rotate it.

After several months: Your server's disk eventually becomes full.

This can cause much bigger problems.

For example: That's why production applications need: Maximum file size Maximum history Total storage limit Compression Time-based rotation Example:

13.

Application Logs vs Audit Logs Not every important event is an application error.

Consider: This isn't an ERROR.

It is an audit event.

Create a separate audit logger.

Then: This gives you a separate audit stream.

14.

Audit Logging Is Extremely Important For systems involving multiple users, administrators, payments, permissions, or sensitive operations, audit logging becomes extremely valuable.

Examples: Instead of: Use structured information: Now the event can easily be searched.

15.

Logging HTTP Requests For backend systems, request logging is extremely useful.

You want to know: Example: A servlet filter is one approach.

This gives you a basic access log.

16.

Correlation IDs This is one of the most useful concepts in distributed systems.

Imagine a request: One request could generate dozens of logs.

How do you identify which logs belong to the same request?

Use a: Example: Then every service logs: Now you can search the entire system using that ID.

17.

Implementing Correlation ID with MDC SLF4J provides MDC: Example: Now add it to Logback: The resulting log becomes: This is much easier to debug.

18.

Structured Logging Traditional logs look like: Structured logs can look like JSON: This is much easier for log aggregation systems to process.

For production environments, structured JSON logging is often preferable.

19.

Why JSON Logs Are Better for Production Suppose you use: You can query structured fields.

For example: Or: Or: This becomes much more powerful than searching plain text.

20.

Logging Exceptions Correctly Bad: This loses the stack trace.

Better: Now you get: The stack trace is extremely important for debugging.

21.

Don't Log the Same Exception Multiple Times A common mistake is: Every layer catches and logs the same exception.

You might get: Three logs for one problem.

Prefer centralized exception handling when possible.

For Spring Boot: Now unexpected exceptions can be logged centrally.

22.

Logging Business Events Not every useful log is technical.

Business events can be extremely valuable.

Example: This can help answer questions such as: Logging should help both developers and operations teams.

23.

Logging External API Calls Suppose your application calls: You should log useful metadata.

Example: But never log:

24.

Logging Database Operations Don't log every SQL query in production unless you have a specific reason.

For example, enabling: in production can create huge amounts of output.

For development: may be useful.

For production: Instead, monitor slow queries through proper database monitoring and profiling tools.

25.

Different Logging Configuration Per Environment Your logging configuration should change based on the environment.

Development: Production: Example: You can maintain: And configure logging accordingly.

26.

Production Logging Architecture A practical production architecture might look like: This is much better than simply SSHing into a server and running: every time something breaks.

27.

Docker and Kubernetes Logging If your application runs inside Docker or Kubernetes, writing logs only to local files may not be the best strategy.

A common approach is: For example: This allows logs to remain available even when containers are recreated.

28.

Logging in Kubernetes In Kubernetes, pods are disposable.

That means this: is not necessarily a reliable long-term logging strategy.

Instead: This is generally more suitable for cloud-native applications.

29.

Log Levels Should Be Intentional A useful rule: Don't do this: Use: Log levels should communicate severity.

30.

Don't Log Everything More logs do not automatically mean better observability.

Bad: This creates noise.

Instead: Log meaningful events.

31.

Logging Performance Logging can affect application performance.

Especially dangerous: When DEBUG isn't enabled, parameterized logging helps avoid unnecessary string concatenation, but object serialization or expensive argument computation can still cost time.

Avoid: if the computation itself is expensive.

You can gua

分享