Video summary

Golang Microservices Full Course #04 - Structured Logging & Centralized Error Handling

Main summary

Key takeaways

Technology

Overview

This episode of the Golang microservices course focuses on structured logging and centralized error handling in a Go + Gin + Clean Architecture setup, using context propagation across layers.

Key technological concepts & features

1) Clean Architecture with strict contract boundaries + context propagation

  • Continues from the prior episode (CRUD with Clean Architecture).
  • Demonstrates how context is passed through all layers:
    • handler -> service -> repository
  • Rationale:
    • If the client cancels or times out, the request context propagates so DB queries can be automatically canceled, saving server resources.
  • Architectural reasoning:
    • Service/repository are treated as contracts (interfaces), enabling implementation swaps (e.g., MySQL → Postgres) without changing higher layers.

2) Centralized, standardized application errors

  • Replaces default Go logging/error handling patterns (e.g., log.Println, log.Fatal) with a custom error model.
  • Introduces an internal package:
    • internal/errors/errors.go
  • Defines an app_error (conceptually) with fields such as:
    • HTTP status code
    • JSON-safe error code (does not expose internal details)
    • message (safe to show to the client)
  • Provides helper constructors like:
    • newAppError(status, code, message)
  • Establishes common error presets:
    • Internal server error (500)
    • Bad request (400) – invalid payload
    • Unauthorized (401) – credential issues
    • Not found (404) – missing resource
    • Later adds: Conflict (409) (e.g., email already registered)

3) Structured logging with correlation IDs

  • Adds structured logging using Go’s slog:
    • internal/logger/logger.go
  • Configures slog to output JSON logs to stdout:
    • slog.NewJSONHandler(os.Stdout, ...)
    • default log level set to INFO
    • uses slog.SetDefault(...)
  • Adds helper logging that automatically includes:
    • correlation_id from context

4) Gin middleware: correlation ID + centralized error response

a) Correlation ID middleware

  • Middleware: internal/middleware/correlation.go
  • Reads request header: X-Correlation-ID
  • If missing, generates a new UUID.
  • Stores correlation ID in the request context so subsequent logs include it.
  • Also sets response header: X-Correlation-ID.

b) Central error handler middleware

  • Middleware: internal/middleware/error_handler.go
  • After c.Next(), checks Gin collected errors:
    • If there are custom app errors:
      • returns a standard JSON error response:
        • success: false
        • error: { code, message } (client-safe)
        • status code derived from the app error
    • If it’s an unknown/unhandled error:
      • logs it server-side
      • responds with generic 500 internal server error JSON (no sensitive details)

Product/code integration steps described

  • Update service methods to return custom app errors:
    • Examples mentioned:
      • Register returns 409 Conflict when email is already registered
      • Get profile returns 404 user not found
      • Update profile returns 500 Internal Server Error on failure scenarios
  • Update handlers to register errors with Gin:
    • c.Error(err) and let middleware format/respond
  • Update main.go to initialize:
    • structured logger (logger.InitLogger)
    • replace previous logging calls so the application consistently uses slog

Security & operational reasoning

  • Explicitly avoids exposing raw DB errors to clients (e.g., SQL errors like “no rows”, “connection refused”).
  • Logs the underlying error internally, but returns sanitized messages externally to reduce information leakage and mitigate security risks (e.g., aiding SQL injection attempts).

Outcome of the episode

  • Demonstrates running the app and connecting to DB with retry/backoff (from the earlier episode context).
  • Mentions correcting/debugging structured logging output and verifying successful DB connection.
  • Ends by committing/merging changes to a publish branch and marking the episode complete.

Main speakers / sources

  • Main speaker: the tutorial author/instructor (name not provided in subtitles)
  • Primary codebase/framework sources referenced:
    • Go standard libraries: context, and replacing log with slog
    • Gin middleware
    • course’s Clean Architecture layers: handler, service, repository

Rate this summary

Your feedback will help improve summaries.

Improve this summary

Reprocess with a stronger model when the summary feels incomplete or inaccurate.

Pro

Translate summary in another language

Pro

Ask questions to this video

Chat for follow-up questions, clarifications, and source-backed answers.

Coming soon

Share this summary

Original video