System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) · บทเรียน

แนวทางปฏิบัติที่ดีในการติดตั้งเครื่องมือด้วยตนเอง

ทำความเข้าใจว่าเมื่อใดและอย่างไรจึงควรติดตั้งเครื่องมือด้วยตนเองเพื่อควบคุมข้อมูลการสังเกตระบบอย่างละเอียด เรียนรู้การเพิ่มแอตทริบิวต์แบบกำหนดเองให้แทรซ

บทเรียน 2 จาก 411 ขั้นตอน

แนวทางปฏิบัติที่ดีในการติดตั้งเครื่องมือด้วยตนเอง เป็นบทเรียน System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Manual Instrumentation Intro

Welcome! In this lesson, we'll dive into manual instrumentation with OpenTelemetry. While auto-instrumentation is great for quick wins, manual control gives you precision.

Manual instrumentation allows you to record highly specific details about your application's internal operations. This is crucial for debugging complex business logic or custom components.

Why Manual Over Auto?

Auto-instrumentation automatically collects data from common libraries and frameworks. However, it can't know your unique application logic.

  • Custom Logic: Instrument specific functions or blocks of code.
  • Business Context: Add attributes relevant to your business domain.
  • Fine-Grained Control: Define exact span boundaries and relationships.
  • Missing Coverage: Cover areas where auto-instrumentation doesn't reach.

Creating Your First Span

A span represents a single operation within a trace. To create one manually, you need a Tracer, which is obtained from the OpenTelemetry SDK.

Here's how to start a new span. Remember to always end your spans!

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;

public class ManualSpanDemo {
  public static void main(String[] args) {
    // Setup OpenTelemetry SDK (simplified for demo)
    SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().build();
    OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
        .setTracerProvider(sdkTracerProvider)
        .buildAndRegisterGlobal();

    Tracer tracer = openTelemetry.getTracer("my-app", "1.0.0");

    // Start a new span
    Span span = tracer.spanBuilder("MyCustomOperation").startSpan();

    try {
      System.out.println("Executing custom operation...");
      // Simulate work
      Thread.sleep(100);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      // Always end the span!
      span.end();
      System.out.println("Span ended.");
    }
  }
}

Activating Spans with Scope

For a span to be part of the current trace context (and for child spans to automatically link to it), it needs to be active. The best way to manage this is using a Scope with a try-with-resources statement.

This ensures the span is automatically set as active and ended when the block exits.

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.Scope;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;

public class ActiveSpanDemo {
  public static void main(String[] args) {
    SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().build();
    OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
        .setTracerProvider(sdkTracerProvider)
        .buildAndRegisterGlobal();

    Tracer tracer = openTelemetry.getTracer("my-app", "1.0.0");

    Span parentSpan = tracer.spanBuilder("ParentOperation").startSpan();
    try (Scope parentScope = parentSpan.makeCurrent()) { // Parent span is active
      System.out.println("Parent operation started.");

      Span childSpan = tracer.spanBuilder("ChildOperation").startSpan(); // Automatically links to parent
      try (Scope childScope = childSpan.makeCurrent()) {
        System.out.println("Child operation executing...");
        Thread.sleep(50);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      } finally {
        childSpan.end();
        System.out.println("Child operation ended.");
      }

      Thread.sleep(50);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      parentSpan.end();
      System.out.println("Parent operation ended.");
    }
  }
}

Adding Custom Attributes

Attributes are key-value pairs that provide contextual information about a span. They are vital for making your traces searchable and understandable.

You can add attributes to a span using span.setAttribute(). Use descriptive keys and relevant values.

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.Scope;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;

public class SpanAttributesDemo {
  public static void main(String[] args) {
    SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().build();
    OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
        .setTracerProvider(sdkTracerProvider)
        .buildAndRegisterGlobal();

    Tracer tracer = openTelemetry.getTracer("my-app", "1.0.0");

    Span span = tracer.spanBuilder("ProcessOrder").startSpan();
    try (Scope scope = span.makeCurrent()) {
      System.out.println("Processing order...");
      // Add attributes for order details
      span.setAttribute("order.id", "XYZ789");
      span.setAttribute("customer.email", "user@example.com");
      span.setAttribute(AttributeKey.longKey("item.count"), 3L);

      Thread.sleep(150);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      span.end();
      System.out.println("Order processed. Span ended with attributes.");
    }
  }
}

Recording Span Events

Events are timestamped messages associated with a span. They are useful for marking significant moments or logging specific actions that occur during the span's lifetime, without creating new child spans.

Think of them as mini-logs within your trace, adding more detail to a specific operation.

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.Scope;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;

public class SpanEventsDemo {
  public static void main(String[] args) {
    SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().build();
    OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
        .setTracerProvider(sdkTracerProvider)
        .buildAndRegisterGlobal();

    Tracer tracer = openTelemetry.getTracer("my-app", "1.0.0");

    Span span = tracer.spanBuilder("UserLogin").startSpan();
    try (Scope scope = span.makeCurrent()) {
      System.out.println("User login initiated...");
      span.addEvent("AuthenticationStarted");

      Thread.sleep(80);
      // Add an event with attributes
      span.addEvent("DatabaseCheck", Attributes.of(
          AttributeKey.stringKey("db.query"), "SELECT * FROM users WHERE id=?"
      ));

      Thread.sleep(70);
      span.addEvent("AuthenticationSuccessful");

    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      span.end();
      System.out.println("User login span ended with events.");
    }
  }
}

