Как отключить Firebase Performance Monitoring


Чтобы пользователи могли включать и отключать Firebase Performance Monitoring, вы можете настроить приложение так, чтобы включать и отключать Performance Monitoring. Эта функция также может быть полезна при разработке и тестировании приложений.

Вот несколько вариантов:

  • Вы можете отключить SDK Performance Monitoring при создании приложения и снова включить его во время выполнения.

  • Вы можете создать приложение с включенным SDK Performance Monitoring, но отключить его во время выполнения с помощью Firebase Remote Config.

  • Вы можете полностью отключить SDK Performance Monitoring без возможности включить его во время выполнения.

Отключите Performance Monitoring в процессе сборки приложения.

Отключение Performance Monitoring во время сборки приложения может быть полезно, например, чтобы избежать передачи данных об эффективности из предварительной версии приложения во время его разработки и тестирования.

Чтобы отключить или деактивировать Performance Monitoring, добавьте один из двух ключей в файл списка свойств (Info.plist) для приложения Apple:

  • Чтобы отключить Performance Monitoring, но разрешить приложению включать его во время выполнения, задайте для firebase_performance_collection_enabled значение false в файле Info.plist приложения.

  • Чтобы полностью отключить Performance Monitoring без возможности включить его во время выполнения, задайте для firebase_performance_collection_deactivated значение true в файле Info.plist приложения.

Отключение приложения во время выполнения с помощью Remote Config

Firebase Remote Config позволяет менять поведение и внешний вид приложения, поэтому это идеальный способ отключить Performance Monitoring в развернутых экземплярах приложения.

Чтобы отключить сбор данных Performance Monitoring при следующем запуске приложения Apple, используйте пример кода ниже. Дополнительную информацию об использовании Remote Config в приложении Apple можно найти в статье Как использовать Firebase Remote Config на платформах Apple.

  1. Убедитесь, что в Podfile используется Remote Config:

    pod 'Firebase/RemoteConfig'
    
  2. Добавьте в начало файла AppDelegate своего приложения следующий код:

    Swift

    Примечание. Этот продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.
    import FirebaseRemoteConfig
    

    Objective-C

    Примечание. Этот продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.
    @import FirebaseRemoteConfig;
    
  3. В файле AppDelegate добавьте следующий код в инструкции launchOptions в методе экземпляра application:didFinishLaunchingWithOptions::

    Swift

    Примечание. Этот продукт недоступен для macOS, Mac Catalyst и watchOS.
    remoteConfig = RemoteConfig.remoteConfig()
    // You can change the "false" below to "true" to permit more fetches when validating
    // your app, but you should change it back to "false" or remove this statement before
    // distributing your app in production.
    let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: false)
    remoteConfig.configSettings = remoteConfigSettings!
    // Load in-app defaults from a plist file that sets perf_disable to false until
    // you update values in the Firebase console.
    remoteConfig.setDefaultsFromPlistFileName("RemoteConfigDefaults")
    // Important! This needs to be applied before FirebaseApp.configure()
    if !remoteConfig["perf_disable"].boolValue {
        // The following line disables all automatic (out-of-the-box) monitoring
        Performance.sharedInstance().isInstrumentationEnabled = false
        // The following line disables all custom monitoring
        Performance.sharedInstance().isDataCollectionEnabled = false
    }
    else {
        Performance.sharedInstance().isInstrumentationEnabled = true
        Performance.sharedInstance().isDataCollectionEnabled = true
    }
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    

    Objective-C

    Примечание. Этот продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.
    self.remoteConfig = [FIRRemoteConfig remoteConfig];
    // You can change the NO below to YES to permit more fetches when validating
    // your app, but you should change it back to NO or remove this statement before
    // distributing your app in production.
    FIRRemoteConfigSettings *remoteConfigSettings =
        [[FIRRemoteConfigSettings alloc] initWithDeveloperModeEnabled:NO];
    self.remoteConfig.configSettings = remoteConfigSettings;
    // Load in-app defaults from a plist file that sets perf_disable to false until
    // you update values in the Firebase console.
    [self.remoteConfig setDefaultsFromPlistFileName:@"RemoteConfigDefaults"];
    // Important! This needs to be applied before [FIRApp configure]
    if (!self.remoteConfig[@"perf_disable"].numberValue.boolValue) {
        // The following line disables all automatic (out-of-the-box) monitoring
        [FIRPerformance sharedInstance].instrumentationEnabled = NO;
        // The following line disables all custom monitoring
        [FIRPerformance sharedInstance].dataCollectionEnabled = NO;
    }
    else {
        [FIRPerformance sharedInstance].instrumentationEnabled = YES;
        [FIRPerformance sharedInstance].dataCollectionEnabled = YES;
    }
    // Use Firebase library to configure APIs
    [FIRApp configure];
    
  4. Добавьте в файл ViewController.m или другой файл реализации, используемый в приложении, следующий код, чтобы получить и активировать значения Remote Config:

    Swift

    Примечание. Этот продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.
    //RemoteConfig fetch and activation in your app, shortly after startup
    remoteConfig.fetch(withExpirationDuration: TimeInterval(30.0)) { (status, error) -> Void in
      if status == .success {
        print("Config fetched!")
        self.remoteConfig.activateFetched()
      } else {
        print("Config not fetched")
        print("Error \(error!.localizedDescription)")
      }
    }
    

    Objective-C

    Примечание. Этот продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.
    //RemoteConfig fetch and activation in your app, shortly after startup
    [self.remoteConfig fetchWithExpirationDuration:30.0 completionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) {
      if (status == FIRRemoteConfigFetchStatusSuccess) {
        NSLog(@"Config fetched!");
        [self.remoteConfig activateFetched];
      } else {
        NSLog(@"Config not fetched");
        NSLog(@"Error %@", error.localizedDescription);
      }
    }];
    
  5. Чтобы отключить Performance Monitoring в консоли Firebase, создайте параметр perf_disable в проекте приложения и задайте для него значение true.

    Если вы зададите для perf_disable значение false, Performance Monitoring останется включенным.

