Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Microservices · Lesson 12

Monitoring and Logging in Microservices

Observing Distributed Services

Monitoring tells you whether a service is healthy and meeting its objectives, while logging explains individual events. In microservices, a request may cross several processes, so correlation and consistent dimensions are essential. Observability should help answer what failed, where, and why.

Recording a Useful Request Event

Structured logs should include stable fields rather than only a sentence. Do not log credentials, tokens, or unnecessary personal information.

import java.time.Instant;

public class RequestLog {
    public static void main(String[] arguments) {
        String traceId = "trace-184";
        String serviceName = "course-service";
        int statusCode = 200;
        System.out.println("time=" + Instant.now()
                + " service=" + serviceName
                + " traceId=" + traceId
                + " status=" + statusCode);
    }
}

Signals and Their Uses

SignalAnswersExample
LogsWhat happened?Validation failure
MetricsHow often or how much?Request latency
TracesWhere did time go?Gateway to database
Health checksIs it serving?Readiness status

Common Mistake and Practices

Common Mistake: Logging a full request body or stack trace for every normal request. Logs become expensive, noisy, and may expose private data while hiding the events operators need.

  • Include a correlation or trace ID.
  • Use structured fields and stable names.
  • Track latency, error rate, and saturation.
  • Define actionable alerts with ownership.
  • Redact secrets and sensitive fields.

Real-World Use Case

A learner request receives one trace ID as it passes through the gateway, course service, and database client. A dashboard shows latency and error rates, while linked logs reveal the failing dependency without searching unrelated text.

Quiz Check

Quick Knowledge Test

Loading quiz questions...