Handling Errors in Spans

It's crucial to mark spans as failed when an error occurs. This helps quickly identify problematic operations in your system.

You can set a span's status to ERROR and record the exception that caused the failure. This provides rich context for debugging.

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Scope;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;

public class SpanErrorDemo {
  public static void main(String[] args) {
    SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().build();
    OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
        .setTracerProvider(sdkTracerProvider)
        .buildAndRegisterGlobal();

    Tracer tracer = openTelemetry.getTracer("my-app", "1.0.0");

    Span span = tracer.spanBuilder("CriticalFunction").startSpan();
    try (Scope scope = span.makeCurrent()) {
      System.out.println("Executing critical function...");
      // Simulate an error condition
      if (Math.random() > 0.5) {
        throw new RuntimeException("Simulated critical failure!");
      }
      System.out.println("Critical function completed successfully.");

    } catch (Exception e) {
      System.out.println("Error caught: " + e.getMessage());
      span.setStatus(StatusCode.ERROR, "Function failed");
      span.recordException(e);
    } finally {
      span.end();
      System.out.println("Critical function span ended.");
    }
  }
}

Best Practices for Spans

To get the most out of manual instrumentation, follow these guidelines:

  • Granularity: Create spans for meaningful units of work, not every single line of code.
  • Meaningful Names: Use clear, low-cardinality names (e.g., user.login, db.query).
  • Rich Attributes: Add relevant business and technical context as attributes.
  • Always End Spans: Use try-with-resources or explicit span.end() in a finally block.
  • Avoid Over-instrumentation: Too many spans can add overhead. Focus on critical paths.

Linking Spans Explicitly

While makeCurrent() handles most parent-child linking, sometimes you need to explicitly link spans. This is common in asynchronous scenarios or when integrating with non-instrumented systems.

You can use SpanBuilder.setParent() or setNoParent() to control the parent-child relationship.

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.TraceFlags;
import io.opentelemetry.api.trace.TraceState;
import io.opentelemetry.context.Context;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;

public class ExplicitLinkDemo {
  public static void main(String[] args) {
    SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().build();
    OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
        .setTracerProvider(sdkTracerProvider)
        .buildAndRegisterGlobal();

    Tracer tracer = openTelemetry.getTracer("my-app", "1.0.0");

    // Imagine a span from an external system, represented by its context
    SpanContext externalContext = SpanContext.create(
        "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", // Trace ID
        "0000000000000001", // Span ID
        TraceFlags.getDefault(), TraceState.getDefault()
    );

    // Create a new span that links to this external context
    Span linkedSpan = tracer.spanBuilder("ProcessingExternalMessage")
        .setParent(Context.current().with(Span.wrap(externalContext))) // Link to external context
        .setSpanKind(SpanKind.CONSUMER) // Indicate it's a message consumer
        .startSpan();

    try {
      System.out.println("Processing message from external system...");
      linkedSpan.setAttribute("message.id", "MSG-123");
      Thread.sleep(100);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      linkedSpan.end();
      System.out.println("Linked span ended.");
    }
  }
}

Manual Instrumentation Check

You're implementing a new feature that calculates a user's loyalty points. You want to instrument this specific calculation to track its duration and the final points awarded. Which of the following is the most appropriate way to record the final points using manual OpenTelemetry instrumentation?

Recap: Manual Control

In this lesson, we explored manual instrumentation with OpenTelemetry. You learned:

  • When to choose manual over auto-instrumentation for fine-grained control.
  • How to create, activate, and end spans.
  • The power of attributes for adding rich context to your traces.
  • How to use events to mark specific moments within a span.
  • Best practices for handling errors and linking spans explicitly.

Mastering manual instrumentation gives you unparalleled visibility into your application's unique logic and performance.

เริ่มต้นได้ฟรี

เรียนรู้ System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

คำถามที่พบบ่อย

บทเรียน “แนวทางปฏิบัติที่ดีในการติดตั้งเครื่องมือด้วยตนเอง” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “แนวทางปฏิบัติที่ดีในการติดตั้งเครื่องมือด้วยตนเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “แนวทางปฏิบัติที่ดีในการติดตั้งเครื่องมือด้วยตนเอง”

ทำความเข้าใจว่าเมื่อใดและอย่างไรจึงควรติดตั้งเครื่องมือด้วยตนเองเพื่อควบคุมข้อมูลการสังเกตระบบอย่างละเอียด เรียนรู้การเพิ่มแอตทริบิวต์แบบกำหนดเองให้แทรซ คุณปฏิบัติ System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “แนวทางปฏิบัติที่ดีในการติดตั้งเครื่องมือด้วยตนเอง” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) นี้ได้ไหม

ได้ บทเรียน System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เทคนิคการติดตั้งเครื่องมืออัตโนมัติ
  2. แนวทางปฏิบัติที่ดีในการติดตั้งเครื่องมือด้วยตนเอง
  3. การส่งต่อบริบทและสัมภาระข้อมูล
  4. แอตทริบิวต์ เหตุการณ์ และสถานะของช่วง
← กลับไปที่ System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry)