项目作者: WeTransfer

项目描述 :
Allow users to easily share Diagnostics with your support team to improve the flow of fixing bugs.
高级语言: Swift
项目地址: git://github.com/WeTransfer/Diagnostics.git
创建时间: 2019-12-02T10:43:07Z
项目社区:https://github.com/WeTransfer/Diagnostics

开源协议:MIT License

下载












Example mail composer Example Report

Diagnostics is a library written in Swift which makes it really easy to share Diagnostics Reports to your support team.

Features

The library allows to easily attach the Diagnostics Report as an attachment to the MFMailComposeViewController.

  • Integrated with the MFMailComposeViewController
  • Default reporters include:
    • App metadata
    • System metadata
    • System logs divided per session
  • Possibility to filter out sensitive data using a DiagnosticsReportFilter
  • A custom DiagnosticsLogger to add your own logs
  • Smart insights like “⚠️ User is low on storage” and “✅ User is using the latest app version”
  • Flexible setup to add your own smart insights
  • Flexible setup to add your own custom diagnostics
  • Native cross-platform support, e.g. iOS, iPadOS and macOS

Usage

The default report already contains a lot of valuable information and could be enough to get you going.

Make sure to set up the DiagnosticsLogger as early as possible to catch all the system logs, for example in the didLaunchWithOptions:

  1. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  2. do {
  3. try DiagnosticsLogger.setup()
  4. } catch {
  5. print("Failed to setup the Diagnostics Logger")
  6. }
  7. return true
  8. }

Then, simply show the MFMailComposeViewController using the following code:

  1. import UIKit
  2. import MessageUI
  3. import Diagnostics
  4. class ViewController: UIViewController {
  5. @IBAction func sendDiagnostics(_ sender: UIButton) {
  6. /// Create the report.
  7. let report = DiagnosticsReporter.create()
  8. guard MFMailComposeViewController.canSendMail() else {
  9. /// For debugging purposes you can save the report to desktop when testing on the simulator.
  10. /// This allows you to iterate fast on your report.
  11. report.saveToDesktop()
  12. return
  13. }
  14. let mail = MFMailComposeViewController()
  15. mail.mailComposeDelegate = self
  16. mail.setToRecipients(["support@yourcompany.com"])
  17. mail.setSubject("Diagnostics Report")
  18. mail.setMessageBody("An issue in the app is making me crazy, help!", isHTML: false)
  19. /// Add the Diagnostics Report as an attachment.
  20. mail.addDiagnosticReport(report)
  21. present(mail, animated: true)
  22. }
  23. }
  24. extension ViewController: MFMailComposeViewControllerDelegate {
  25. func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
  26. controller.dismiss(animated: true)
  27. }
  28. }

On macOS you could send the report by using the NSSharingService:

  1. import AppKit
  2. import Diagnostics
  3. func send(report: DiagnosticsReport) {
  4. let service = NSSharingService(named: NSSharingService.Name.composeEmail)!
  5. service.recipients = ["support@yourcompany.com"]
  6. service.subject = "Diagnostics Report"
  7. let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("Diagnostics-Report.html")
  8. // remove previous report
  9. try? FileManager.default.removeItem(at: url)
  10. do {
  11. try report.data.write(to: url)
  12. } catch {
  13. print("Failed with error: \(error)")
  14. }
  15. service.perform(withItems: [url])
  16. }

Using a UserDefaultsReporter

In order to use UserDefaultsReporter, you need to specify the desired UserDefaults instance together with all the keys you would like to read, and use it in DiagnosticsReporter.create(filename:using:filters:smartInsightsProvider) to create a DiagnosticsReport.

  1. let userDefaultsReporter = UserDefaultsReporter(
  2. userDefaults: UserDefaults(suiteName: "a.userdefaults.instance"),
  3. keys: ["key_1"]
  4. )
  5. let diagnosticsReport = DiagnosticsReporter.create(using: [userDefaultsReporter])

Filtering out sensitive data

