crashlytics (앱 내 설정)

부가 설명
문맥수집, 크래시 레포트, 스택 트레이스
Tags
Crashlytics

공식 문서

기타 블로그

 

설치 ( RN ≥ 0.60 기준 )

# Install & setup the app module yarn add @react-native-firebase/app # Install the Crashlytics module yarn add @react-native-firebase/crashlytics # If you're developing your app using iOS, run this command cd ios/ && pod install
 

안드로이드 추가 설정

안드로이드는 위 패키지 설치 외에도 추가 설정을 해야함. (안그러면 크래시남..!)
안드로이드 추가 설정

1) android/build.gradle - 구글 repo 추가

  • 안되어있으면 추가하면 됨. (일반적으로 돼있음)
// .. buildscript { // .. repositories { // .. google() } // .. }

2) android/build.gradle - Firebase Crashlytics 플러그인 디펜던시 추가

// .. buildscript { // .. dependencies { // .. classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1' } // .. }

3) android/app/build.gradle - 앱에 crashlytics 적용

apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' // 여기 아래에 추가해라 apply plugin: 'com.google.firebase.crashlytics' //추가 (new)

4) android/app/build.gradle - Crashlytics NDK reporting 활성화

(선택사항)
Crashlycis NDK reporting은 Native Development Kit crashes도 잡을 수 있게 해준다.
예를 들어 React Native에서는 요가 레이아웃 엔진에서 발생한 충돌을 캡처한다.
android { // ... buildTypes { release { /* firebaseCrashlytics extension이 기본적으로는 빌드 속도 향상을 위해 disabled된 상태이므로 추가하고, nativeSymbolUploadEnabled도 true로 설정한다. */ firebaseCrashlytics { nativeSymbolUploadEnabled true } // ... } } }

5) 프로젝트 Rebuild

$ npx react-native run-android
 

iOS 추가 설정

  • 설정을 제대로 하지 않으면 아래와 같은 에러가 뜬다.
notion image
Ios 추가 설정
  1. 앱 bundle ID 기입
    1. notion image
      • bundle ID는 xcode를 열어서 확인 및 설정할 수 있다.
      notion image
  1. GoogleService-Info.plist 파일 다운로드
    1. notion image
      notion image
      • xcodeproj에 해도 되나, 우리는 Pods를 쓰고 있으므로 xcworkspace에다 추가해야함.
  1. Firebase SDK 추가
    1. notion image
      # Podfile에 아래내용 추가 # add the Firebase pod for Google Analytics pod 'Firebase/Analytics' # add pods for any other desired Firebase products # https://firebase.google.com/docs/ios/setup#available-pods
       
  1. Configure Firebase with iOS credentials
    1. /ios/{프로젝트명}/AppDelegate.m 파일 수정

      구글 파이어베이스 앱 등록 시 보여주는 코드

      • Swift
      import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() return true } }
      • Objective-C
      // @import는 반드시 관련된 것 바로 위에 써줘야함. @import UIKit; @import Firebase; @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIRApp configure]; return YES; }
  1. Autolinking & rebuilding
# iOS apps cd ios/ pod install --repo-update cd .. npx react-native run-ios
6. 끝.
 

사용법

  • crash 메소드로 크래시 발생을 강제하여 관련 메소드들이 제대로 동작하는 지 테스트 할 수 있다.

1) log

log 메소드를 앱 전역에 사용함으로써 크래시 발생 상황과 관련된 문맥을 누적한다.
import crashlytics from '@react-native-firebase/crashlytics'; ... crashlytics().log('유저가 강의 탭에 진입함'); ...

2) Crash Attributes

문맥 정보 누적 뿐만 아니라 crashlytics에서는 크래시 리포트의 속성을 설정하는 다양한 메소드를 제공한다.
크래시에 대한 분석정보를 추가함으로써 분석 시 편의성을 제공함.
  • 사전 정의된 속성을 지정할 수도 있고,
    • crashlytics().setUserId(user.uid),
  • 커스텀 속성을 지정할 수도 있다.
    • crashlytics().setAttribute('credits', String(user.credits)),
  • 여러 속성 한번에 설정
    • crashlytics().setAttributes({ role: 'admin', followers: '13', email: user.email, username: user.username })

예시 코드

아래 코드에서 크래시가 나면 크래시 리포트에서 유추할 수 있는 점은 다음과 같다.
  1. log를 통해 유저가 로그인하는 상황이라는 것을 알 수 있고
  1. 속성 설정을 통해 유저가 기입한 정보인 uid, credits, role, followers, email, usename을 알 수 있다. (입력값에 문제가 있는지 확인 가능)
