Điều kiện kích hoạt Cảnh báo Firebase

Firebase cung cấp tính năng cảnh báo cho nhiều sự kiện quản lý dự án và ứng dụng. Dưới đây là một vài sự kiện mẫu khi Firebase có thể gửi cho bạn loại cảnh báo này:

  • Đối với Crashlytics, chúng tôi có thể thông báo cho bạn nếu số lượng sự cố trên ứng dụng của bạn tăng đáng kể.
  • Đối với tính năng Giám sát hiệu suất, chúng tôi có thể thông báo cho bạn nếu thời gian khởi động của ứng dụng vượt quá ngưỡng đã định cấu hình.
  • Đối với tính năng Phân phối ứng dụng, chúng tôi có thể thông báo cho bạn nếu một trong những người kiểm thử của bạn đăng ký thiết bị iOS mới.

Tuỳ thuộc vào cảnh báo và các lựa chọn ưu tiên do thành viên dự án đặt, Firebase sẽ hiển thị các loại cảnh báo này trong bảng điều khiển của Firebase hoặc gửi chúng qua email.

Trang này mô tả cách viết các hàm trong Cloud Functions cho Firebase (thế hệ thứ 2) để xử lý các sự kiện cảnh báo.

Tính năng này hoạt động như thế nào?

Bạn có thể kích hoạt các hàm để phản hồi các sự kiện cảnh báo do những nguồn sau đưa ra:

Trong vòng đời thông thường, hàm được kích hoạt bởi sự kiện cảnh báo sẽ thực hiện những việc sau:

  1. Nghe/chờ một loại cảnh báo cụ thể được phát từ Firebase.
  2. Kích hoạt khi cảnh báo được phát ra và nhận được tải trọng sự kiện chứa thông tin cụ thể về sự kiện đó.
  3. Gọi mã hàm của bạn để xử lý tải trọng sự kiện.

Kích hoạt một hàm trên các sự kiện cảnh báo

Sử dụng gói con firebase-functions/v2/alerts để viết một hàm xử lý các sự kiện cảnh báo. Các ví dụ dành riêng cho sản phẩm sau đây minh hoạ quy trình công việc, trong đó hàm sử dụng webhook để đăng tin nhắn lên kênh Discord khi cảnh báo về sản phẩm được kích hoạt từ Firebase.

Xử lý một sự kiện cảnh báo trong Crashlytics

Trong ví dụ sau về Crashlytics, bạn sử dụng Cloud Functions cho Firebase để xử lý một sự kiện cảnh báo về một vấn đề nghiêm trọng mới xảy ra. Hàm này đăng thông tin cảnh báo trong tin nhắn lên kênh Discord.

Ví dụ về thông báo sự cố trong Discord

Thông báo mẫu về vấn đề sự cố nghiêm trọng mới

Hàm này theo dõi sự kiện tương ứng với việc Firebase phát hành một vấn đề nghiêm trọng mới:

Node.js