It could be that your report is containing sensitive data. You can filter this out by creating a DiagnosticsReportFilter.

The example project contains an example of this:

  1. struct DiagnosticsDictionaryFilter: DiagnosticsReportFilter {
  2. // This demonstrates how a filter can be used to filter out sensible data.
  3. static func filter(_ diagnostics: Diagnostics) -> Diagnostics {
  4. guard let dictionary = diagnostics as? [String: Any] else { return diagnostics }
  5. return dictionary.filter { keyValue -> Bool in
  6. if keyValue.key == "App Display Name" {
  7. // Filter out the key with the value "App Display Name"
  8. return false
  9. } else if keyValue.key == "AppleLanguages" {
  10. // Filter out a user defaults key.
  11. return false
  12. }
  13. return true
  14. }
  15. }
  16. }

Which can be used by passing in the filter into the create(..) method:

  1. let report = DiagnosticsReporter.create(using: reporters, filters: [DiagnosticsDictionaryFilter.self])

Adding your own custom logs

To make your own logs appear in the logs diagnostics you need to make use of the DiagnosticsLogger.

  1. /// Support logging simple `String` messages.
  2. DiagnosticsLogger.log(message: "Application started")
  3. /// Support logging `Error` types.
  4. DiagnosticsLogger.log(error: ExampleError.missingData)

The error logger will make use of the localized description if available which you can add by making your error conform to LocalizedError.

Adding a directory tree report

It’s possible to add a directory tree report for a given set of URL, resulting in the following output:

  1. └── Documents
  2. +-- contents
  3. | +-- B3F2F9AD-AB8D-4825-8369-181DEAAFF940.png
  4. | +-- 5B9C090E-6CE1-4A2F-956B-15897AB4B0A1.png
  5. | +-- 739416EF-8FF8-4502-9B36-CEB778385BBF.png
  6. | +-- 27A3C96B-1813-4553-A6B7-436E6F3DBB20.png
  7. | +-- 8F176CEE-B28F-49EB-8802-CC0438879FBE.png
  8. | +-- 340C2371-A81A-4188-8E04-BC19E94F9DAE.png
  9. | +-- E63AFEBC-B7E7-46D3-BC92-E34A53C0CE0A.png
  10. | +-- 6B363F44-AB69-4A60-957E-710494381739.png
  11. | +-- 9D31CA40-D152-45D9-BDCE-9BB09CCB825E.png
  12. | +-- 304E2E41-9697-4F9A-9EE0-8D487ED60C45.jpeg
  13. | └── 7 more file(s)
  14. +-- diagnostics_log.txt
  15. +-- Okapi.sqlite
  16. +-- Library
  17. | +-- Preferences
  18. | | └── group.com.wetransfer.app.plist
  19. | └── Caches
  20. | └── com.apple.nsurlsessiond
  21. | └── Downloads
  22. | └── com.wetransfer
  23. +-- Coyote.sqlite-shm
  24. +-- Coyote.sqlite
  25. +-- Coyote.sqlite-wal
  26. +-- Okapi.sqlite-shm
  27. +-- Okapi.sqlite-wal
  28. └── 1 more file(s)

You can do this by adding the DirectoryTreesReporter:

  1. var reporters = DiagnosticsReporter.DefaultReporter.allReporters
  2. let documentsURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
  3. let directoryTreesReporter = DirectoryTreesReporter(
  4. directories: [
  5. documentsURL
  6. ]
  7. )
  8. reporters.insert(directoryTreesReporter, at: 1)

Adding your own custom report

To add your own report you need to make use of the DiagnosticsReporting protocol.

  1. /// An example Custom Reporter.
  2. struct CustomReporter: DiagnosticsReporting {
  3. static func report() -> DiagnosticsChapter {
  4. let diagnostics: [String: String] = [
  5. "Logged In": Session.isLoggedIn.description
  6. ]
  7. return DiagnosticsChapter(title: "My custom report", diagnostics: diagnostics)
  8. }
  9. }

