How to disable Firebase Crash Reporting when the app is running on debug?
Asked Answered
C

16

77

I have successfully implemented Firebase Crash Reporting, but I need to disable the service when the app is running undo the 'debug' Build Variant, in order to avoid non-real crashes in the console during the development.

The official documentation doesn't say anything about this.

Catboat answered 23/5, 2016 at 17:12 Comment(4)
if (!development) { FirebaseCrash.report(e);}Enfield
Thanks, @James_Parsons, but I did not mean that. I need to disable automatic crash reporting, not just the manual calls to the API.Catboat
releaseCompile 'com.google.firebase:firebase-crash:9.8.0' won't this work? it is supposed to add the dependency only for your release builds, hence while developing the library won't be added to the project, right?Contusion
check this answer: https://mcmap.net/q/266462/-can-39-t-disable-crashlytics-in-a-firebase-app-anymoreBalmung
C
48

UPDATED: With Google Play Services / Firebase 11+ you could now disable crash reporting at runtime. FirebaseCrash.setCrashCollectionEnabled() (Thanks @Tyler Carberry)

OLD ANSWER:

There is no official support for this, as far as the community has been able to surmise. The best way I would suggest to do this is, set up multiple Firebase apps in your dashboard, one for each build type, and set up multiple google_services.json files directing to each different app depending on the build variant.

Cognize answered 23/5, 2016 at 17:19 Comment(11)
Okay, this could be useful. How can I tweak the google_services.json file so it can depends on my current Build Variant? As far as I know, you can only define different files based on the build variant, if they are in the app/src/{flavor}, but this file is in the app directory rootCatboat
Yeah, you're exactly right, you just need to move things around. Create app/src/release directory and move the current google_services.json file into there, then put the new files that were generated for each app type into the other folders.Cognize
Thanks! The tweak was useful. Hope to see this feature soon in the Firebase SDK.Catboat
Hi, I'm with the Crash Reporting team. We are looking into providing a way for you to disable crash reporting programmatically. We also found that some developers in some parts of the world are not allowed to collect crashes for legal reasons, and they also need a way to disable crash reporting at runtime.Flap
@DougStevenson it has been quite a while since your comment and I don't seem to find any way of disabling the automatic crash reporting. Any way to do it at the moment?Underfur
for more details on this answer, see: firebase.googleblog.com/2016/08/…Dispensation
Doesn't FB crash reporting only track apps signed with the specified keystore SHA1 under FB - Project Settings? If so then you are using debug.keystore for debug verison and FB shouldn't track that? I have the same problem as you but don't understand why tracking occurs when signed with another keystore?Trigg
@DougStevenson Has this been added since your last comment? If not, is there a ticket I can follow for updates?Rajewski
@ColinWhite Sorry, there is nothing available yet. If you follow Firebase on twitter (or me CodingDoug), you'll likely hear about any new stuff that way.Flap
With Google Play Services 11.0 you could now disable crash reporting at runtime. FirebaseCrash.setCrashCollectionEnabled(!BuildConfig.DEBUG);Deciduous
It is now FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(false);Sankaran
D
32

With Google Play Services 11.0 you could now disable crash reporting at runtime.

FirebaseCrash.setCrashCollectionEnabled(!BuildConfig.DEBUG);
Deciduous answered 8/6, 2017 at 3:17 Comment(1)
It is now FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(false);Sankaran
T
28

Recently was introduced the possibility to disable Firebase crash reporting in a official way. You need to upgrade the firebase android sdk to at least version 11.0.0

In order to do so, you need to edit your AndroidManifest.xml and add:

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

Inside the <application> block.

You can check if Firebase crash report is enabled at runtime using FirebaseCrash.isCrashCollectionEnabled().

Below a complete example to disable Firebase crash reporting in your debug builds.

build.gradle:

...
 buildTypes {

    release {
        ...
        resValue("bool", "FIREBASE_CRASH_ENABLED", "true")
    }

    debug {
        ...
        resValue("bool", "FIREBASE_CRASH_ENABLED", "false")

    }

}
...
dependencies {
    ...
    compile "com.google.firebase:firebase-core:11.0.0"
    compile "com.google.firebase:firebase-crash:11.0.0"
    ...
}

AndroidManifest.xml:

 <application>

    <meta-data
        android:name="firebase_crash_collection_enabled"
        android:value="@bool/FIREBASE_CRASH_ENABLED"/>
