Search code examples
iosswiftcrashlyticsgoogle-fabric

How to print customize logging in Crashlytics Swift?


We have install pod file for fabric and crashlytics and imported in the app delegate. Fabric.with([Crashlytics.self, Branch.self]) in didFinishLaunchingWithOptions function. It's working fine. But I want to print which action could be clicked by the user. Eg) Clicked Login Button.

I saw we can call this function, But where can i call this?

func write(string: String) {
        CLSLogv("%@", getVaList([string]))
    }

we won't be able to find the line of code from this crash

How to print custom logs in fabric? Which default function get called while getting crash?


Solution

  • You can create CrashLogger class with logEvent function which takes eventName as String and data dictionary which is [String: CustomStringConvertible] format to pass any relevant info to Crashlytics

    import Crashlytics
    
    final class CrashLogger {
    
        static let shared = CrashLogger()
    
        private init() { }
    
        func logEvent(_ event: String, withData data: [String: CustomStringConvertible]) {
            let dataString = data.reduce("Event: \(event): ", { (result, element: (key: String, value: CustomStringConvertible)) -> String in
                return result + " (" + element.key + ": " + String(describing: element.value) + " )"
            })
            logEvent(dataString)
        }
    
        private func logEvent(_ message: String) {
            CLSLogv("%@", getVaList([message]))
        }
    }
    

    Now you can call this logEvent method whenever you want to log the custom event in Crashlytics and it will be available in logs section when you view any crash in Firebase.

    How to use: for example addToCart function in eCommerce application:

    func addToCard(_ product: Product) {
        CrashLogger.logEvent("addToCart", withData: ["productId": product.id, "productName": product.name)
        //do further processing like update cart item count etc.
    }
    

    Refer Crashlytics custom logging docs for further info.