You can then add this report to the creation method:

  1. var reporters = DiagnosticsReporter.DefaultReporter.allReporters
  2. reporters.insert(CustomReporter.self, at: 1)
  3. let report = DiagnosticsReporter.create(using: reporters)

Smart Insights


By default, standard Smart Insights are provided:

  • UpdateAvailableInsight uses your bundle identifier to fetch the latest available app version. An insight will be shown whether an update is available to the user or not.
  • DeviceStorageInsight shows whether the user is out of storage or not

Adding your own custom insights

It’s possible to provide your own custom insights based on the chapters in the report. A common example is to parse the errors and show a smart insight about an occurred error:

  1. struct SmartInsightsProvider: SmartInsightsProviding {
  2. func smartInsights(for chapter: DiagnosticsChapter) -> [SmartInsightProviding] {
  3. guard let html = chapter.diagnostics as? HTML else { return [] }
  4. if html.errorLogs.contains(where: { $0.contains("AppDelegate.ExampleLocalizedError") }) {
  5. return [
  6. SmartInsight(
  7. name: "Localized data",
  8. result: .warn(message: "An error was found regarding missing localisation.")
  9. )
  10. ]
  11. }
  12. return []
  13. }
  14. }

The example project provides the above sample code for you to try out. You can make use of html.errorLogs, .debugLogs, and .systemLogs to quickly access specific logs from the report.

Creating a custom HTML formatter for your report

You can make use of the HTMLFormatting protocol to customize the way the HTML is reported.

Simply pass in the formatter into the DiagnosticsChapter initialiser:

  1. DiagnosticsChapter(title: "UserDefaults", diagnostics: userDefaults, formatter: <#HTMLFormatting.Type#>)

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Installation

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

Manifest File

Add Diagnostics as a package to your Package.swift file and then specify it as a dependency of the Target in which you wish to use it.

  1. import PackageDescription
  2. let package = Package(
  3. name: "MyProject",
  4. platforms: [
  5. .macOS(.v10_15)
  6. ],
  7. dependencies: [
  8. .package(url: "https://github.com/WeTransfer/Diagnostics.git", .upToNextMajor(from: "1.8.0"))
  9. ],
  10. targets: [
  11. .target(
  12. name: "MyProject",
  13. dependencies: ["Diagnostics"]),
  14. .testTarget(
  15. name: "MyProjectTests",
  16. dependencies: ["MyProject"]),
  17. ]
  18. )

Xcode

To add Diagnostics as a dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter the repository URL: https://github.com/WeTransfer/Diagnostics.git.

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

  1. $ brew update
  2. $ brew install carthage

To integrate Diagnostics into your Xcode project using Carthage, specify it in your Cartfile:

  1. github "WeTransfer/Diagnostics" ~> 1.00

Run carthage update to build the framework and drag the built Diagnostics.framework into your Xcode project.

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate Diagnostics into your project manually.

Embedded Framework

  • Open up Terminal, cd into your top-level project directory, and run the following command “if” your project is not initialized as a git repository:

    1. $ git init
  • Add Diagnostics as a git submodule by running the following command:

    1. $ git submodule add https://github.com/WeTransfer/Diagnostics.git
  • Open the new Diagnostics folder, and drag the Diagnostics folder into the Project Navigator of your application’s Xcode project. This will add the SPM package as a local package.

    It should appear nested underneath your application’s blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the “Targets” heading in the sidebar.

  • In the tab bar at the top of that window, open the “General” panel.
  • Click on the + button under the “Embedded Binaries” section.
  • Select Diagnostics.framework.
  • And that’s it!

    The Diagnostics.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.


Release Notes

See CHANGELOG.md for a list of changes.

Authors

This library is created as part of the WeTransfer Hackathon. Process has been reported on Twitter.

Thanks to:

Also, a little shoutout to 1Password for inspiring us to create this library.

License

Diagnostics is available under the MIT license. See the LICENSE file for more info.