exports.postfatalissuetodiscord = onNewFatalIssuePublished(async (event) => {

Python

@crashlytics_fn.on_new_fatal_issue_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_fatal_issue_to_discord(event: crashlytics_fn.CrashlyticsNewFatalIssueEvent) -> None:
    """Publishes a message to Discord whenever a new Crashlytics fatal issue occurs."""

Sau đó, hàm này sẽ phân tích cú pháp đối tượng sự kiện được trả về, phân tích cú pháp thông tin hữu ích từ tải trọng sự kiện và tạo một tin nhắn để đăng lên kênh Discord:

Node.js

  // construct a helpful message to send to Discord
  const appId = event.appId;
  const {id, title, subtitle, appVersion} = event.data.payload.issue;
  const message = `
🚨 New fatal issue for ${appId} in version ${appVersion} 🚨

**${title}**

${subtitle}

id: \`${id}\`
`;

Python

    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    issue = event.data.payload.issue
    message = f"""
🚨 New fatal issue for {app_id} in version {issue.app_version} 🚨

# {issue.title}

{issue.subtitle}

ID: `{issue.id}`
""".strip()

Cuối cùng, hàm này gửi tin nhắn đã tạo đến Discord thông qua yêu cầu HTTP:

Node.js

const response = await postMessageToDiscord("Crashlytics Bot", message);
if (response.ok) {
  logger.info(
      `Posted fatal Crashlytics alert ${id} for ${appId} to Discord`,
      event.data.payload,
  );
} else {
  throw new Error(response.error);
}

Python

response = post_message_to_discord("Crashlytics Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted fatal Crashlytics alert {issue.id} for {app_id} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

Để tìm hiểu về tất cả các sự kiện cảnh báo của Crashlytics mà bạn có thể ghi nhận, hãy chuyển đến tài liệu tham khảo về cảnh báo Crashlytics.

Xử lý sự kiện cảnh báo của giải pháp Giám sát hiệu suất

Ví dụ sau sẽ xuất một hàm theo dõi các sự kiện cảnh báo về ngưỡng hiệu suất:

Node.js

exports.postperformancealerttodiscord = onThresholdAlertPublished(
    async (event) => {

Python

@performance_fn.on_threshold_alert_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_performance_alert_to_discord(event: performance_fn.PerformanceThresholdAlertEvent) -> None:
    """Publishes a message to Discord whenever a performance threshold alert is fired."""

Sau đó, hàm này sẽ phân tích cú pháp đối tượng sự kiện được trả về, phân tích cú pháp thông tin hữu ích từ tải trọng sự kiện và tạo một tin nhắn để đăng lên kênh Discord:

Node.js

      // construct a helpful message to send to Discord
      const appId = event.appId;
      const {
        eventName,
        metricType,
        eventType,
        numSamples,
        thresholdValue,
        thresholdUnit,
        conditionPercentile,
        appVersion,
        violationValue,
        violationUnit,
        investigateUri,
      } = event.data.payload;
      const message = `
    ⚠️ Performance Alert for ${metricType} of ${eventType}: **${eventName}** ⚠️
    
    App id: ${appId}
    Alert condition: ${thresholdValue} ${thresholdUnit}
    Percentile (if applicable): ${conditionPercentile}
    App version (if applicable): ${appVersion}
    
    Violation: ${violationValue} ${violationUnit}
    Number of samples checked: ${numSamples}
    
    **Investigate more:** ${investigateUri}
    `;

Python

    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    perf = event.data.payload
    message = f"""
⚠️ Performance Alert for {perf.metric_type} of {perf.event_type}: **{perf.event_name}** ⚠️

App ID: {app_id}
Alert condition: {perf.threshold_value} {perf.threshold_unit}
Percentile (if applicable): {perf.condition_percentile}
App version (if applicable): {perf.app_version}

Violation: {perf.violation_value} {perf.violation_unit}
Number of samples checked: {perf.num_samples}

**Investigate more:** {perf.investigate_uri}
""".strip()

Cuối cùng, hàm này gửi tin nhắn đã tạo đến Discord thông qua yêu cầu HTTP:

Node.js

const response = await postMessageToDiscord(
    "Firebase Performance Bot", message);
if (response.ok) {
  logger.info(
      `Posted Firebase Performance alert ${eventName} to Discord`,
      event.data.payload,
  );
} else {
  throw new Error(response.error);
}

Python

response = post_message_to_discord("App Performance Bot", message,
                                   DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted Firebase Performance alert {perf.event_name} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

Để tìm hiểu về tất cả các sự kiện cảnh báo về hiệu suất mà bạn có thể nắm bắt, hãy chuyển đến tài liệu tham khảo về cảnh báo Giám sát hiệu suất.

Xử lý sự kiện cảnh báo Phân phối ứng dụng

Ví dụ trong phần này cho bạn biết cách viết một hàm cho thông báo trên thiết bị iOS của người kiểm thử mới.

Trong ví dụ này, hàm này theo dõi các sự kiện được gửi mỗi khi người kiểm thử đăng ký một thiết bị iOS mới. Khi một thiết bị iOS mới được đăng ký, bạn cần cập nhật hồ sơ cấp phép bằng UDID của thiết bị đó, sau đó phân phối lại ứng dụng.

Node.js

exports.postnewduuidtodiscord = onNewTesterIosDevicePublished(async (event) => {

Python

@app_distribution_fn.on_new_tester_ios_device_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_new_udid_to_discord(event: app_distribution_fn.NewTesterDeviceEvent) -> None:
    """Publishes a message to Discord whenever someone registers a new iOS test device."""

Sau đó, hàm này sẽ phân tích cú pháp đối tượng được trả về, phân tích cú pháp thông tin hữu ích từ tải trọng sự kiện và tạo thông điệp để đăng lên kênh Discord:

Node.js

  // construct a helpful message to send to Discord
  const appId = event.appId;
  const {
    testerDeviceIdentifier,
    testerDeviceModelName,
    testerEmail,
    testerName,
  } = event.data.payload;
  const message = `
📱 New iOS device registered by ${testerName} <${testerEmail}> for ${appId}

UDID **${testerDeviceIdentifier}** for ${testerDeviceModelName}
`;

Python

    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    app_dist = event.data.payload
    message = f"""
📱 New iOS device registered by {app_dist.tester_name} <{app_dist.tester_email}> for {app_id}

UDID **{app_dist.tester_device_identifier}** for {app_dist.tester_device_model_name}
""".strip()

Cuối cùng, hàm này gửi tin nhắn đã tạo đến Discord thông qua yêu cầu HTTP:

Node.js

const response = await postMessageToDiscord("AppDistribution Bot", message);
if (response.ok) {
  logger.info(
      `Posted iOS device registration alert for ${testerEmail} to Discord`,
  );
} else {
  throw new Error(response.error);
}

Python

response = post_message_to_discord("App Distro Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted iOS device registration alert for {app_dist.tester_email} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

Để tìm hiểu về tất cả các sự kiện cảnh báo Phân phối ứng dụng mà bạn có thể ghi lại, hãy chuyển đến tài liệu tham khảo về cảnh báo Phân phối ứng dụng.

Để tìm hiểu cách sử dụng hàm được kích hoạt bởi cảnh báo Firebase phản hồi trong ứng dụng từ tính năng Phân phối ứng dụng, hãy xem phần Gửi phản hồi trong ứng dụng đến Jira.