Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Nâng Cao Giám Sát Rails: Tích Hợp AppSignal Nâng Cao

Phần 1 đã cover setup AppSignal cho Rails - tự động track errors, monitor performance, report metrics dependencies.

Nhưng mỗi app khác nhau, cần hơn giám sát chung chung. Bài này cover custom instrumentation và monitoring cho insights sâu hơn.

Yêu cầu theo dõi code:

  • Tài khoản www.appsignal.com
  • Docker cài đặt & chạy (cho docker-compose)

Custom Instrumentation Và Monitoring

Khi cần hơn out-of-the-box, AppSignal gem cho phép thêm custom instrumentation.

Instrumenting Phần Code

Ví dụ: thêm feature filter posts theo chữ cái đầu title. Method Post.where_title_starts_with đã có sẵn. Update PostsController#index:

# app/controllers/posts_controller.rb
def index
  starts_with = params[:starts_with]
  @posts = if starts_with.present?
    Post.where_title_starts_with(starts_with)
  else
    Post.all
  end
end

Đây là core feature, cần biết performance. AppSignal cung cấp vài cách.

1. Instrument block code - wrap code block:

# app/models/post.rb
def self.where_title_starts_with(letter)
  Appsignal.instrument('Post.where_title_starts_with', "Fetch posts that start with letter") do
    Analytics.track_post_title_search(letter.downcase)
    select('*, pg_sleep(0.01)').where("title ILIKE :letter", letter: "#{letter.downcase}%").load
  end
end

2. Instrument method toàn bộ - cho Analytics.track_post_title_search (xử lý nặng):

# app/services/analytics.rb
require 'appsignal/integrations/object'
class Analytics
  def self.track_post_title_search(letter, sleep = sleep(1))
    # Some heavy processing
    sleep 1
  end
  appsignal_instrument_class_method :track_post_title_search
end

Insights

Vài phút sau, check AppSignal dashboard. Verify feature: https://localhost:3000/posts?starts_with=f.

Performance → Issue list → PostsController#index → Event Timeline: breakdown thời gian chạy code cụ thể.

Timeline có cho tất cả performance events, nhưng đây thấy custom instrumentation: Post.where_title_starts_with mất 8.84s, trong đó Analytics.track_post_title_search 2.01s, phần còn lại là ActiveRecord query. Click vào từng event để xem chi tiết (vd: sql.active_record).

Instrumentation helpers cho breakdown chi tiết, dễ dàng insight vào code ảnh hưởng performance.

Exception Handling

Ngoài performance, cần biết khi app hoạt động không như mong đợi. AppSignal report unhandled exceptions, nhưng có thêm.

Xóa code gây lỗi intermittent. Backtrace chỉ lỗi tại app/controllers/pages_controller.rb:7 home. Xóa if statement:

class PagesController < ApplicationController
  def home
    CreateRandomPostsJob.perform_later
  end
end

Error rate giảm đáng kể.

Hiện tại user xem post không tồn tại → app crash (vd: /posts/doesnotexist). Thay bằng thông báo. Update #set_post:

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  # ...
  private
  def set_post
    @post = Post.find(params[:id])
  rescue ActiveRecord::RecordNotFound => e
    render json: { error: "Oops. That post isn't here" }, status: :not_found
  end
  # ...
end

Vì handle exception thủ công, không tự report AppSignal. Dùng Appsignal.set_error để track manual:

def set_post
  Appsignal.tag_request(user_id: 'user-from-params', post_id: params[:id])
  @post = Post.find(params[:id])
  rescue ActiveRecord::RecordNotFound => e
    Appsignal.set_error(e)
    render json: { error: "Oops. That post isn't here" }, status: :not_found
end

Test: https://localhost:3000/posts/doesnotexist → JSON response thay vì crash.

Insights

Errors → Issue list → ActiveRecord::RecordNotFound. Error detail page: context request (HTTP method, params, session) + custom tags. Tags giúp filter errors.

Tags cũng xuất hiện trong performance measurement (PostsController#show). Thêm metadata vào transaction giúp diagnose production issues (vd: Kubernetes metadata).

Metrics

Có custom instrumentation và error tracking. Nhận ra: spikes trong posts searches. Analytics#track_post_title_search gọi API third-party có rate limit. Cần track tần suất gọi.

AppSignal cho phép track custom metrics.

1. Counter với tags - track tần suất gọi analytics service:

# app/services/analytics.rb
require 'appsignal/integrations/object'
class Analytics
  def self.track_post_title_search(letter, sleep = sleep(1))
    Appsignal.increment_counter("track_post_search", 1, { letter: letter })
    # Some heavy processing
    sleep 1
  end
  appsignal_instrument_class_method :track_post_title_search
end

2. Gauge - track số posts trả về trong PostsController#index:

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  # ...
  def index
    # ...
    Appsignal.set_gauge("posts_index", @posts.size, starts_with: params[:starts_with])
  end
end

Fake traffic script chạy, thêm search f, l, v để đa dạng data.

Insights

Tạo custom dashboard trên AppSignal (UI hoặc import JSON). Import dashboard mẫu:

{
  "title": "Post Search",
  "description": "Sample dashboard about posts search activity",
  "visuals": [
    {
      "title": "Analytics",
      "line_label": "%name% %letter%",
      "display": "LINE",
      "format": "number",
      "draw_null_as_zero": true,
      "metrics": [{
        "name": "track_post_search",
        "fields": [{ "field": "COUNTER" }],
        "tags": [{ "key": "letter", "value": "*" }]
      }],
      "type": "timeseries"
    },
    {
      "title": "Search",
      "line_label": "%name% %starts_with%",
      "display": "LINE",
      "format": "number",
      "draw_null_as_zero": true,
      "metrics": [{
        "name": "posts_index",
        "fields": [{ "field": "GAUGE" }],
        "tags": [{ "key": "starts_with", "value": "*" }]
      }],
      "type": "timeseries"
    }
  ]
}

Vài phút sau thấy data trên graphs. Hover → legend metrics trong timeframe. Lines riêng cho mỗi tag value. Fake traffic chỉ search 'e', nhưng manual search f, l, v tạo lines mới.

AppSignal còn breadcrumbs - track danh sách actions, report trong error → info cụ thể, ordered về nguyên nhân error.

Đọc thêm custom instrumentation trong guides.

Tóm Tắt: Custom Instrumentation Và Monitoring Cho Ruby Apps Với AppSignal

Phần 1: setup cơ bản AppSignal cho Ruby apps.

Phần 2: app đã có monitoring tốt → làm tốt hơn với AppSignal gem.

Custom instrumentation, error tracking, performance monitoring cho insights cần thiết. AppSignal cho nhiều out-of-the-box, cho bạn kiểm soát khi cần.

Để code chạy tự do, miễn là bạn theo dõi nó. Happy coding!

P.S. Đăng ký Ruby Magic newsletter để đọc sớm nhất!