На этой странице приведены советы по устранению неполадок, которые помогут приступить к работе с Performance Monitoring или использовать функции и инструменты Performance Monitoring .
Первые проверки для устранения неполадок
Следующие две проверки представляют собой общие рекомендации для всех, прежде чем приступать к дальнейшему устранению неполадок.
1. Проверьте сообщения журнала на наличие событий производительности.
Проверьте сообщения журнала, чтобы убедиться, что Performance Monitoring SDK фиксирует события производительности.
Включите ведение журнала отладки для Performance Monitoring во время сборки, добавив элемент
<meta-data>в файлAndroidManifest.xmlвашего приложения, например:<application> <meta-data android:name="firebase_performance_logcat_enabled" android:value="true" /> </application>Проверьте сообщения журнала на наличие сообщений об ошибках.
Performance Monitoring помечает свои сообщения журнала тегом
FirebasePerformance. Используя фильтрацию LogCat, вы можете просматривать трассировку длительности и журнал сетевых запросов HTTP/S, выполнив следующую команду:adb logcat -s FirebasePerformance
Проверьте следующие типы журналов, которые указывают на то, что Performance Monitoring регистрирует события производительности:
-
Logging trace metric: TRACE_NAME , FIREBASE_PERFORMANCE_CONSOLE_URL -
Logging network request trace: URL
-
Нажмите на URL-адрес, чтобы просмотреть данные в консоли Firebase. Обновление данных на панели управления может занять несколько минут.
Если ваше приложение не регистрирует события производительности, ознакомьтесь с советами по устранению неполадок .
2. Проверьте панель состояния Firebase.
Проверьте панель состояния Firebase на предмет известных сбоев в работе Firebase или Performance Monitoring .
Начало работы с Performance Monitoring
Если вы только начинаете работать с Performance Monitoring ( iOS+ | Android | Web ), следующие советы по устранению неполадок могут помочь в решении проблем, связанных с обнаружением Firebase SDK или отображением первых данных о производительности в консоли Firebase .
Firebase может определить, успешно ли вы добавили SDK Performance Monitoring в своё приложение, получая информацию о событиях (например, о взаимодействиях с приложением). Обычно в течение 10 минут после запуска приложения на панели производительности консоли Firebase отображается сообщение «SDK обнаружен». Затем, в течение 30 минут, на панели отображаются первоначально обработанные данные.
Если с момента добавления последней версии SDK в приложение прошло более 10 минут, а изменений по-прежнему нет, проверьте сообщения журнала , чтобы убедиться, что Performance Monitoring регистрирует события. Чтобы устранить задержку с сообщением об обнаружении SDK, попробуйте выполнить соответствующие действия, описанные ниже.
Убедитесь, что вы используете Performance Monitoring Android SDK 19.1.0 или более позднюю версию (или Firebase BoM 26.3.0 или более позднюю версию), см. Заметки о выпуске .
Если вы все еще ведете локальную разработку, попробуйте сгенерировать больше событий для сбора данных:
- Создавайте события, переключая приложение между фоновым и передним режимами несколько раз, взаимодействуя с приложением путем навигации по экранам и/или запуская сетевые запросы.
Убедитесь, что файл конфигурации Firebase (
google-services.json) корректно добавлен в приложение и не был изменён. В частности, проверьте следующее:Имя файла конфигурации не дополняется дополнительными символами, например
(2).Файл конфигурации находится в каталоге модуля (уровня приложения) вашего приложения.
Идентификатор приложения Firebase Android (
mobilesdk_app_id), указанный в файле конфигурации, верен для вашего приложения. Найдите идентификатор приложения Firebase на карточке «Ваши приложения» в проекта .
Если с файлом конфигурации вашего приложения что-то не так, попробуйте сделать следующее:
Удалите файл конфигурации, который в данный момент есть в вашем приложении.
Следуйте этим инструкциям , чтобы загрузить новый файл конфигурации и добавить его в приложение Android.
Если SDK регистрирует события и все настроено правильно, но вы по-прежнему не видите сообщение об обнаружении SDK или обработанные данные (спустя 10 минут), обратитесь в службу поддержки Firebase .
Проверьте настройку плагина Gradle Performance Monitoring следующим образом:
Убедитесь, что вы правильно добавили плагин . В частности, проверьте следующее:
- Вы добавили плагин (
) в файлapply plugin: 'com.google.firebase.firebase-perf' build.gradleвашего модуля (уровня приложения) . - You included the classpath dependency for the plugin (
) in your project-levelclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradlefile.
- Вы добавили плагин (
Убедитесь, что плагин не отключен с помощью одного из следующих флагов:
-
instrumentationEnabledв файлеbuild.gradleвашего модуля (на уровне приложения) -
firebasePerformanceInstrumentationEnabledв файлеgradle.properties
-
Проверьте, что Performance Monitoring SDK не отключен с помощью одного из следующих флагов в файле
AndroidManifest.xml:-
firebase_performance_collection_enabled -
firebase_performance_collection_deactivated
-
Убедитесь, что Performance Monitoring не отключен во время выполнения .
Если вы не можете найти что-либо отключенное в своем приложении, обратитесь в службу поддержки Firebase .
Performance Monitoring обрабатывает данные о событиях производительности перед их отображением на панели мониторинга производительности .
Если с момента появления сообщения «SDK обнаружен» прошло более 24 часов , а данные по-прежнему не отображаются, проверьте панель состояния Firebase на наличие известных сбоев. Если сбоев нет, обратитесь в службу поддержки Firebase .
Общее устранение неполадок
Если вы успешно добавили SDK и используете Performance Monitoring в своем приложении, следующие советы по устранению неполадок могут помочь в решении общих проблем, связанных с функциями и инструментами Performance Monitoring .
Если вы не видите сообщения журнала о событиях производительности , попробуйте выполнить следующие действия по устранению неполадок:
Проверьте настройку плагина Gradle Performance Monitoring следующим образом:
Убедитесь, что вы правильно добавили плагин . В частности, проверьте следующее:
- Вы добавили плагин (
) в файлapply plugin: 'com.google.firebase.firebase-perf' build.gradleвашего модуля (уровня приложения) . - Вы включили зависимость classpath для плагина (
) в файлclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradleуровня проекта .
- Вы добавили плагин (
Убедитесь, что плагин не отключен с помощью одного из следующих флагов:
-
instrumentationEnabledв файлеbuild.gradleвашего модуля (на уровне приложения) -
firebasePerformanceInstrumentationEnabledв файлеgradle.properties
-
Проверьте, что Performance Monitoring SDK не отключен с помощью одного из следующих флагов в файле
AndroidManifest.xml:-
firebase_performance_collection_enabled -
firebase_performance_collection_deactivated
-
Убедитесь, что Performance Monitoring не отключен во время выполнения .
Если вы не можете найти что-либо отключенное в своем приложении, обратитесь в службу поддержки Firebase .
Если у вас отсутствуют данные для трассировок рендеринга экрана, попробуйте выполнить следующие действия по устранению неполадок:
Убедитесь, что вы используете последнюю версию Android SDK (v22.0.4). Трассировка рендеринга экрана доступна только в версии 15.2.0 и более поздних.
Убедитесь, что вы вручную не отключили аппаратное ускорение для экрана.
Убедитесь, что вы не используете DexGuard или Jack. Performance Monitoring несовместим с этими инструментами.
DexGuard отключает автоматический сбор трассировок запуска приложения, приложений, работающих на переднем плане и в фоновом режиме. Однако любые трассировки пользовательского кода должны работать нормально, если ваше приложение использует DexGuard.
Jack устарел и, как правило, не должен использоваться в вашем приложении.
Видите ли вы данные о производительности для автоматически собранных трассировок , но не для трассировок пользовательского кода ? Попробуйте выполнить следующие действия для устранения неполадок:
Если вы настроили пользовательские трассировки кода с помощью Trace API , проверьте настройку трассировок, особенно следующее:
- Имена для пользовательских трассировок кода и пользовательских метрик должны соответствовать следующим требованиям: не должно быть начальных или конечных пробелов, не должно быть начального символа подчеркивания (
_), а максимальная длина составляет 32 символа. - Все трассировки должны быть запущены и остановлены. Любая трассировка, которая не была запущена, не была остановлена или остановлена до начала, не будет зарегистрирована.
- Имена для пользовательских трассировок кода и пользовательских метрик должны соответствовать следующим требованиям: не должно быть начальных или конечных пробелов, не должно быть начального символа подчеркивания (
Если вы инструментировали трассировку пользовательского кода с помощью нотации
@AddTrace, проверьте настройку плагина Gradle Performance Monitoring :Убедитесь, что вы правильно добавили плагин . В частности, проверьте следующее:
- Вы добавили плагин (
) в файлapply plugin: 'com.google.firebase.firebase-perf' build.gradleвашего модуля (уровня приложения) . - Вы включили зависимость classpath для плагина (
) в файлclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradleуровня проекта .
- Вы добавили плагин (
Убедитесь, что плагин не отключен с помощью одного из следующих флагов:
-
instrumentationEnabledв файлеbuild.gradleвашего модуля (на уровне приложения) -
firebasePerformanceInstrumentationEnabledв файлеgradle.properties
-
Проверьте сообщения журнала , чтобы убедиться, что Performance Monitoring регистрирует ожидаемые следы пользовательского кода.
Если Performance Monitoring регистрирует события, но данные не отображаются в течение 24 часов, обратитесь в службу поддержки Firebase .
Если у вас отсутствуют данные сетевого запроса, попробуйте выполнить следующие действия по устранению неполадок:
Для приложений Android плагин Performance Monitoring Gradle обеспечивает инструментарий для автоматического мониторинга сетевых запросов HTTP/S . Проверьте следующее:
Убедитесь, что вы правильно добавили плагин . В частности, проверьте следующее:
- Вы добавили плагин (
) в файлapply plugin: 'com.google.firebase.firebase-perf' build.gradleвашего модуля (уровня приложения) . - Вы включили зависимость classpath для плагина (
) в файлclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradleуровня проекта .
- Вы добавили плагин (
Убедитесь, что плагин не отключен с помощью одного из следующих флагов:
-
instrumentationEnabledв файлеbuild.gradleвашего модуля (на уровне приложения) -
firebasePerformanceInstrumentationEnabledв файлеgradle.properties
-
Проверьте совместимость сетевых библиотек. Performance Monitoring автоматически собирает метрики для сетевых запросов, использующих следующие сетевые библиотеки: OkHttp 3.xx, URLConnection Java и Apache HttpClient.
Обратите внимание, что вы можете добавить пользовательский мониторинг сетевых запросов .
Имейте в виду следующее:
В зависимости от поведения вашего кода и используемых им сетевых библиотек, Performance Monitoring может регистрировать только завершённые сетевые запросы. Это означает, что данные об оставшихся открытых HTTP/S-соединениях могут не регистрироваться.
Performance Monitoring несовместим с DexGuard и Jack.
- DexGuard отключает мониторинг сетевых запросов HTTP/S.
- Jack устарел и, как правило, не должен использоваться в вашем приложении.
Performance Monitoring не отслеживает сетевые запросы с недопустимыми заголовками
Content-Type. Однако сетевые запросы без заголовковContent-Typeбудут по-прежнему приниматься.
Узнайте больше о том, как Performance Monitoring объединяет данные сетевых запросов по шаблонам URL.
Вы также можете попробовать пользовательские шаблоны URL !
Часто задаваемые вопросы
Мы заменили раздел «Основные проблемы» на раздел «Недавние оповещения» вслед за недавним введением оповещений, которые автоматически уведомляют вас о превышении установленных вами пороговых значений. Раздел «Ошибки» теперь устарел и заменен оповещениями.
Селектор приложений в верхней части карточки «Производительность» фильтрует записи оповещений в разделе «Недавние оповещения» . Отображаются только три последних оповещения для выбранных приложений.
Дополнительную информацию об оповещениях см. в разделе Настройка оповещений о проблемах с производительностью .
Performance Monitoring поддерживает оповещения о метриках, превышающих заданные пороговые значения. Чтобы избежать путаницы с настраиваемыми пороговыми значениями для метрик производительности, мы удалили возможность настраивать пороговые значения для проблем .
Мы заменили страницы «Подробности» и «Метрики» новым, переработанным, централизованным пользовательским интерфейсом (UI), чтобы улучшить процесс устранения неполадок. Этот новый пользовательский интерфейс предлагает те же основные функции, что и страницы «Подробности» и «Метрики». Подробнее об устранении неполадок см. в разделе «Просмотр дополнительных данных для конкретной трассировки» .
Performance Monitoring собирает данные о производительности с пользовательских устройств вашего приложения. Если у вашего приложения много пользователей или оно генерирует большой объём активности, связанной с производительностью, Performance Monitoring может ограничить сбор данных подмножеством устройств, чтобы сократить количество обрабатываемых событий. Эти ограничения достаточно высоки, чтобы даже при меньшем количестве событий значения метрик по-прежнему отражали пользовательский опыт использования приложения.
Для управления объемом собираемых данных Performance Monitoring использует следующие параметры выборки:
Ограничение скорости на устройстве : чтобы предотвратить внезапные выбросы данных трассировки, мы ограничиваем количество событий кода и сетевых запросов, отправляемых устройством, 300 событиями каждые 10 минут. Такой подход защищает устройство от зацикливания измерительных приборов, которые могут отправлять большие объёмы данных о производительности, и предотвращает искажение результатов измерений одним устройством.
Динамическая выборка : Performance Monitoring собирает ограниченное количество трассировок кода и сетевых запросов для каждого приложения ежедневно для всех пользователей приложения. На устройствах задаётся динамическая частота выборки (с помощью Firebase Remote Config ), чтобы определить, следует ли случайному устройству захватывать и отправлять трассировки. Устройство, не выбранное для выборки, не отправляет никаких событий. Динамическая частота выборки зависит от приложения и корректируется, чтобы общий объём собираемых данных оставался ниже установленного лимита.
Проекты, в которых реализована интеграция BigQuery, получают более высокий лимит на количество трассировок сетевых запросов.
Сеансы пользователей отправляют дополнительные подробные данные с устройства, что требует больше ресурсов для сбора и отправки данных. Чтобы минимизировать влияние сеансов пользователей, Performance Monitoring может также ограничить их количество.
Ограничение скорости на стороне сервера : Чтобы приложения не превышали лимит выборки, Performance Monitoring может использовать выборку на стороне сервера для отбрасывания некоторых событий, полученных от устройств. Хотя такое ограничение не влияет на эффективность наших метрик, оно может привести к незначительным изменениям в шаблонах, включая следующие:
- Количество следов может отличаться от количества выполнений фрагмента кода.
- Трассы, тесно связанные в коде, могут иметь разное количество выборок.
Мы заменили вкладку «Проблемы» функцией «Оповещения», которая автоматически уведомляет вас о превышении установленных вами пороговых значений. Вам больше не нужно вручную проверять консоль Firebase , чтобы определить статус порогового значения. Подробнее об оповещениях см. в статье «Настройка оповещений о проблемах с производительностью» .
Мы переработали раздел Performance Monitoring консоли Firebase , чтобы на вкладке «Панель мониторинга» отображались ключевые метрики и все ваши данные отслеживания в одном месте. В рамках редизайна мы удалили страницы «На устройстве» и «Сеть» .
Таблица трассировок в нижней части вкладки «Панель мониторинга» содержит ту же информацию, что и на вкладках «На устройстве» и «Сеть» , но с некоторыми дополнительными функциями, включая возможность сортировки трассировок по процентному изменению определённой метрики. Чтобы просмотреть все метрики и данные для конкретной трассировки, щёлкните по её названию в таблице трассировок.
Просматривайте свои трассировки на следующих подвкладках таблицы трассировок:
- Трассировки сетевых запросов (как готовые, так и пользовательские) — вкладка «Сетевые запросы»
- Пользовательские трассировки кода — вкладка «Пользовательские трассировки»
- Трассировки запуска приложения, приложения на переднем плане, приложения в фоновом режиме — вкладка «Пользовательские трассировки»
- Следы рендеринга экрана — вкладка «Рендеринг экрана»
- Следы загрузки страницы — вкладка «Загрузка страницы»
Подробную информацию о таблице трассировок и просмотре метрик и данных можно найти на странице обзора консоли ( iOS+ | Android | Web ).
Медленно отрисовываемые кадры и зависшие кадры рассчитываются с учётом предполагаемой частоты обновления устройства 60 Гц. Если частота обновления устройства ниже 60 Гц, время отрисовки каждого кадра будет меньше, поскольку в секунду обрабатывается меньше кадров. Более медленная отрисовка может привести к увеличению количества медленных или зависших кадров, поскольку большее количество кадров будет отрисовываться медленнее или зависать. Однако, если частота обновления устройства выше 60 Гц, время отрисовки каждого кадра будет меньше. Это может привести к уменьшению количества медленных или зависших кадров. Это текущее ограничение Performance Monitoring SDK.
Чтобы отслеживать производительность фрагментов в дополнение к активности приложения, убедитесь, что ваше приложение использует Performance Monitoring Android SDK версии 20.1.0 или выше. Подробнее см. в статье Добавление мониторинга производительности в ваше приложение .
Каждая трассировка фрагмента и активности основана на имени класса, определённого в вашем приложении. Каждая трассировка экрана содержит префикс st, за которым следует имя класса. В консоли Firebase этот префикс удаляется. Подробнее см. в статье «Данные о производительности рендеринга экрана (приложения Apple и Android)» .
Performance Monitoring осуществляет выборку всех событий, собранных на устройстве. Такой подход позволяет собирать минимально необходимое количество событий с пользовательских устройств для предоставления метрик производительности.
Performance Monitoring позволяет настроить оповещения по интересующим вас показателям. Для созданных трассировок рендеринга экрана вы можете настроить оповещения , которые будут уведомлять вас, когда процент медленных и зависших кадров превысит заданное вами пороговое значение.
Performance Monitoring для Android использует инструментирование байт-кода для предоставления некоторых готовых функций, таких как мониторинг сетевых запросов HTTP/S . В процессе компиляции требуется итерация по всем классам приложения (включая зависимости) для инструментирования кода, критически важного для измерения производительности сетевых запросов вашего приложения.
Вот некоторые основные факторы, способствующие увеличению времени сборки:
- Количество классов или файлов
- Размер каждого из этих классов (строки кода)
- Конфигурация вашей машины
- Первоначальная сборка по сравнению с последующей сборкой (последующие сборки обычно быстрее первоначальной)
Чтобы оптимизировать время сборки, рассмотрите возможность модулизации кода .
Начиная с версии 1.3.3 плагина Performance Monitoring , мы сосредоточились на значительном улучшении обработки инкрементальной сборки и кэширования входных данных библиотеки. Чтобы получить самые актуальные улучшения времени сборки, убедитесь, что у вас установлена последняя версия плагина (v2.0.2) .
Обратите внимание, что вы можете локально отключить плагин Performance Monitoring для отладочных сборок, чтобы избежать длительного времени сборки. Однако этот подход не рекомендуется для производственных сборок, так как он может привести к пропуску измерений производительности сетевых запросов в вашем приложении.
Performance Monitoring для Android использует инструментирование байт-кода для предоставления некоторых готовых функций, таких как мониторинг сетевых запросов HTTP/S . В процессе компиляции требуется итерация по всем классам приложения (включая зависимости) для инструментирования кода, критически важного для измерения производительности сетевых запросов вашего приложения.
Если после интеграции с плагином Performance Monitoring возникают ошибки сборки, например JSR/RET are not supported with computeFrames option , или аналогичные ошибки, это может быть связано с тем, что у вас также есть зависимость от библиотеки, несовместимой с плагином Performance Monitoring Gradle.
Чтобы обойти эту проблему, можно исключить несовместимые классы/библиотеки из инструментирования, выполнив следующие шаги:
- Обновите плагин Performance Monitoring Gradle до последней версии (минимум v1.4.0 ).
- Обновите версию плагина Android Gradle до версии 7.2.0 или более новой.
- Добавьте следующий флаг в файл
build.gradleвашего модуля (уровня приложения), чтобы исключить несовместимые классы/библиотеки из инструментирования: Дополнительную информацию о свойствеandroid { // ... androidComponents { onVariants(selector().all(), { instrumentation.excludes.add("example.incompatible.library") }) } }
excludeAPIInstrumentationплагина Android Gradle см. в разделе Инструментарий .
Если вы столкнулись с ошибками сборки из-за несовместимых библиотек, сообщите о них на Github, чтобы их также можно было исключить из анализа в плагине Performance Monitoring .
Если вы включили интеграцию BigQuery для Firebase Performance Monitoring , ваши данные будут экспортированы в BigQuery через 12–24 часа после окончания дня (по тихоокеанскому времени).
Например, данные за 19 апреля будут доступны в BigQuery 20 апреля с 12:00 до полуночи (все даты и время указаны по тихоокеанскому времени).
Near real-time data processing and display
Firebase Performance Monitoring processes collected performance data as it comes in, which results in near real-time data display in the Firebase console. Processed data displays in the console within a few minutes of its collection, hence the term "near real-time".
To take advantage of near real-time data processing, make sure your app uses a real-time compatible SDK version .
To take advantage of near real-time data processing, you only need to make sure that your app uses a Performance Monitoring SDK version that's compatible with real-time data processing.
These are the real-time compatible SDK versions:
- iOS — v7.3.0 or later
- tvOS — v8.9.0 or later
- Android — v19.0.10 or later (or Firebase Android BoM v26.1.0 or later)
- Web — v7.14.0 or later
Note that we always recommend using the latest version of SDK, but any version listed above will enable Performance Monitoring to process your data in near real time.
These are the SDK versions compatible with real-time data processing:
- iOS — v7.3.0 or later
- tvOS — v8.9.0 or later
- Android — v19.0.10 or later (or Firebase Android BoM v26.1.0 or later)
- Web — v7.14.0 or later
Note that we always recommend using the latest version of SDK, but any version listed above will enable Performance Monitoring to process your data in near real time.
If your app doesn't use a real-time compatible SDK version, you will still see all your app's performance data in the Firebase console. However, the display of performance data will be delayed by roughly 36 hours from the time of its collection.
Yes! Regardless of which SDK version an app instance uses, you'll see performance data from all your users.
However, if you're looking at recent data (less than roughly 36 hours old), then the displayed data is from users of app instances using a real-time compatible SDK version. The non-recent data, though, includes performance data from all versions of your app.
Contacting Firebase Support
If you reach out to Firebase Support , always include your Firebase App ID. Find your Firebase App ID in the Your apps card of your Project settings .
,This page provides troubleshooting tips for getting started with Performance Monitoring or using Performance Monitoring features and tooling.
First checks for troubleshooting
The following two checks are general best practices recommended for anyone before further troubleshooting.
1. Check log messages for performance events
Check your log messages to be sure that the Performance Monitoring SDK is capturing performance events.
Enable debug logging for Performance Monitoring at build time by adding a
<meta-data>element to your app'sAndroidManifest.xmlfile, like so:<application> <meta-data android:name="firebase_performance_logcat_enabled" android:value="true" /> </application>Check your log messages for any error messages.
Performance Monitoring tags its log messages with
FirebasePerformance. Using logcat filtering, you can specifically view duration trace and HTTP/S network request logging by running the following command:adb logcat -s FirebasePerformance
Check for the following types of logs which indicate that Performance Monitoring is logging performance events:
-
Logging trace metric: TRACE_NAME , FIREBASE_PERFORMANCE_CONSOLE_URL -
Logging network request trace: URL
-
Click on the URL to view your data in the Firebase console. It may take a few moments for the data to update in the dashboard.
If your app isn't logging performance events, review the troubleshooting tips .
2. Check the Firebase Status Dashboard
Check the Firebase Status Dashboard in case there is a known outage for Firebase or for Performance Monitoring .
Getting started with Performance Monitoring
If you're getting started with Performance Monitoring ( iOS+ | Android | Web ), the following troubleshooting tips can help with issues that involve Firebase detecting the SDK or displaying your first performance data in the Firebase console.
Firebase can detect if you've successfully added the Performance Monitoring SDK to your app when it receives event information (like app interactions) from your app. Usually within 10 minutes of starting your app, the Performance dashboard of the Firebase console displays an "SDK detected" message. Then, within 30 minutes, the dashboard displays the initial processed data.
If it's been more than 10 minutes since you added the latest version of SDK to your app, and you're still not seeing any change, check your log messages to make sure that Performance Monitoring is logging events. Try the appropriate troubleshooting steps as described below to troubleshoot a delayed SDK detection message.
Make sure that you're using the Performance Monitoring Android SDK 19.1.0 or later (or Firebase BoM 26.3.0 or later), see Release Note .
If you're still developing locally, try generating more events for data collection:
- Generate events by switching your app between background and foreground several times, interacting with your app by navigating across screens, and/or triggering network requests.
Make sure that your Firebase configuration file (
google-services.json) is correctly added to your app and that you haven't modified the file. Specifically, check the following:The config file name isn't appended with additional characters, like
(2).The config file is in the module (app-level) directory of your app.
The Firebase Android App ID (
mobilesdk_app_id) listed in the config file is correct for your app. Find your Firebase App ID in the Your apps card of your Project settings .
If anything seems wrong with the config file in your app, try the following:
Delete the config file that you currently have in your app.
Follow these instructions to download a new config file and add it to your Android app.
If the SDK is logging events and everything seems to be set up correctly, but you're still not seeing the SDK detection message or processed data (after 10 minutes), contact Firebase Support .
Check the setup of the Performance Monitoring Gradle plugin, as follows:
Make sure that you added the plugin correctly. Specifically, check the following:
- You added the plugin (
) in your module (app-level)apply plugin: 'com.google.firebase.firebase-perf' build.gradlefile. - You included the classpath dependency for the plugin (
) in your project-levelclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradlefile.
- You added the plugin (
Make sure that the plugin is not disabled through either of the following flags:
-
instrumentationEnabledin your module (app-level)build.gradlefile -
firebasePerformanceInstrumentationEnabledin yourgradle.propertiesfile
-
Check that the Performance Monitoring SDK is not disabled through either of the following flags in your
AndroidManifest.xmlfile:-
firebase_performance_collection_enabled -
firebase_performance_collection_deactivated
-
Make sure that Performance Monitoring is not disabled at runtime .
If you can't find anything that's disabled in your app, contact Firebase Support .
Performance Monitoring processes performance event data before displaying it in the Performance dashboard .
If it's been more than 24 hours since the "SDK detected" message appeared , and you're still not seeing data, then check the Firebase Status Dashboard in case there is a known outage. If there is no outage, contact Firebase Support .
Общее устранение неполадок
If you've successfully added the SDK and are using Performance Monitoring in your app, the following troubleshooting tips can help with general issues that involve Performance Monitoring features and tooling.
If you're not seeing log messages for performance events , try the following troubleshooting steps:
Check the setup of the Performance Monitoring Gradle plugin, as follows:
Make sure that you added the plugin correctly. Specifically, check the following:
- You added the plugin (
) in your module (app-level)apply plugin: 'com.google.firebase.firebase-perf' build.gradlefile. - You included the classpath dependency for the plugin (
) in your project-levelclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradlefile.
- You added the plugin (
Make sure that the plugin is not disabled through either of the following flags:
-
instrumentationEnabledin your module (app-level)build.gradlefile -
firebasePerformanceInstrumentationEnabledin yourgradle.propertiesfile
-
Check that the Performance Monitoring SDK is not disabled through either of the following flags in your
AndroidManifest.xmlfile:-
firebase_performance_collection_enabled -
firebase_performance_collection_deactivated
-
Make sure that Performance Monitoring is not disabled at runtime .
If you can't find anything that's disabled in your app, contact Firebase Support .
If you're missing data for screen rendering traces, try the following troubleshooting steps:
Make sure that you're using the latest version of the Android SDK (v22.0.4). Screen rendering traces are only available with v15.2.0 or later.
Make sure that you haven't manually disabled Hardware Acceleration for a screen.
Make sure that you're not using DexGuard or Jack. Performance Monitoring is incompatible with these toolchains.
DexGuard disables automatic collection of app start, app-in-foreground, and app-in-background traces. However, any custom code traces should behave normally if your app uses DexGuard.
Jack is deprecated and generally should not be used in your app.
Are you seeing performance data for automatically collected traces but not for custom code traces ? Try the following troubleshooting steps:
If you instrumented custom code traces via the Trace API , check the setup of the traces, especially the following:
- Names for custom code traces and custom metrics must meet the following requirements: no leading or trailing whitespace, no leading underscore (
_) character, and max length is 32 characters. - All traces must be started and stopped. Any trace that is not started, not stopped, or stopped before started will not be logged.
- Names for custom code traces and custom metrics must meet the following requirements: no leading or trailing whitespace, no leading underscore (
If you instrumented custom code traces via
@AddTracenotation , check the setup of the Performance Monitoring Gradle plugin:Make sure that you added the plugin correctly. Specifically, check the following:
- You added the plugin (
) in your module (app-level)apply plugin: 'com.google.firebase.firebase-perf' build.gradlefile. - You included the classpath dependency for the plugin (
) in your project-levelclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradlefile.
- You added the plugin (
Make sure that the plugin is not disabled through either of the following flags:
-
instrumentationEnabledin your module (app-level)build.gradlefile -
firebasePerformanceInstrumentationEnabledin yourgradle.propertiesfile
-
Check your log messages to make sure that Performance Monitoring is logging expected custom code traces.
If Performance Monitoring is logging events, but no data displays after 24 hours, contact Firebase Support .
If you're missing network request data, try the following troubleshooting steps:
For Android apps, the Performance Monitoring Gradle plugin enables instrumentation that provides automatic monitoring of HTTP/S network requests . Check the following:
Make sure that you added the plugin correctly. Specifically, check the following:
- You added the plugin (
) in your module (app-level)apply plugin: 'com.google.firebase.firebase-perf' build.gradlefile. - You included the classpath dependency for the plugin (
) in your project-levelclasspath 'com.google.firebase:perf-plugin:2.0.2' build.gradlefile.
- You added the plugin (
Make sure that the plugin is not disabled through either of the following flags:
-
instrumentationEnabledin your module (app-level)build.gradlefile -
firebasePerformanceInstrumentationEnabledin yourgradle.propertiesfile
-
Check for network library incompatibility. Performance Monitoring automatically collects metrics for network requests that use the following networking libraries: OkHttp 3.xx, Java's URLConnection, and Apache HttpClient.
Note that you can add custom monitoring for network requests .
Be aware of the following:
Depending on the behavior of your code and networking libraries used by your code, Performance Monitoring might only report on network requests that are completed. This means that HTTP/S connections that are left open might not be reported.
Performance Monitoring is not compatible with DexGuard and Jack.
- DexGuard disables monitoring of HTTP/S network requests.
- Jack is deprecated and generally should not be used in your app.
Performance Monitoring does not report on network requests with invalid
Content-Typeheaders. However, network requests without theContent-Typeheaders will still be accepted.
Learn more about how Performance Monitoring aggregates network request data under URL patterns.
You can also try out custom URL patterns !
Часто задаваемые вопросы
We replaced Top Issues with Recent Alerts as a follow-up to our recent introduction of alerts, which automatically notify you when the thresholds you set are crossed. Issues are now deprecated and replaced by alerts.
The apps selector at the top of the Performance card filters the alert entries under Recent Alerts . Only the three most recent alerts for the app(s) selected are displayed.
To learn more about alerts, see Set up alerts for performance issues .
Performance Monitoring supports alerts for metrics that exceed defined thresholds. To avoid confusion with these configurable thresholds for performance metrics, we removed the ability to configure thresholds for issues .
We replaced the Details and Metrics pages with a newly redesigned, centralized user interface (UI) to improve how you troubleshoot issues. This new troubleshooting UI offers the same core functionality that Details and Metrics offered. To learn more about troubleshooting, see View more data for a specific trace .
Performance Monitoring collects performance data from your app's user devices. If your application has many users or if the app generates a large amount of performance activity, Performance Monitoring might limit data collection to a subset of devices to reduce the number of processed events. These limits are high enough so that, even with fewer events, the metric values are still representative of your user's app experience.
To manage the volume of data that we collect, Performance Monitoring uses the following sampling options:
On-device rate limiting : To prevent a device from sending sudden bursts of traces, we limit the number of code and network request traces sent from a device to 300 events every 10 mins. This approach protects the device from looped instrumentations that can send large amounts of performance data, and it prevents a single device from skewing the performance measurements.
Dynamic sampling : Performance Monitoring collects a limited number of code traces and network request traces per app daily across all app users. A dynamic sampling rate is fetched on devices (using Firebase Remote Config ) to determine whether a random device should capture and send traces. A device that is not selected for sampling does not send any events. The dynamic sampling rate is app-specific and adjusts to ensure that the overall volume of collected data remains below the limit.
Projects that enabled BigQuery integration receive a higher limit for the number of network request traces.
User sessions send additional, detailed data from a user's device, requiring more resources to capture and send the data. To minimize the impact of user sessions, Performance Monitoring might also restrict the number of sessions.
Server-side rate limiting : To ensure that apps don't exceed the sampling limit, Performance Monitoring might use server-side sampling to drop some events received from devices. Although this type of limiting doesn't change the effectiveness of our metrics, it may cause minor pattern shifts, including the following:
- The number of traces can differ from the number of times that a piece of code was executed.
- Traces that are closely coupled in code may each have a different number of samples.
We replaced the Issues tab with the introduction of Alerts, which automatically notifies you when the thresholds you set are exceeded. You no longer need to manually check the Firebase console to determine the status of a threshold. To learn about Alerts, see Set up alerts for performance issues .
We've redesigned the Performance Monitoring section of the Firebase console so that the Dashboard tab displays your key metrics and all your traces in one space. As part of the redesign, we removed the On device and Network pages.
The traces table at the bottom of the Dashboard tab has all the same information that the On device and Network tabs displayed, but with some added features, including the ability to sort your traces by the percentage change for a specific metric. To view all the metrics and data for a specific trace, click the trace name in the traces table.
View your traces in the following subtabs of the traces table:
- Network request traces (both out-of-the-box and custom) — Network requests subtab
- Custom code traces — Custom traces subtab
- App start, app-in-foreground, app-in-background traces — Custom traces subtab
- Screen rendering traces — Screen rendering subtab
- Page load traces — Page load subtab
For details about the traces table and viewing metrics and data, visit the console overview page ( iOS+ | Android | Web ).
Slow rendering frames and frozen frames are calculated with an assumed device refresh rate of 60Hz. If a device refresh rate is lower than 60Hz, each frame will have a slower rendering time because fewer frames are rendered per second. Slower rendering times can cause more slow or frozen frames to be reported because more frames will be rendered slower or will freeze. However, if a device refresh rate is higher than 60Hz, each frame will have a faster rendering time. This can cause fewer slow or frozen frames to be reported. This is a current limitation in the Performance Monitoring SDK.
To see the performance of fragments in addition to app activity, make sure that your app is using Performance Monitoring Android SDK version 20.1.0 or above. To learn more, see Add Performance Monitoring to your app .
Each of the fragment and activity traces is based on its class name as defined in your application. Each of the screen traces contains the st prefix followed by the name of the class. On the Firebase console, the prefix is removed. To learn more, see Learn about screen rendering performance data (Apple & Android apps) .
Performance Monitoring conducts event sampling across all events collected on a device. This approach lets us collect the minimum events needed from user devices to provide performance metrics.
Performance Monitoring lets you set up alerts for the metrics you care about. For generated screen rendering traces, you can set up alerts to notify you when the slow and frozen frames percentage exceeds a threshold that you set.
Performance Monitoring for Android uses bytecode instrumentation to provide some out-of-the-box features like monitoring HTTP/S network requests . As a part of compilation, the process requires iteration through all the classes of your app (including dependencies) to instrument the code that is crucial in measuring the network request performance of your application.
Here are some key contributors to an increase in build time:
- Number of classes or files
- Size of each of those classes (lines of code)
- Your machine configuration
- Initial build versus a subsequent build (subsequent builds are usually faster than the initial build)
To optimize your build time, consider modularizing your code .
Starting with v1.3.3 of the Performance Monitoring plugin, we've concentrated on making considerable improvements in the incremental build processing and caching of library inputs. To receive the most recent build time improvements, make sure to use the latest version of the plugin (v2.0.2) .
Note that you can disable the Performance Monitoring plugin for your debug builds locally if you want to avoid long build times. However, this approach is not recommended for production builds, as it could result in missed performance measurements for the network requests in your app.
Performance Monitoring for Android uses bytecode instrumentation to provide some out-of-the-box features like monitoring HTTP/S network requests . As a part of compilation, the process requires iteration through all the classes of your app (including dependencies) to instrument the code that is crucial in measuring the network request performance of your application.
If you get build errors like JSR/RET are not supported with computeFrames option or similar errors after integrating with the Performance Monitoring plugin, this might be because you also have a dependency on a library that's incompatible with the Performance Monitoring Gradle plugin.
To get around this, you can exclude incompatible classes/libraries from being instrumented by following these steps:
- Update to the latest version of Performance Monitoring Gradle plugin (minimum v1.4.0 ).
- Update your Android Gradle plugin version to v7.2.0 or newer.
- Add the following flag to your module (app-level)
build.gradlefile to exclude the incompatible classes/libraries from being instrumented: To learn more about theandroid { // ... androidComponents { onVariants(selector().all(), { instrumentation.excludes.add("example.incompatible.library") }) } }
excludeproperty of Android Gradle plugin'sInstrumentationAPI, see Instrumentation .
Please file a Github issue when you encounter build errors due to incompatible libraries so that they can also be excluded from being instrumented in the Performance Monitoring plugin.
If you have enabled the BigQuery integration for Firebase Performance Monitoring , your data will be exported to BigQuery 12 to 24 hours after the end of the day (Pacific Time).
For example, the data for April 19th will be available in BigQuery on April 20th between 12:00pm and midnight (all dates and times are Pacific Time).
Near real-time data processing and display
Firebase Performance Monitoring processes collected performance data as it comes in, which results in near real-time data display in the Firebase console. Processed data displays in the console within a few minutes of its collection, hence the term "near real-time".
To take advantage of near real-time data processing, make sure your app uses a real-time compatible SDK version .
To take advantage of near real-time data processing, you only need to make sure that your app uses a Performance Monitoring SDK version that's compatible with real-time data processing.
These are the real-time compatible SDK versions:
- iOS — v7.3.0 or later
- tvOS — v8.9.0 or later
- Android — v19.0.10 or later (or Firebase Android BoM v26.1.0 or later)
- Web — v7.14.0 or later
Note that we always recommend using the latest version of SDK, but any version listed above will enable Performance Monitoring to process your data in near real time.
These are the SDK versions compatible with real-time data processing:
- iOS — v7.3.0 or later
- tvOS — v8.9.0 or later
- Android — v19.0.10 or later (or Firebase Android BoM v26.1.0 or later)
- Web — v7.14.0 or later
Note that we always recommend using the latest version of SDK, but any version listed above will enable Performance Monitoring to process your data in near real time.
If your app doesn't use a real-time compatible SDK version, you will still see all your app's performance data in the Firebase console. However, the display of performance data will be delayed by roughly 36 hours from the time of its collection.
Yes! Regardless of which SDK version an app instance uses, you'll see performance data from all your users.
However, if you're looking at recent data (less than roughly 36 hours old), then the displayed data is from users of app instances using a real-time compatible SDK version. The non-recent data, though, includes performance data from all versions of your app.
Contacting Firebase Support
If you reach out to Firebase Support , always include your Firebase App ID. Find your Firebase App ID in the Your apps card of your Project settings .