...
Twedy answered 9/6, 2017 at 8:9 Comment(6)
Does the flag firebase_crash_collection_enabled work for version 9.2.1 of Firebase?Vingtetun
@Vingtetun no, the feature was not yet availableTwedy
This is a great solution and is based on the documented mechanism for disabled Crashlytics. The manifest key is now 'firebase_crashlytics_collection_enabled' by the way.Cardona
@Leon, sorry mate, you are wrong. This approach is an android standard de facto for enable/disable things in manifest, the fact that is similar to the approach used by Crashlytics documentation is totally random!Twedy
Not "firebase_crash_collection_enabled" but "firebase_crashlytics_collection_enabled" - from firebase.google.com/docs/crashlytics/customize-crash-reportsSectorial
@AlexShevelev Firebase Crashlytics is a different product, here we refer to firebase crash reporting, now deprecatedTwedy
H
11

in my Application class, onCreate()

if (BuildConfig.DEBUG) {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
            Log.wtf("Alert", paramThrowable.getMessage(), paramThrowable);
            System.exit(2); //Prevents the service/app from freezing
        }
    });
}

It works because it takes the oldHandler, which includes the Firebase one

 final UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();

out of the processing path

Houdon answered 5/9, 2016 at 0:56 Comment(0)
R
11

You can change the firebase crash dependency to a release only dependency.

To do this, you define it as a releaseCompile dependency

releaseCompile 'com.google.firebase:firebase-crash:9.4.0'

Now it will only be included in the release builds. If you have other custom build types that you want crash reporting for, you can add it to them to.

customBuildTypeCompile 'com.google.firebase:firebase-crash:9.4.0'
Rhodian answered 8/12, 2016 at 9:4 Comment(1)
FYI, even using this method, it appears that Firebase saves up all the crashes in a database, and if you ever install a release version on your emulator (to test ProGuard, for instance), it will then upload ALL the saved crashes.Sheridansherie
S
9

The simple and easy trick I used is to add firebase crash reporting dependency in release build only in build.gradle file.

This will remove crash reporting library from debug build type and add this in release build only.

dependencies {
    releaseCompile 'com.google.firebase:firebase-crash:10.2.0'
}
Staple answered 23/2, 2017 at 6:37 Comment(0)
C
7

Inspired by this related answer and others here, I came up with this handy solution.

Using Timber for logging, I created different implementations of a Tree subclass for debug and release builds. In debug, it defers to DebugTree which writes to logcat. In release, it forwards exceptions and high-priority logs to Firebase, dropping the rest.

build.gradle

dependencies {
  ...
  compile 'com.jakewharton.timber:timber:4.3.0'
  releaseCompile 'com.google.firebase:firebase-crash:9.0.2'
}

src/debug/java/[package]/ForestFire.java

import timber.log.Timber;

public class ForestFire extends Timber.DebugTree {}

src/release/java/[package]/ForestFire.java

import android.util.Log;
import com.google.firebase.crash.FirebaseCrash;
import timber.log.Timber;

public class ForestFire extends Timber.Tree {
  @Override
  protected void log(int priority, String tag, String message, Throwable t) {
    if (Log.WARN <= priority) {
      FirebaseCrash.log(message);
      if (t != null) {
        FirebaseCrash.report(t);
      }
    }
  }
}

App startup

Timber.plant(new ForestFire());
Cutlerr answered 7/9, 2016 at 16:2 Comment(0)
S
6

First initialize variables in the gradle file and check whether it is in debug or in release mode. The best way to submit the crash report is within the Application class.

Build.gradle

    buildTypes {
         release {
             buildConfigField "Boolean", "REPORT_CRASH", '"true"'
             debuggable false
         }
         debug {
             buildConfigField "Boolean", "REPORT_CRASH", '"false"'
             debuggable true
         }
    }

Now first check the mode and submit the crash report if crashed .

Application.java

    /** Report FirebaseCrash Exception if application crashed*/
    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
    {
        @Override
        public void uncaughtException (Thread thread, Throwable e)
        {
            /** Check whether it is development or release mode*/
            if(BuildConfig.REPORT_CRASH)
            {
                FirebaseCrash.report( e);
            }
        }
    });
Strawflower answered 9/6, 2016 at 10:54 Comment(1)
for the first part you can simply use BuildConfig.DEBUGHersh
C
4

Currently you can't disable firebase crash reporting although you can deactivate firebase analytics.

So one way to do this is creating another app with different ID within same firebase project. After this you just need to change appID to enable or disable firebase crash reporting. I created below two app for my convenience:

AppID:com.android - For release build type

AppID:com.android.debug - For debug build type

Please follow below link for more details:

https://firebase.googleblog.com/2016/08/organizing-your-firebase-enabled-android-app-builds.html

Edit: You don't need to change appID in android project again and again. There is a better way to use different appID for debug build type-

android {
    defaultConfig {
        applicationId "com.android"
        ...
    }
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }
    }
}

Checkout the link for more details:

https://developer.android.com/studio/build/application-id.html

Edit2:

Basically in above solution you are making two different app in Firebase project, And this way you can separate your development and production errors.

FYI Firebase crash reporting is deprecated. You should use Fabrics Crashlytics (Owned by Google). It has some really cool features.