//예시 코드 import React, { useEffect } from 'react'; import { View, Button } from 'react-native'; import crashlytics from '@react-native-firebase/crashlytics'; async function onSignIn(user) { crashlytics().log('User signed in.'); await Promise.all([ //크래시 속성 설정 crashlytics().setUserId(user.uid), crashlytics().setAttribute('credits', String(user.credits)), crashlytics().setAttributes({ role: 'admin', followers: '13', email: user.email, username: user.username }), ]); } export default function App() { useEffect(() => { crashlytics().log('App mounted.'); //문맥정보 누적 }, []); return ( <View> <Button title="Sign In" onPress={() => onSignIn({ uid: 'Aa0Bb1Cc2Dd3Ee4Ff5Gg6Hh7Ii8Jj9', username: 'Joaquin Phoenix', email: 'phoenix@example.com', credits: 42, }) } /> {/* 크래시 강제 발생 메소드 */} <Button title="Test Crash" onPress={() => crashlytics().crash()} /> </View> ); }

3) Error Reports

크래시리틱스는 JavaScript stack trace을 Firebase 콘솔로 전송하는 것도 지원한다.
오류가 발생했지만 사용자의 코드로 인해 정상적으로 복구되는 모든 경우에 사용할 수 있다.
  • try - catch 문으로 예외 처리한 경우 등
stack trace을 전송하려면 recordError 메서드로 catch문에서 잡힌 Error 오브젝트를 전달하면 된다.
 
개발 중에는 기본적으로 error reporting이 꺼져있으므로, firebase.json에서 설정 값 수정 필요.
import React, { useState, useEffect } from 'react'; import { View, Text } from 'react-native'; import crashlytics from '@react-native-firebase/crashlytics'; const users = []; export default function App() { const [userCounts, setUserCounts] = useState(null); function updateUserCounts() { crashlytics().log('Updating user count.'); try { if (users) { // An empty array is truthy, but not actually true. // Therefore the array was never initialised. setUserCounts(userCounts.push(users.length)); } } catch (error) { crashlytics().recordError(error); console.log(error); } } useEffect(() => { crashlytics().log('App mounted.'); if (users == true) setUserCounts([]); updateUserCounts(); }, []); if (userCounts) { return ( <View> <Text>There are currently {userCounts[userCounts.length - 1]} users.</Text> </View> ); } return ( <View> <Text>Unable to display user information.</Text> </View> ); }

4) Opt-out (정보제공 동의 여부 on/off)

Crashlytics에서 유저와 관련된 주요 정보도 수집되는데, 유저가 opt-out 하기를 원할 수도 있다.
opt-out : 정보주체의 동의를 받지 않고 개인정보를 수집&이용 후, 당사자가 거부 의사를 밝히면 활용을 중지하는 방식.
  • log와 attribute를 통해 정보들은 설정되지만 crash report를 보내지 않는 방식
  • 수집 여부 설정은 간단하게 메소드 하나로 변경할 수 있다.
    • setCrashlyticsCollectionEnabled
import React, { useState } from 'react'; import { View, Button, Text } from 'react-native'; import crashlytics from '@react-native-firebase/crashlytics'; export default function App() { const [enabled, setEnabled] = useState(crashlytics().isCrashlyticsCollectionEnabled); async function toggleCrashlytics() { await crashlytics() .setCrashlyticsCollectionEnabled(!enabled) .then(() => setEnabled(crashlytics().isCrashlyticsCollectionEnabled)); } return ( <View> <Button title="Toggle Crashlytics" onPress={toggleCrashlytics} /> <Button title="Crash" onPress={() => crashlytics().crash()} /> <Text>Crashlytics is currently {enabled ? 'enabled' : 'disabled'}</Text> </View> ); }
 
 

firebase.json

옵셔널 파일 , 파이어베이스 설정 파일
firebase.json 설정 파일

1) Disable Auto Collection

firebase.json 설정 파일에서 auto_collection_enabled 옵션을 통해 Crashlytics가 보고서를 보낼지 여부를 구성할 수 있다.
사용자가 opt-in 하기를 원한다면 일단은 disable로 설정하고, 추후에 사용자가 opt-in 했을 때 메소드를 통해 enable로 변경되도록 하는 게 좋다.
opt-in : 정보주체가 개인 데이터 수집을 허용하기 전 까지 당사자의 데이터 수집을 금지하는 제도이다.
// <project-root>/firebase.json { "react-native": { "crashlytics_auto_collection_enabled": false } }

2) Enable debug crash logs

앱 디버깅 중에는 stack straces를 이미 갖고 있기 때문에 디버그 모드에서는 default로 Crashlytics가 disabled 된다. (개발 도중에는 기본적으로 꺼져있다는 뜻)
하지만 디버그 모드와 상관없이 Crashlytics를 활성화하려면 아래처럼 옵션을 설정하면 된다.
// <project-root>/firebase.json { "react-native": { "crashlytics_debug_enabled": true } }

3) Chrashlytics NDK

React Native Firebase는 Crashlytics NDK 리포팅을 지원하며 defaultenabled 되어있다.
이건 Crashlytics가 Yoga layout engine에서 유래된 크래시들을 캡처할 수 있도록 한다.
옵션을 끄려면 아래와 같이 설정하면 된다.
// <project-root>/firebase.json { "react-native": { "crashlytics_ndk_enabled": false } }