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


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

Например, отключив Performance Monitoring в процессе сборки приложения , вы можете:

  • Disable certain functionalities of Performance Monitoring (such as those provided by the Performance Monitoring Gradle plugin ) in your debug builds, but re-enable the functionalities for your release build.

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

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

You can also build your app with Performance Monitoring enabled , but use Firebase Remote Config to give you flexibility to disable (and re-enable) Performance Monitoring in your production app. With this option, you can even configure your app to let users opt-in or opt-out of using Performance Monitoring .

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

Вы можете отключить Performance Monitoring в процессе сборки , отключив плагин Performance Monitoring Gradle и/или отключив библиотеку Performance Monitoring для Android .

During development and debugging, disabling the plugin is useful because instrumentation by the plugin can contribute to increased build time. You might, though, consider keeping the library enabled so that you can still view performance data from app start, app-in-foreground, and app-in-background traces as well as any custom code traces in your app.

Отключите плагин Performance Monitoring Gradle.

Вы можете отключить плагин Performance Monitoring , добавив флаг instrumentationEnabled , используя следующие параметры:

Отключите плагин с помощью флага свойства расширения.

С помощью флага свойства Extensions можно отключить плагин Performance Monitoring для определенного варианта сборки во время компиляции.

  1. В корневом (проектном) файле Gradle ( <project>/build.gradle.kts или <project>/build.gradle ) убедитесь, что для зависимости Android Gradle Plugin указана версия 3.4.0 или более поздняя.

    For earlier versions of the Android Gradle Plugin, you can still disable the Performance Monitoring plugin for a specific build variant, but the build time contribution for that variant won't be completely eliminated.

  2. Add the following flag to your module (app-level) Gradle file (usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle ), then set it to false to disable the Performance Monitoring plugin.

    Kotlin

    import com.google.firebase.perf.plugin.FirebasePerfExtension
    
    // ...
    
    android {
      // ...
      buildTypes {
        getByName("debug") {
          configure<FirebasePerfExtension> {
            // Set this flag to 'false' to disable @AddTrace annotation processing and
            // automatic monitoring of HTTP/S network requests
            // for a specific build variant at compile time.
            setInstrumentationEnabled(false)
          }
        }
      }
    }

    Groovy

    android {
      // ...
      buildTypes {
        debug {
          FirebasePerformance {
            // Set this flag to 'false' to disable @AddTrace annotation processing and
            // automatic monitoring of HTTP/S network requests
            // for a specific build variant at compile time.
            instrumentationEnabled false
          }
        }
      }
    }

Отключите плагин с помощью флага в свойствах проекта.

С помощью флага в свойствах проекта можно отключить плагин Performance Monitoring для всех вариантов сборки во время компиляции.

Добавьте следующий флаг в файл gradle.properties , а затем установите его значение в false , чтобы отключить плагин Performance Monitoring .

// ...

// Set this flag to 'false' to disable @AddTrace annotation processing and
// automatic monitoring of HTTP/S network requests
// for all build variants at compile time.
firebasePerformanceInstrumentationEnabled=false

Отключите библиотеку Performance Monitoring Android.

Если вы отключите библиотеку Performance Monitoring во время компиляции, вы сможете выбрать, разрешить ли вашему приложению включать эту библиотеку во время выполнения.

Отключите библиотеку на этапе компиляции, но разрешите приложению включить её во время выполнения.

Добавьте следующий элемент <meta-data> в файл AndroidManifest.xml вашего приложения:

  <application>
    <meta-data
      android:name="firebase_performance_collection_enabled"
      android:value="false" />
  </application>

Отключите библиотеку на этапе компиляции, но не позволяйте приложению включать её во время выполнения.

Добавьте следующий элемент <meta-data> в файл AndroidManifest.xml вашего приложения:

  <application>
    <meta-data
      android:name="firebase_performance_collection_deactivated"
      android:value="true" />
  </application>

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

