development

앱이 디버그에서 실행될 때 Firebase 오류보고를 비활성화하는 방법은 무엇입니까?

big-blog 2020. 10. 26. 08:11
반응형

앱이 디버그에서 실행될 때 Firebase 오류보고를 비활성화하는 방법은 무엇입니까?


Firebase 오류보고를 성공적으로 구현했지만 개발 중에 콘솔에서 실제가 아닌 충돌을 방지하기 위해 앱이 실행 중일 때 '디버그'빌드 변형을 실행 취소하여 서비스를 비활성화해야합니다.

공식 문서는 이것에 대해 아무것도 말하지 않습니다.


업데이트 : 이제 Google Play 서비스 / Firebase 11 이상을 사용하여 런타임에 오류보고를 비활성화 할 수 있습니다. FirebaseCrash.setCrashCollectionEnabled()( @Tyler Carberry 에게 감사드립니다 )

이전 답변 :

커뮤니티가 추측 할 수있는 한 이에 대한 공식적인 지원은 없습니다. 이 작업을 수행하는 가장 좋은 방법은 대시 보드에서 각 빌드 유형에 대해 하나씩 여러 Firebase 앱을 설정하고 빌드 변형에 따라 각기 다른 앱으로 전달되는 여러 google_services.json 파일을 설정하는 것입니다.


이제 Google Play 서비스 11.0을 사용하여 런타임에 오류보고를 비활성화 할 수 있습니다.

FirebaseCrash.setCrashCollectionEnabled(!BuildConfig.DEBUG);

최근 에 공식적으로 Firebase 충돌보고를 비활성화 할 수있는 가능성이 도입되었습니다. firebase android sdk를 버전 11.0.0 이상으로 업그레이드해야합니다.

이렇게하려면 다음을 편집 AndroidManifest.xml하고 추가 해야 합니다.

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

<application>블록 내부 .

FirebaseCrash.isCrashCollectionEnabled ()를 사용하여 런타임에 Firebase 오류 보고서가 사용 설정되었는지 확인할 수 있습니다 .

아래는 디버그 빌드에서 Firebase 오류보고를 사용 중지하는 전체 예입니다.

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"/>
...

내 응용 프로그램 클래스에서 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
        }
    });
}

Firebase를 포함하는 oldHandler를 사용하기 때문에 작동합니다.

 final UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();

처리 경로에서


Firebase 비정상 종료 종속성을 릴리스 전용 종속성으로 변경할 수 있습니다.

이를 위해 releaseCompile 종속성으로 정의합니다.

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

이제 릴리스 빌드에만 포함됩니다. 비정상 종료보고를 원하는 다른 사용자 지정 빌드 유형이있는 경우 추가 할 수 있습니다.

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

내가 사용한 간단하고 쉬운 트릭은 build.gradle파일의 릴리스 빌드에만 firebase 충돌보고 종속성을 추가하는 것입니다 .

그러면 디버그 빌드 유형에서 충돌보고 라이브러리가 제거되고 릴리스 빌드에만 추가됩니다.

dependencies {
    releaseCompile 'com.google.firebase:firebase-crash:10.2.0'
}

이 관련 답변 과 다른 사람들 로부터 영감을 받아이 편리한 솔루션을 찾았습니다.

로깅을 위해 Timber사용하여 디버그 및 릴리스 빌드를위한 Tree 하위 클래스의 다양한 구현을 만들었습니다. 디버그에서는 logcat에 쓰는 DebugTree를 따릅니다. 릴리스에서는 예외와 우선 순위가 높은 로그를 Firebase에 전달하고 나머지는 삭제합니다.

build.gradle

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

src / debug / java / [패키지] /ForestFire.java

import timber.log.Timber;

public class ForestFire extends Timber.DebugTree {}

src / release / java / [패키지] /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);
      }
    }
  }
}

앱 시작

Timber.plant(new ForestFire());

먼저 gradle 파일에서 변수를 초기화하고 디버그 모드인지 릴리스 모드인지 확인합니다. 충돌 보고서를 제출하는 가장 좋은 방법은 Application 클래스 내에 있습니다.

Build.gradle

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

이제 먼저 모드를 확인하고 충돌이 발생한 경우 충돌 보고서를 제출하십시오.

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);
            }
        }
    });

현재 Firebase 분석을 비활성화 할 수 있지만 Firebase 오류보고를 비활성화 할 수 없습니다.

따라서이를 수행하는 한 가지 방법은 동일한 Firebase 프로젝트 내에서 다른 ID로 다른 앱을 만드는 것입니다. 그런 다음 appID를 변경하여 firebase 오류보고를 사용 또는 사용 중지하면됩니다. 편의를 위해 아래 두 개의 앱을 만들었습니다.

AppID : com.android- 릴리스 빌드 유형용

AppID : com.android.debug- 디버그 빌드 유형용

자세한 내용은 아래 링크를 따르십시오.

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

편집 : 당신은 안드로이드 프로젝트에서 반복해서 appID를 변경할 필요가 없습니다. 디버그 빌드 유형에 다른 appID를 사용하는 더 좋은 방법이 있습니다.

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

자세한 내용은 링크를 확인하십시오.

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

편집 2 :

기본적으로 위의 솔루션에서는 Firebase 프로젝트에서 두 개의 다른 앱을 만들고 있습니다. 이렇게하면 개발 및 프로덕션 오류를 분리 할 수 ​​있습니다.

참고로 Firebase 오류보고는 지원이 중단되었습니다. Fabrics Crashlytics (Google 소유)를 사용해야합니다 . 정말 멋진 기능이 있습니다.


FirebaseAnalytics수업을 위해 .
컬렉션 비활성화 : 컬렉션 setAnalyticsCollectionEnabled(false);
활성화 : setAnalyticsCollectionEnabled(true);또는 AndroidManifest.xml애플리케이션 태그에 쓰기 :<meta-data android:name="firebase_analytics_collection_enabled" android:value="false" />

가능한 사용 :

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

출처


먼저 만들어야합니다 debugrelease빌드를 변형하고 부울 값을 가진 변수를 설정하십시오. 그런 다음 충돌보고 application를 활성화하는 위치에서 확장되는 Java 파일에서 해당 값을 가져와야합니다 Fabric.

코드 예제는 다음과 같습니다.

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.


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.


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://stackoverflow.com/a/39322734/4245651).

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;
}

public class MyApp extends Application {
    public static boolean isDebuggable;

    public void onCreate() {
        super.onCreate();
        isDebuggable = (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
        FirebaseCrash.setCrashCollectionEnabled(!isDebuggable);
    }
}

참고URL : https://stackoverflow.com/questions/37396826/how-to-disable-firebase-crash-reporting-when-the-app-is-running-on-debug

반응형