為特定網路要求新增自訂監控功能 (Apple &、Android 應用程式)

Performance Monitoring 會收集「追蹤記錄」,協助您監控應用程式的效能。追蹤記錄是應用程式在兩個時間點之間擷取的效能資料報表。

Performance Monitoring 自動收集的網路要求追蹤記錄包含應用程式的大部分網路要求。不過,部分要求可能不會列入報表,或者您也可以使用不同的程式庫來發出網路要求。在這些情況下,您可以使用 Performance Monitoring API 手動檢測自訂網路要求追蹤記錄。自訂網路要求追蹤記錄僅適用於 Apple 和 Android 應用程式。

自訂網路要求追蹤記錄的預設指標與 Performance Monitoring 自動收集的網路要求追蹤記錄指標相同,具體包括回應時間、回應和要求酬載大小,以及成功率。自訂網路要求追蹤記錄不支援新增自訂指標。

在程式碼中,使用 Performance Monitoring SDK 提供的 API 定義自訂網路要求追蹤記錄的開頭和結尾。

自訂網路要求追蹤記錄會顯示在 Firebase 控制台中,以及 Performance Monitoring 自動擷取的網路要求 (位於追蹤記錄表的「Network requests」(網路要求) 子分頁中)。

新增自訂網路要求追蹤記錄

使用 Performance Monitoring HTTPMetric API (Swift | Obj-C) 新增自訂網路要求追蹤記錄,以監控特定網路要求。

如要在 Performance Monitoring 中手動檢測自訂網路要求,請新增類似下方的程式碼:

Swift

注意:這項 Firebase 產品不適用於 macOS、Mac Catalyst 和 watchOS 目標。
guard let metric = HTTPMetric(url: "https://www.google.com", httpMethod: .get) else { return }

metric.start()
guard let url = URL(string: "https://www.google.com") else { return }
let request: URLRequest = URLRequest(url:url)
let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: request) { (urlData, response, error) in
        if let httpResponse = response as? HTTPURLResponse {
         metric.responseCode = httpResponse.statusCode
        }
        metric.stop()
}
dataTask.resume()

Objective-C

注意:這項 Firebase 產品不適用於 macOS、Mac Catalyst 和 watchOS 目標。
@property (nonatomic) FIRHTTPMetric *metric;

- (void)beginManualNetworkInstrumentation {
  self.metric =
      [[FIRHttpMetric alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com"]
                              HTTPMethod:FIRHTTPMethodGET];

  [self.metric start];

  NSURLRequest *request =
      [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com"]];
  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                                delegate:self];
  [connection resume];
}

- (void)connection:(NSURLConnection *)connection
    didReceiveResponse:(NSURLResponse *) response {
  NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response
  self.metric.responseCode = httpResponse.statusCode;
  [self.metric stop];
}

自訂網路要求追蹤記錄也支援新增自訂屬性 (Swift | Obj-C) 但不支援自訂指標。

後續步驟

  • 設定快訊,用於降低應用程式效能的網路要求。舉例來說,如果特定網址模式的回應時間超過您設定的門檻,您就可以為團隊設定電子郵件快訊。