Firebase Remote Config lets you make changes to the behavior and appearance of your app, so it provides an ideal way to let you disable Performance Monitoring in deployed instances of your app.

To disable Performance Monitoring data collection the next time that your Android app starts, use the example code shown below. For more information about using Remote Config in an Android app, see Use Firebase Remote Config on Android .

  1. Убедитесь, что Remote Config находится в разделе dependencies вашего модуля (на уровне приложения) в файле Gradle (обычно <project>/<app-module>/build.gradle.kts или <project>/<app-module>/build.gradle ):

    Kotlin

      implementation("com.google.firebase:firebase-config-ktx:23.1.0")
    

    Java

      implementation("com.google.firebase:firebase-config:23.1.0")
    
  2. Настройте Remote Config и отключите Performance Monitoring , если perf_disable имеет значение true :

    Kotlin

    // Setup remote config
    val config = Firebase.remoteConfig
    
    // You can uncomment the following two statements to permit more fetches when
    // validating your app, but you should comment out or delete these lines before
    // distributing your app in production.
    // val configSettings = remoteConfigSettings {
    //     minimumFetchIntervalInSeconds = 3600
    // }
    // config.setConfigSettingsAsync(configSettings)
    // Load in-app defaults from an XML file that sets perf_disable to false until you update
    // values in the Firebase Console
    
    // Observe the remote config parameter "perf_disable" and disable Performance Monitoring if true
    config.setDefaultsAsync(R.xml.remote_config_defaults)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Firebase.performance.isPerformanceCollectionEnabled = !config.getBoolean("perf_disable")
            } else {
                // An error occurred while setting default parameters
            }
        }

    Java

    // Setup remote config
    final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
    
    // You can uncomment the following two statements to permit more fetches when
    // validating your app, but you should comment out or delete these lines before
    // distributing your app in production.
    // FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
    //       .setMinimumFetchIntervalInSeconds(3600)
    //       .build();
    // config.setConfigSettingsAsync(configSettings);
    // Load in-app defaults from an XML file that sets perf_disable to false until you update
    // values in the Firebase Console
    
    //Observe the remote config parameter "perf_disable" and disable Performance Monitoring if true
    config.setDefaultsAsync(R.xml.remote_config_defaults)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        if (config.getBoolean("perf_disable")) {
                            FirebasePerformance.getInstance().setPerformanceCollectionEnabled(false);
                        } else {
                            FirebasePerformance.getInstance().setPerformanceCollectionEnabled(true);
                        }
                    } else {
                        // An error occurred while setting default parameters
                    }
                }
            });
  3. Добавьте следующий код в файл MainActivity.java , чтобы получить и активировать значения Remote Config :

    Kotlin

    // Remote Config fetches and activates parameter values from the service
    val config = Firebase.remoteConfig
    config.fetch(3600)
        .continueWithTask { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }
            config.activate()
        }
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Parameter values successfully activated
                // ...
            } else {
                // Handle errors
            }
        }

    Java

    //Remote Config fetches and activates parameter values from the service
    final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
    config.fetch(3600)
            .continueWithTask(new Continuation<Void, Task<Boolean>>() {
                @Override
                public Task<Boolean> then(@NonNull Task<Void> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }
                    return config.activate();
                }
            })
            .addOnCompleteListener(new OnCompleteListener<Boolean>() {
                @Override
                public void onComplete(@NonNull Task<Boolean> task) {
                    if (task.isSuccessful()) {
                        // Parameter values successfully activated
                        // ...
                    } else {
                        // Handle errors
                    }
                }
            });
  4. Чтобы отключить Performance Monitoring в консоли Firebase , создайте параметр perf_disable в проекте вашего приложения, а затем установите его значение равным true .

    This change will make calls to the Performance Monitoring SDK "no operation" calls (NOOPs), eliminating any significant effects on app performance from using the Performance Monitoring SDK in your app.

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