Отключить мониторинг производительности Firebase


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

Ниже приведены некоторые варианты для рассмотрения:

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

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

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

Отключите 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 вашего приложения:

    Быстрый

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

    Objective-C

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

    Быстрый

    Примечание: этот продукт недоступен на платформах 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 :

    Быстрый

    Примечание: этот продукт 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: (вместо показанного выше для того же метода экземпляра):

    Быстрый

    Примечание: этот продукт 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 .