Как отключить автоматический или специальный сбор данных по отдельности

Вы можете внести некоторые изменения в код, показанный выше и в консоли Firebase, чтобы отключить весь автоматический (стандартный) мониторинг отдельно от пользовательского.

  1. Добавьте следующий код в операторы launchOptions в методе экземпляра application:didFinishLaunchingWithOptions: (вместо того, что показано выше для того же метода экземпляра):

    Swift

    Примечание. Этот продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.
    remoteConfig = FIRRemoteConfig.remoteConfig()
    let remoteConfigSettings = FIRRemoteConfigSettings(developerModeEnabled: true)
    remoteConfig.configSettings = remoteConfigSettings!
    // Important! This needs to be applied before FirebaseApp.configure()
    if remoteConfig["perf_disable_auto"].boolValue {
        // The following line disables all automatic (out-of-the-box) monitoring
        Performance.sharedInstance().isInstrumentationEnabled = false
    }
    else {
        Performance.sharedInstance().isInstrumentationEnabled = true
    }
    if remoteConfig["perf_disable_manual"].boolValue {
        // The following line disables all custom monitoring
        Performance.sharedInstance().isDataCollectionEnabled = false
    }
    else {
        Performance.sharedInstance().isDataCollectionEnabled = true
    }
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    

    Objective-C

    Примечание. Этот продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.
    self.remoteConfig = [FIRRemoteConfig remoteConfig];
    FIRRemoteConfigSettings *remoteConfigSettings =
        [[FIRRemoteConfigSettings alloc] initWithDeveloperModeEnabled:YES];
    self.remoteConfig.configSettings = remoteConfigSettings;
    // Important! This needs to be applied before [FirebaseApp configure]
    if (self.remoteConfig[@"perf_disable_auto"].numberValue.boolValue) {
        // The following line disables all automatic (out-of-the-box) monitoring
        [FIRPerformance sharedInstance].instrumentationEnabled = NO;
    }
    else {
        [FIRPerformance sharedInstance].instrumentationEnabled = YES;
    }
    if (self.remoteConfig[@"perf_disable_manual"].numberValue.boolValue) {
        // The following line disables all custom monitoring
        [FIRPerformance sharedInstance].dataCollectionEnabled = NO;
    }
    else {
        [FIRPerformance sharedInstance].dataCollectionEnabled = YES;
    }
    // Use Firebase library to configure APIs
    [FirebaseApp configure];
    
  2. Выполните следующие действия в консоли Firebase:

    • Чтобы отключить автоматический мониторинг, создайте в проекте приложения параметр perf_disable_auto и задайте для него значение true.
    • Чтобы отключить весь специальный мониторинг, создайте в проекте приложения параметр perf_disable_manual и задайте для него значение true.