├── .github ├── FUNDING.yml └── workflows │ ├── build-multiplatform.yml │ ├── build-documentation.yml │ └── test.yml ├── .spi.yml ├── .gitignore ├── .swiftlint ├── Tests └── OSLogViewerTests │ └── OSLogViewerTests.swift ├── LICENCE.md ├── Package.swift ├── Sources └── OSLogViewer │ ├── OSLogViewer.Colors.swift │ ├── OSLogExtractor.swift │ ├── Localizable.xcstrings │ └── OSLogViewer.swift └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: 0xWDG 2 | -------------------------------------------------------------------------------- /.spi.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | builder: 3 | configs: 4 | - documentation_targets: [OSLogViewer] 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /.swiftlint: -------------------------------------------------------------------------------- 1 | excluded: 2 | - "*resource_bundle_accessor*" # SwiftPM Generated 3 | - .build 4 | 5 | opt_in_rules: 6 | - missing_docs 7 | - empty_count 8 | - empty_string 9 | - toggle_bool 10 | - unused_optional_binding 11 | - valid_ibinspectable 12 | - modifier_order 13 | - first_where 14 | - fatal_error_message 15 | - force_unwrapping -------------------------------------------------------------------------------- /.github/workflows/build-multiplatform.yml: -------------------------------------------------------------------------------- 1 | # .github/workflows/build-multiplatform.yml 2 | 3 | name: Build-Packages 4 | 5 | on: 6 | # Run on pull_request 7 | pull_request: 8 | 9 | # Dispatch if triggered using Github (website) 10 | workflow_dispatch: 11 | 12 | jobs: 13 | Build-Packages: 14 | runs-on: macos-latest 15 | steps: 16 | - name: Build Swift Packages 17 | uses: 0xWDG/build-swift@main 18 | -------------------------------------------------------------------------------- /Tests/OSLogViewerTests/OSLogViewerTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import OSLogViewer 3 | 4 | final class OSLogViewerTests: XCTestCase { 5 | func testExample() throws { 6 | // XCTest Documentation 7 | // https://developer.apple.com/documentation/xctest 8 | 9 | // Defining Test Cases and Test Methods 10 | // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.github/workflows/build-documentation.yml: -------------------------------------------------------------------------------- 1 | # .github/workflows/build-documentation.yml 2 | 3 | name: build-documentation 4 | 5 | on: 6 | # Run on push to main branch 7 | push: 8 | branches: 9 | - main 10 | 11 | # Dispatch if triggered using Github (website) 12 | workflow_dispatch: 13 | 14 | jobs: 15 | Build-documentation: 16 | runs-on: macos-latest 17 | steps: 18 | - name: Build documentation 19 | uses: 0xWDG/build-documentation@main 20 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run Swiftlint + Tests 2 | on: 3 | # Run on push to main branch 4 | push: 5 | # Dispatch if triggered using Github (website) 6 | workflow_dispatch: 7 | 8 | jobs: 9 | swiftlint: 10 | runs-on: macos-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | 14 | - name: SwiftLint 15 | run: | 16 | brew install swiftlint 17 | swiftlint --reporter github-actions-logging --strict 18 | 19 | test_macos: 20 | runs-on: macos-latest 21 | steps: 22 | - uses: actions/checkout@v3 23 | 24 | - name: Swift test 25 | run: swift test 26 | -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Wesley de Groot, email+OSS@WesleydeGroot.nl 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.8.0 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "OSLogViewer", 8 | defaultLocalization: "en", 9 | platforms: [ 10 | .macOS(.v12), 11 | .iOS(.v16), 12 | .watchOS(.v9), 13 | .tvOS(.v16) 14 | ], 15 | products: [ 16 | // Products define the executables and libraries a package produces, making them visible to other packages. 17 | .library( 18 | name: "OSLogViewer", 19 | targets: ["OSLogViewer"] 20 | ) 21 | ], 22 | targets: [ 23 | // Targets are the basic building blocks of a package, defining a module or a test suite. 24 | // Targets can depend on other targets in this package and products from dependencies. 25 | .target( 26 | name: "OSLogViewer", 27 | resources: [ 28 | .process("Localizable.xcstrings") 29 | ] 30 | ), 31 | .testTarget( 32 | name: "OSLogViewerTests", 33 | dependencies: ["OSLogViewer"] 34 | ) 35 | ] 36 | ) 37 | -------------------------------------------------------------------------------- /Sources/OSLogViewer/OSLogViewer.Colors.swift: -------------------------------------------------------------------------------- 1 | // 2 | // OSLogViewer.Colors.swift 3 | // OSLogViewer 4 | // 5 | // Created by Wesley de Groot on 01/06/2024. 6 | // https://wesleydegroot.nl 7 | // 8 | // https://github.com/0xWDG/OSLogViewer 9 | // MIT LICENCE 10 | 11 | #if canImport(SwiftUI) && canImport(OSLog) 12 | import SwiftUI 13 | import OSLog 14 | 15 | #if canImport(UIKit) 16 | import UIKit 17 | #endif 18 | 19 | #if canImport(AppKit) 20 | import AppKit 21 | #endif 22 | 23 | extension OSLogViewer { 24 | /// Generate the background color for the log message 25 | /// - Parameter level: log level 26 | /// - Returns: The appropiate color 27 | func getBackgroundColor(level: OSLogEntryLog.Level) -> Color { 28 | switch level { 29 | case .undefined, .debug, .info, .notice: 30 | getBackgroundColorDefault() 31 | 32 | case .error: 33 | getBackgroundColorError() 34 | 35 | case .fault: 36 | getBackgroundColorFault() 37 | 38 | default: 39 | getBackgroundColorDefault() 40 | } 41 | } 42 | 43 | /// Get the default background color 44 | func getBackgroundColorDefault() -> Color { 45 | #if canImport(UIKit) && !os(tvOS) && !os(watchOS) 46 | Color(uiColor: UIColor.secondarySystemGroupedBackground) 47 | #elseif canImport(AppKit) 48 | Color(nsColor: .init(name: "debug", dynamicProvider: { traits in 49 | if traits.name == .darkAqua || traits.name == .vibrantDark { 50 | return .init(red: 0.11, green: 0.11, blue: 0.12, alpha: 1) 51 | } else { 52 | return .init(red: 1, green: 1, blue: 1, alpha: 1) 53 | } 54 | })) 55 | #else 56 | // Fallback 57 | Color.clear 58 | #endif 59 | } 60 | 61 | /// Get the error background color 62 | func getBackgroundColorError() -> Color { 63 | #if canImport(UIKit) && !os(watchOS) 64 | Color(uiColor: .init(dynamicProvider: { traits in 65 | if traits.userInterfaceStyle == .light { 66 | return .init(red: 1, green: 0.968, blue: 0.898, alpha: 1) 67 | } else { 68 | return .init(red: 0.858, green: 0.717, blue: 0.603, alpha: 0.4) 69 | } 70 | })) 71 | #elseif canImport(AppKit) 72 | Color(nsColor: .init(name: "Error", dynamicProvider: { traits in 73 | if traits.name == .darkAqua || traits.name == .vibrantDark { 74 | return .init(red: 0.858, green: 0.717, blue: 0.603, alpha: 0.4) 75 | } else { 76 | return .init(red: 1, green: 0.968, blue: 0.898, alpha: 1) 77 | } 78 | })) 79 | #else 80 | Color.yellow 81 | #endif 82 | } 83 | 84 | /// Get the fault background color 85 | func getBackgroundColorFault() -> Color { 86 | #if canImport(UIKit) && !os(watchOS) 87 | Color(uiColor: .init(dynamicProvider: { traits in 88 | if traits.userInterfaceStyle == .light { 89 | return .init(red: 0.98, green: 0.90, blue: 0.90, alpha: 1) 90 | } else { 91 | return .init(red: 0.26, green: 0.15, blue: 0.17, alpha: 1) 92 | } 93 | })) 94 | #elseif canImport(AppKit) 95 | Color(nsColor: .init(name: "Fault", dynamicProvider: { traits in 96 | if traits.name == .darkAqua || traits.name == .vibrantDark { 97 | return .init(red: 0.26, green: 0.15, blue: 0.17, alpha: 1) 98 | } else { 99 | return .init(red: 0.98, green: 0.90, blue: 0.90, alpha: 1) 100 | } 101 | })) 102 | #else 103 | Color.red 104 | #endif 105 | } 106 | } 107 | #endif 108 | -------------------------------------------------------------------------------- /Sources/OSLogViewer/OSLogExtractor.swift: -------------------------------------------------------------------------------- 1 | // 2 | // OSLogExtractor.swift 3 | // OSLogViewer 4 | // 5 | // Created by Wesley de Groot on 19/11/2024. 6 | // 7 | // https://github.com/0xWDG/OSLogViewer 8 | // MIT LICENCE 9 | 10 | import Foundation 11 | 12 | #if canImport(OSLog) 13 | import OSLog 14 | #endif 15 | 16 | /// OSLogExtractor is made to extract your apps OS_Log history, 17 | public class OSLogExtractor { 18 | /// Identifier 19 | public let id = UUID() 20 | 21 | /// Subsystem to read logs from 22 | public var subsystem: String 23 | 24 | /// From which date preriod 25 | public var since: Date 26 | 27 | /// OSLogExtractor is made to extract your apps OS_Log history, 28 | /// 29 | /// - Parameters: 30 | /// - subsystem: which subsystem should be read 31 | /// - since: from which time (standard 1hr) 32 | public init( 33 | subsystem: String = Bundle.main.bundleIdentifier ?? "", 34 | since: Date = Date().addingTimeInterval(-3600) 35 | ) { 36 | self.subsystem = subsystem 37 | self.since = since 38 | } 39 | 40 | /// Export OSLog as string. 41 | public func export() async -> String { 42 | #if canImport(OSLog) 43 | let logMessages = await getLog() 44 | 45 | let appName: String = { 46 | if let displayName: String = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String { 47 | return displayName 48 | } else if let name: String = Bundle.main.infoDictionary?["CFBundleName"] as? String { 49 | return name 50 | } 51 | return "this application" 52 | }() 53 | 54 | return [ 55 | "This is the OSLog archive for \(appName).\r\n", 56 | "Generated on \(Date().formatted())\r\n", 57 | "Generator https://github.com/0xWDG/OSLogViewer\r\n\r\n", 58 | logMessages.map { 59 | "\($0.composedMessage)\r\n" + 60 | getLogLevelEmoji(level: $0.level) + 61 | " \($0.date.formatted()) 🏛️ \($0.sender) ⚙️ \($0.subsystem) 🌐 \($0.category)" 62 | } 63 | .joined(separator: "\r\n\r\n") 64 | ] 65 | .joined() 66 | #else 67 | return "" 68 | #endif 69 | } 70 | 71 | #if canImport(OSLog) 72 | /// Generate an emoji for the current log level 73 | /// - Parameter level: log level 74 | /// - Returns: Emoji 75 | func getLogLevelEmoji(level: OSLogEntryLog.Level) -> String { 76 | switch level { 77 | case .undefined, .notice: 78 | "🔔" 79 | case .debug: 80 | "🩺" 81 | case .info: 82 | "ℹ️" 83 | case .error: 84 | "❗" 85 | case .fault: 86 | "‼️" 87 | default: 88 | "🔔" 89 | } 90 | } 91 | 92 | /// Get the logs 93 | public func getLog() async -> [OSLogEntryLog] { 94 | do { 95 | /// Initialize logstore for the current proces 96 | let logStore = try OSLogStore(scope: .currentProcessIdentifier) 97 | 98 | /// Fetch all logs since a specific date 99 | let sinceDate = logStore.position(date: self.since) 100 | 101 | /// Predicate (filter) all results to have the subsystem starting with the given subsystem 102 | let predicate = NSPredicate( 103 | format: "subsystem BEGINSWITH %@", 104 | self.subsystem 105 | ) 106 | 107 | /// Get all logs from the log store 108 | return try logStore.getEntries( 109 | at: sinceDate, 110 | matching: predicate 111 | ).compactMap { 112 | // Remap from `AnySequence` to type `[OSLogEntryLog]` 113 | $0 as? OSLogEntryLog 114 | } 115 | 116 | } catch { 117 | // We fail to get the results, add this to the log. 118 | os_log(.fault, "Something went wrong %@", error as NSError) 119 | 120 | return [] 121 | } 122 | } 123 | #endif 124 | } 125 | -------------------------------------------------------------------------------- /Sources/OSLogViewer/Localizable.xcstrings: -------------------------------------------------------------------------------- 1 | { 2 | "sourceLanguage" : "en", 3 | "strings" : { 4 | "" : { 5 | "shouldTranslate" : false 6 | }, 7 | " " : { 8 | "shouldTranslate" : false 9 | }, 10 | " " : { 11 | "shouldTranslate" : false 12 | }, 13 | "%@ %@" : { 14 | "localizations" : { 15 | "en" : { 16 | "stringUnit" : { 17 | "state" : "new", 18 | "value" : "%1$@ %2$@" 19 | } 20 | } 21 | }, 22 | "shouldTranslate" : false 23 | }, 24 | "%@ %@ " : { 25 | "localizations" : { 26 | "en" : { 27 | "stringUnit" : { 28 | "state" : "new", 29 | "value" : "%1$@ %2$@ " 30 | } 31 | } 32 | }, 33 | "shouldTranslate" : false 34 | }, 35 | "Collecting logs..." : { 36 | "localizations" : { 37 | "de" : { 38 | "stringUnit" : { 39 | "state" : "translated", 40 | "value" : "Protokolle sammeln..." 41 | } 42 | }, 43 | "fr" : { 44 | "stringUnit" : { 45 | "state" : "translated", 46 | "value" : "Collecte des journaux..." 47 | } 48 | }, 49 | "nl" : { 50 | "stringUnit" : { 51 | "state" : "translated", 52 | "value" : "Logboeken verzamelen..." 53 | } 54 | } 55 | } 56 | }, 57 | "Debug" : { 58 | "shouldTranslate" : false 59 | }, 60 | "Default" : { 61 | "shouldTranslate" : false 62 | }, 63 | "Error" : { 64 | "shouldTranslate" : false 65 | }, 66 | "Fault" : { 67 | "shouldTranslate" : false 68 | }, 69 | "for subsystem \"%@\"." : { 70 | "localizations" : { 71 | "de" : { 72 | "stringUnit" : { 73 | "state" : "translated", 74 | "value" : "Für Subsystem “%@”." 75 | } 76 | }, 77 | "fr" : { 78 | "stringUnit" : { 79 | "state" : "translated", 80 | "value" : "Pour le sous-système “%@”." 81 | } 82 | }, 83 | "nl" : { 84 | "stringUnit" : { 85 | "state" : "translated", 86 | "value" : "voor subsysteem “%@”." 87 | } 88 | } 89 | } 90 | }, 91 | "Information" : { 92 | "shouldTranslate" : false 93 | }, 94 | "No results found" : { 95 | "localizations" : { 96 | "de" : { 97 | "stringUnit" : { 98 | "state" : "translated", 99 | "value" : "Keine Ergebnisse gefunden" 100 | } 101 | }, 102 | "fr" : { 103 | "stringUnit" : { 104 | "state" : "translated", 105 | "value" : "Aucun résultat trouvé" 106 | } 107 | }, 108 | "nl" : { 109 | "stringUnit" : { 110 | "state" : "translated", 111 | "value" : "Geen resultaten gevonden" 112 | } 113 | } 114 | } 115 | }, 116 | "No results found for subsystem \"%@\"." : { 117 | "localizations" : { 118 | "de" : { 119 | "stringUnit" : { 120 | "state" : "translated", 121 | "value" : "Keine Ergebnisse für das Subsystem “%@” gefunden." 122 | } 123 | }, 124 | "fr" : { 125 | "stringUnit" : { 126 | "state" : "translated", 127 | "value" : "Aucun résultat trouvé pour le sous-système “%@”." 128 | } 129 | }, 130 | "nl" : { 131 | "stringUnit" : { 132 | "state" : "translated", 133 | "value" : "Geen resultaten gevonden voor subsysteem “%@”." 134 | } 135 | } 136 | } 137 | }, 138 | "Notice" : { 139 | "shouldTranslate" : false 140 | }, 141 | "OSLog viewer" : { 142 | "localizations" : { 143 | "de" : { 144 | "stringUnit" : { 145 | "state" : "translated", 146 | "value" : "OSLog-Zuschauer" 147 | } 148 | }, 149 | "fr" : { 150 | "stringUnit" : { 151 | "state" : "translated", 152 | "value" : "Visionneuse OSLog" 153 | } 154 | }, 155 | "nl" : { 156 | "stringUnit" : { 157 | "state" : "translated", 158 | "value" : "OSLog bekijken" 159 | } 160 | } 161 | } 162 | } 163 | }, 164 | "version" : "1.0" 165 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OSLogViewer 2 | 3 | OSLogViewer is made for viewing your apps OS_Log history, it is a SwiftUI view which can be used in your app to view and export your logs. 4 | 5 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2F0xWDG%2FOSLogViewer%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/0xWDG/OSLogViewer) 6 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2F0xWDG%2FOSLogViewer%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/0xWDG/OSLogViewer) 7 | [![Swift Package Manager](https://img.shields.io/badge/SPM-compatible-brightgreen.svg)](https://swift.org/package-manager) 8 | ![License](https://img.shields.io/github/license/0xWDG/OSLogViewer) 9 | 10 | _Key features:_ 11 | 12 | - View your apps OS_Log history 13 | - Export logs 14 | 15 | ## Requirements 16 | 17 | - Swift 5.8+ (Xcode 14.3+) 18 | - iOS 16+, macOS 12+, watchOS 9+, tvOS 16+, visionOS 1+ 19 | 20 | ## Installation 21 | 22 | Install using Swift Package Manager 23 | 24 | ```swift 25 | dependencies: [ 26 | .package(url: "https://github.com/0xWDG/OSLogViewer.git", branch: "main"), 27 | ], 28 | targets: [ 29 | .target(name: "MyTarget", dependencies: [ 30 | .product(name: "OSLogViewer", package: "OSLogViewer"), 31 | ]), 32 | ] 33 | ``` 34 | 35 | And import it: 36 | 37 | ```swift 38 | import OSLogViewer 39 | ``` 40 | 41 | ## Usage 42 | 43 | ### Quick usage 44 | 45 | ```swift 46 | import OSLogViewer 47 | 48 | NavigationLink { 49 | // Default configuration 50 | // uses your app's bundle identifier as subsystem 51 | // and shows all logs from the last hour. 52 | OSLogViewer() 53 | } label: { 54 | Text("View logs") 55 | } 56 | ``` 57 | 58 | ### Custom usage 59 | 60 | custom subsystem 61 | 62 | ```swift 63 | import OSLogViewer 64 | 65 | OSLogViewer( 66 | subsystem: "nl.wesleydegroot.exampleapp", 67 | ) 68 | ``` 69 | 70 | custom time 71 | 72 | ```swift 73 | import OSLogViewer 74 | 75 | OSLogViewer( 76 | since: Date().addingTimeInterval(-7200) // 2 hours 77 | ) 78 | ``` 79 | 80 | custom subsystem and time 81 | 82 | ```swift 83 | import OSLogViewer 84 | 85 | OSLogViewer( 86 | subsystem: "nl.wesleydegroot.exampleapp", 87 | since: Date().addingTimeInterval(-7200) // 2 hours 88 | ) 89 | ``` 90 | 91 | ## Screenshots 92 | 93 | 94 | 95 | ## Export example 96 | 97 | ```plaintext 98 | This is the OSLog archive for exampleapp 99 | Generated on 2/6/2024, 11:53 100 | Generator https://github.com/0xWDG/OSLogViewer 101 | 102 | Info message 103 | ℹ️ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory 104 | 105 | Error message 106 | ❗ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory 107 | 108 | Error message 109 | ❗ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory 110 | 111 | Critical message 112 | ‼️ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory 113 | 114 | Log message 115 | 🔔 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory 116 | 117 | Log message 118 | 🔔 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory 119 | ``` 120 | 121 | ## Changelog 122 | 123 | - 1.0.0 124 | - Initial release 125 | - 1.0.1 126 | - Improved support for dark mode. 127 | - Colors are more similar to Xcode's console. 128 | - Added support for exporting logs. 129 | - 1.0.2 & 1.0.3 130 | - Fix: building on macOS < 14. 131 | - Improved support for dark mode. 132 | - Colors are more similar to Xcode's console. 133 | - Added support for exporting logs. 134 | - 1.0.4 135 | - Fix: building on all platforms other than iOS. 136 | - Improved support for dark mode. 137 | - Colors are more similar to Xcode's console. 138 | - Added support for exporting logs. 139 | - Added online documentation https://0xwdg.github.io/OSLogViewer/ 140 | - 1.0.5 141 | - Improve text alignment and word-breaks in the details 142 | - 1.0.7 143 | - Multi platform support 144 | - 1.0.8 145 | - Fix hang on loading data 146 | - 1.1.0 147 | - Added OSLogExtractor 148 | - 1.1.1 149 | - Fixes for Linux targets 150 | - 1.1.2 151 | - Fix logs on Mac displaying incorrectly by @infinitepower18 in #2 152 | - 1.1.3 153 | - Make datarace safe 154 | 155 | ## Contact 156 | 157 | 🦋 [@0xWDG](https://bsky.app/profile/0xWDG.bsky.social) 158 | 🐘 [mastodon.social/@0xWDG](https://mastodon.social/@0xWDG) 159 | 🐦 [@0xWDG](https://x.com/0xWDG) 160 | 🧵 [@0xWDG](https://www.threads.net/@0xWDG) 161 | 🌐 [wesleydegroot.nl](https://wesleydegroot.nl) 162 | 🤖 [Discord](https://discordapp.com/users/918438083861573692) 163 | 164 | Interested learning more about Swift? [Check out my blog](https://wesleydegroot.nl/blog/). 165 | -------------------------------------------------------------------------------- /Sources/OSLogViewer/OSLogViewer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // OSLogViewer.swift 3 | // OSLogViewer 4 | // 5 | // Created by Wesley de Groot on 01/06/2024. 6 | // https://wesleydegroot.nl 7 | // 8 | // https://github.com/0xWDG/OSLogViewer 9 | // MIT LICENCE 10 | 11 | #if canImport(SwiftUI) && canImport(OSLog) 12 | import SwiftUI 13 | @preconcurrency import OSLog 14 | 15 | /// OSLogViewer is made for viewing your apps OS_Log history, 16 | /// it is a SwiftUI view which can be used in your app to view and export your logs. 17 | public struct OSLogViewer: View { 18 | /// Subsystem to read logs from 19 | public var subsystem: String 20 | 21 | /// From which date preriod 22 | public var since: Date 23 | 24 | /// OSLogViewer is made for viewing your apps OS_Log history, 25 | /// it is a SwiftUI view which can be used in your app to view and export your logs. 26 | /// 27 | /// - Parameters: 28 | /// - subsystem: which subsystem should be read 29 | /// - since: from which time (standard 1hr) 30 | public init( 31 | subsystem: String = Bundle.main.bundleIdentifier ?? "", 32 | since: Date = Date().addingTimeInterval(-3600) 33 | ) { 34 | self.subsystem = subsystem 35 | self.since = since 36 | } 37 | 38 | @State 39 | /// This variable saves the log messages 40 | private var logMessages: [OSLogEntryLog] = [] 41 | 42 | @State 43 | /// This variable saves the current state 44 | private var finishedCollecting: Bool = false 45 | 46 | @State 47 | /// This variable saves the export sheet state 48 | private var exportSheet: Bool = false 49 | 50 | /// The body of the view 51 | public var body: some View { 52 | VStack { 53 | List { 54 | ForEach(logMessages, id: \.self) { entry in 55 | VStack { 56 | // Actual log message 57 | Text(entry.composedMessage) 58 | .frame(maxWidth: .infinity, alignment: .leading) 59 | 60 | // Details (time, framework, subsystem, category 61 | detailsBuilder(for: entry) 62 | .frame(maxWidth: .infinity, alignment: .leading) 63 | .fixedSize(horizontal: false, vertical: true) 64 | .font(.footnote) 65 | } 66 | .listRowBackground(getBackgroundColor(level: entry.level)) 67 | } 68 | } 69 | } 70 | .modifier(OSLogModifier()) 71 | .toolbar { 72 | #if os(macOS) 73 | if #available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, *) { 74 | ShareLink( 75 | items: export() 76 | ) 77 | .disabled(!finishedCollecting) 78 | } 79 | #elseif !os(tvOS) && !os(watchOS) 80 | ToolbarItem(placement: .navigationBarTrailing) { 81 | if #available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, *) { 82 | ShareLink( 83 | items: export() 84 | ) 85 | .disabled(!finishedCollecting) 86 | } 87 | } 88 | #else 89 | EmptyView() 90 | #endif 91 | } 92 | .overlay { 93 | if logMessages.isEmpty { 94 | if !finishedCollecting { 95 | if #available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, *) { 96 | ContentUnavailableView("Collecting logs...", systemImage: "hourglass") 97 | } else { 98 | VStack { 99 | Image(systemName: "hourglass") 100 | Text("Collecting logs...") 101 | } 102 | } 103 | } else { 104 | if #available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, *) { 105 | ContentUnavailableView( 106 | "No results found", 107 | systemImage: "magnifyingglass", 108 | description: Text("for subsystem \"\(subsystem)\".") 109 | ) 110 | } else { 111 | VStack { 112 | Image(systemName: "magnifyingglass") 113 | Text("No results found for subsystem \"\(subsystem)\".") 114 | } 115 | } 116 | } 117 | } 118 | } 119 | .refreshable { 120 | await getLog() 121 | } 122 | .onAppear { 123 | Task { 124 | await getLog() 125 | } 126 | } 127 | } 128 | 129 | func export() -> [String] { 130 | let appName: String = { 131 | if let displayName: String = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String { 132 | return displayName 133 | } else if let name: String = Bundle.main.infoDictionary?["CFBundleName"] as? String { 134 | return name 135 | } 136 | return "this application" 137 | }() 138 | 139 | return [ 140 | [ 141 | "This is the OSLog archive for \(appName).\r\n", 142 | "Generated on \(Date().formatted())\r\n", 143 | "Generator https://github.com/0xWDG/OSLogViewer\r\n\r\n", 144 | logMessages.map { 145 | "\($0.composedMessage)\r\n" + 146 | getLogLevelEmoji(level: $0.level) + 147 | " \($0.date.formatted()) 🏛️ \($0.sender) ⚙️ \($0.subsystem) 🌐 \($0.category)" 148 | } 149 | .joined(separator: "\r\n\r\n") 150 | ] 151 | .joined() 152 | ] 153 | } 154 | 155 | @ViewBuilder 156 | /// Build details (time, framework, subsystem, category), for the footnote row 157 | /// - Parameter entry: log entry 158 | /// - Returns: Text containing icons and details. 159 | func detailsBuilder(for entry: OSLogEntryLog) -> Text { 160 | // No accebility labels are used, 161 | // If added it will _always_ file to check in compile time. 162 | getLogLevelIcon(level: entry.level) + 163 | // Non breaking space 164 | Text("\u{00a0}") + 165 | // Date 166 | Text(entry.date, style: .time) + 167 | // (Breaking) space 168 | Text(" ") + 169 | // 􀤨 Framework (aka sender) 170 | Text("\(Image(systemName: "building.columns"))\u{00a0}\(entry.sender) ") + 171 | // 􀥎 Subsystem 172 | Text("\(Image(systemName: "gearshape.2"))\u{00a0}\(entry.subsystem) ") + 173 | // 􀦲 Category 174 | Text("\(Image(systemName: "square.grid.3x3"))\u{00a0}\(entry.category)") 175 | } 176 | 177 | /// Generate an emoji for the current log level 178 | /// - Parameter level: log level 179 | /// - Returns: Emoji 180 | func getLogLevelEmoji(level: OSLogEntryLog.Level) -> String { 181 | switch level { 182 | case .undefined, .notice: 183 | "🔔" 184 | case .debug: 185 | "🩺" 186 | case .info: 187 | "ℹ️" 188 | case .error: 189 | "❗" 190 | case .fault: 191 | "‼️" 192 | default: 193 | "🔔" 194 | } 195 | } 196 | 197 | /// Generate an icon for the current log level 198 | /// - Parameter level: log level 199 | /// - Returns: SF Icon as Text 200 | func getLogLevelIcon(level: OSLogEntryLog.Level) -> Text { 201 | switch level { 202 | case .undefined, .notice: 203 | // 􀼸 204 | Text(Image(systemName: "bell.square.fill")) 205 | .accessibilityLabel("Notice") 206 | case .debug: 207 | // 􀝾 208 | Text(Image(systemName: "stethoscope")) 209 | .accessibilityLabel("Debug") 210 | case .info: 211 | // 􁊇 212 | Text(Image(systemName: "info.square")) 213 | .accessibilityLabel("Information") 214 | case .error: 215 | // 􀢒 216 | Text(Image(systemName: "exclamationmark.2")) 217 | .accessibilityLabel("Error") 218 | case .fault: 219 | // 􀣴 220 | Text(Image(systemName: "exclamationmark.3")) 221 | .accessibilityLabel("Fault") 222 | default: 223 | // 􀼸 224 | Text(Image(systemName: "bell.square.fill")) 225 | .accessibilityLabel("Default") 226 | } 227 | } 228 | 229 | /// Get the logs 230 | public func getLog() async { 231 | // We start collecting 232 | finishedCollecting = false 233 | 234 | DispatchQueue.global(qos: .background).async { 235 | do { 236 | /// Initialize logstore for the current proces 237 | let logStore = try OSLogStore(scope: .currentProcessIdentifier) 238 | 239 | /// Fetch all logs since a specific date 240 | let sinceDate = logStore.position(date: since) 241 | 242 | /// Predicate (filter) all results to have the subsystem starting with the given subsystem 243 | let predicate = NSPredicate(format: "subsystem BEGINSWITH %@", subsystem) 244 | 245 | /// Get all logs from the log store 246 | let allEntries = try logStore.getEntries( 247 | at: sinceDate, 248 | matching: predicate 249 | ).compactMap { $0 as? OSLogEntryLog } 250 | 251 | DispatchQueue.main.async { 252 | /// Remap from `AnySequence` to type `[OSLogEntryLog]` 253 | logMessages = allEntries 254 | } 255 | } catch { 256 | // We fail to get the results, add this to the log. 257 | os_log(.fault, "Something went wrong %@", error as NSError) 258 | } 259 | 260 | DispatchQueue.main.async { 261 | // We've finished collecting 262 | finishedCollecting = true 263 | } 264 | } 265 | } 266 | 267 | struct OSLogModifier: ViewModifier { 268 | func body(content: Content) -> some View { 269 | #if os(macOS) 270 | content 271 | #else 272 | content 273 | .navigationViewStyle(.stack) // iPad 274 | #if !os(tvOS) && !os(watchOS) 275 | .navigationBarTitle("OSLog viewer", displayMode: .inline) 276 | #endif 277 | #endif 278 | } 279 | } 280 | } 281 | 282 | struct OSLogViewer_Previews: PreviewProvider { 283 | static var previews: some View { 284 | OSLogViewer() 285 | } 286 | } 287 | #endif 288 | --------------------------------------------------------------------------------