Carrack answered 18/1, 2017 at 5:49 Comment(0)
N
2

For FirebaseAnalytics class.
Disable collection: setAnalyticsCollectionEnabled(false);
Enable collection: setAnalyticsCollectionEnabled(true); or write to AndroidManifest.xml in the application tag: <meta-data android:name="firebase_analytics_collection_enabled" android:value="false" />

Possible use:

if (BuildConfig.DEBUG){ //disable for debug
    mFirebaseAnalytics.setAnalyticsCollectionEnabled(false);
}

Source

Necessity answered 23/2, 2017 at 12:53 Comment(0)
B
1

First you will have to create debug and release build variants and then set a variable with boolean value. Then you will need to get that value from your java file which extends application i.e from where you enable Fabric crash reporting.

A code example is given below.

In your app's build.gradle file, add the following lines to create 2 build variants debug and release and then add a variable with boolean value.

defaultConfig {
    buildConfigField 'boolean', 'ENABLE_ANALYTICS', 'true'
}

buildTypes {
    debug {
        applicationIdSuffix ".debug"
        versionNameSuffix 'DEBUG'
        buildConfigField 'boolean', 'ENABLE_ANALYTICS', 'false'
    }
    release {
        minifyEnabled false
    }
}

Then when you are trying to add Fabric crash reporting check the value for ENABLE_ANALYTICS

public class Test extends Application {

private GoogleAnalytics googleAnalytics;
private static Tracker tracker;

@Override
public void onCreate() {
    super.onCreate();
    if (BuildConfig.ENABLE_ANALYTICS)
        Fabric.with(this, new Crashlytics());
    }
}

You can see the value for ENABLE_ANALYTICS by ctrl + click on the value. Hope this helps.

Bessie answered 24/5, 2017 at 5:38 Comment(0)
N
1

The simplest solution for users when they run app in Debug mode or in Release mode:

AndroidManifest.xml:

<meta-data
            android:name="firebase_crash_collection_enabled"
            android:value="${analytics_deactivated}"/>

build.gradle(Module:app)

buildTypes {

        debug {
            manifestPlaceholders = [analytics_deactivated: "false"]
        }

        release {
            manifestPlaceholders = [analytics_deactivated: "true"]

        }
    }

Hence, when the app is in release mode, the crashlatics will be turned on and app runs in debug mode, it would be turned off.

Niggardly answered 11/10, 2019 at 9:20 Comment(0)
K
1

I guess the recent firebase crashlytics has this implementation.

 FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG)
Katerine answered 21/11, 2020 at 15:7 Comment(0)
C
0

I use versionCode as filter for local/production builds.

gradle.properties

VERSION_CODE=1

app/build.gradle

android {
    defaultConfig {
        versionCode VERSION_CODE as int
    }
}

When publishing new version of app, just set new value from command line:

./gradlew build -PVERSION_CODE=new_value

Otherwise, when you're building from Android Studio, you will always get the same versionCode, so you can easily distinguish crash reports in Firebase console.

Cano answered 23/11, 2016 at 10:54 Comment(0)
A
0

As has been said before - there is no official way to do this. But the worst workaround for me as mentioned @mark-d is to reset DefaultUncaughtExceptionHandler (https://mcmap.net/q/264891/-how-to-disable-firebase-crash-reporting-when-the-app-is-running-on-debug).

But if you just call System.exit(2) as was suggested - the app will be instantly closed on exception, without any dialog message and hard getting debug logs. If this is important to you, there is a way to restore default handler:

if (BuildConfig.DEBUG) {
        final Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
        if (currentHandler.getClass().getPackage().getName()
                                                .startsWith("com.google.firebase")) {
            final Thread.UncaughtExceptionHandler defaultHandler = 
                getPrivateFieldByType(currentHandler, Thread.UncaughtExceptionHandler.class);
            Thread.setDefaultUncaughtExceptionHandler(defaultHandler);
        }
}

Where

public static <T> T getPrivateFieldByType(Object obj, Class<T> fieldType) {
    if (obj != null && fieldType != null) {
        for (Field field : obj.getClass().getDeclaredFields()) {
            if (field.getType().isAssignableFrom(fieldType)) {
                boolean accessible = field.isAccessible();
                if (!accessible) field.setAccessible(true);
                T value = null;
                try {
                    //noinspection unchecked
                    value = (T) field.get(obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (!accessible) field.setAccessible(false);
                return value;
            }
        }
    }
    return null;
}
Aldose answered 21/2, 2017 at 10:28 Comment(0)
R
0
public class MyApp extends Application {
    public static boolean isDebuggable;

    public void onCreate() {
        super.onCreate();
        isDebuggable = (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
        FirebaseCrash.setCrashCollectionEnabled(!isDebuggable);
    }
}
Robalo answered 5/11, 2017 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.