0Pricing
Elixir & Phoenix: Scalable Backend Development · บทเรียน

การตรวจติดตามด้วย Telemetry และเมตริก

ผสาน Telemetry เข้ากับแอปพลิเคชันเพื่อส่งเมตริกและรับข้อมูลเชิงลึกเกี่ยวกับพฤติกรรมขณะทำงาน

การตรวจติดตามด้วย Telemetry และเมตริก เป็นบทเรียน Elixir & Phoenix: Scalable Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Elixir & Phoenix: Scalable Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน

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

What is Elixir Telemetry?

In Elixir, Telemetry is a powerful, low-level event dispatching library. It helps you understand what's happening inside your running application.

  • It's built into Elixir/OTP, making it a standard way to observe systems.
  • Think of it as a central nervous system for your app's events.
  • It enables you to collect metrics, trace operations, and monitor performance.

It's crucial for building observable and maintainable applications.

Events: The Core of Telemetry

Telemetry works by emitting events. An event is a signal that something notable has happened in your application.

  • Each event has a unique name (a list of atoms, e.g., [:my_app, :user, :login]).
  • Events can carry measurements (numeric values like duration) and metadata (additional context like user ID).
  • You don't emit events directly; instead, you use functions that wrap your code.

Measuring Duration with Telemetry.span

One common use of Telemetry is to measure how long an operation takes. This is done using :telemetry.span/3.

  • It executes a given function and measures its execution time.
  • It emits two events: one when the span starts and one when it ends.
  • The end event includes the duration as a measurement.

This is great for profiling function calls or database queries.

Emitting Discrete Events with Telemetry.execute

Sometimes, you just want to signal that an action occurred, without necessarily measuring its duration. For this, use :telemetry.execute/3.

  • It emits a single event with specified measurements and metadata.
  • Useful for tracking things like cache hits/misses, background job completions, or specific API calls.
  • It's a simpler, more direct way to emit a single point-in-time event.

Code: Emitting a Telemetry Span

Let's see :telemetry.span/3 in action. This example simulates a 'processing' task and measures its duration.

We define a simple module and call a function that wraps its work in a span.

defmodule MyApp.Worker do
  require Logger

  def process_data(data) do
    Logger.info("Starting data processing...")
    :telemetry.span(
      [:my_app, :worker, :process_data],
      %{input_length: byte_size(data)},
      fn ->
        # Simulate some work
        :timer.sleep(100)
        result = String.upcase(data)
        {:ok, result}
      end
    )
  end
end

# --- Main execution for CoddyKit ---
Logger.info("Calling MyApp.Worker.process_data...")
{:ok, result} = MyApp.Worker.process_data("hello elixir")
IO.puts("Processed result: #{result}")
IO.puts("\n(No Telemetry output yet - we need a handler!)")

Attaching Telemetry Handlers

Emitting events is only half the story! To do something useful with them, you need to attach handlers.

  • A handler is a function that gets called whenever a specific Telemetry event is emitted.
  • You attach a handler using :telemetry.attach/4, specifying the event name and your handler function.
  • Handlers allow you to react to events: log them, send them to a metrics system, or trigger other actions.

They are the listeners of your application's internal signals.

Handler Function Structure

A Telemetry handler function must accept four arguments:

  1. event_name: The name of the event (e.g., [:my_app, :user, :login]).
  2. measurements: A map of numeric values associated with the event (e.g., %{duration: 123456}).
  3. metadata: A map of additional context (e.g., %{user_id: 123}).
  4. config: Any custom configuration passed during attachment.

Your handler logic will use these arguments to process the event.

Code: Attaching and Handling Events

Now let's add a handler to our previous example. This handler will simply log the event details.

Notice how :telemetry.attach/4 links our handler function to the specific event name.

defmodule MyApp.WorkerWithHandler do
  require Logger

  # Define our simple handler function
  def handle_event(event_name, measurements, metadata, _config) do
    Logger.info("\n--- Telemetry Event Received ---")
    Logger.info("Event: #{inspect(event_name)}")
    Logger.info("Measurements: #{inspect(measurements)}")
    Logger.info("Metadata: #{inspect(metadata)}")
    Logger.info("------------------------------")
  end

  # Function that emits a Telemetry event
  def process_data(data) do
    Logger.info("Starting data processing...")
    :telemetry.span(
      [:my_app, :worker, :process_data],
      %{input_length: byte_size(data)},
      fn ->
        :timer.sleep(100)
        result = String.upcase(data)
        {:ok, result}
      end
    )
  end
end

# --- Main execution for CoddyKit ---
# Attach the handler *before* emitting events
:telemetry.attach(
  "my-worker-handler",
  [:my_app, :worker, :process_data], # Event name to listen for
  &MyApp.WorkerWithHandler.handle_event/4, # Our handler function
  nil # Optional config
)
Logger.info("Telemetry handler 'my-worker-handler' attached.")

# Perform some work, which will now trigger the handler
{:ok, result} = MyApp.WorkerWithHandler.process_data("hello world")
IO.puts("Processed result: #{result}")

# Clean up: detach the handler (good practice in tests/scripts)
:telemetry.detach("my-worker-handler")
Logger.info("Telemetry handler 'my-worker-handler' detached.")

Telemetry as a Metrics Source

Telemetry is not a metrics system itself, but it's an excellent source for them. By attaching handlers, you can feed events into dedicated metrics libraries.

  • Libraries like telemetry_metrics can aggregate Telemetry events into counters, gauges, and histograms.
  • These aggregated metrics are then often exported to monitoring systems like Prometheus or Datadog.
  • This separation keeps Telemetry lightweight and flexible, allowing you to choose your preferred metrics backend.

Quick Check: Telemetry Handlers

You've learned about emitting and handling Telemetry events. Let's test your understanding.

Recap: Telemetry for Observability

In this lesson, we explored Elixir's Telemetry library:

  • Telemetry is an event dispatching system for internal application observability.
  • It uses events with unique names, measurements, and metadata.
  • :telemetry.span/3 measures code execution duration.
  • :telemetry.execute/3 emits discrete, point-in-time events.
  • Handlers are functions attached via :telemetry.attach/4 to process events.
  • Telemetry events are a prime source for building application metrics.

Mastering Telemetry is key to understanding and monitoring your Elixir applications effectively!

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

บทเรียน “การตรวจติดตามด้วย Telemetry และเมตริก” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การตรวจติดตามด้วย Telemetry และเมตริก” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Elixir & Phoenix: Scalable Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การตรวจติดตามด้วย Telemetry และเมตริก”

ผสาน Telemetry เข้ากับแอปพลิเคชันเพื่อส่งเมตริกและรับข้อมูลเชิงลึกเกี่ยวกับพฤติกรรมขณะทำงาน คุณปฏิบัติ Elixir & Phoenix: Scalable Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Elixir & Phoenix: Scalable Backend Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Elixir & Phoenix: Scalable Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การตรวจติดตามด้วย Telemetry และเมตริก” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Elixir & Phoenix: Scalable Backend Development นี้ได้ไหม

ได้ บทเรียน Elixir & Phoenix: Scalable Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. การวัดประสิทธิภาพและการทำโพรไฟล์ Elixir
  2. การตรวจติดตามด้วย Telemetry และเมตริก
  3. การจัดการข้อผิดพลาดและการบันทึกล็อกแบบมีโครงสร้าง
  4. การติดตามแบบกระจายด้วย OpenTelemetry
← กลับไปที่ Elixir & Phoenix: Scalable Backend Development