From 9b2572ba41544870ac55a6dfbbe72c808a3f54ba Mon Sep 17 00:00:00 2001 From: Angelo Stavrow Date: Sat, 25 Jun 2022 11:17:44 -0400 Subject: [PATCH] Refactor logging into reuseable methods --- Shared/LocalStorageManager.swift | 52 +++++++------------ Shared/Logging/Logging.swift | 40 ++++++++++++++ .../PostCollection/CollectionListModel.swift | 25 +++------ .../project.pbxproj | 16 ++++++ 4 files changed, 81 insertions(+), 52 deletions(-) create mode 100644 Shared/Logging/Logging.swift diff --git a/Shared/LocalStorageManager.swift b/Shared/LocalStorageManager.swift index 759bbf0..2cf57ca 100644 --- a/Shared/LocalStorageManager.swift +++ b/Shared/LocalStorageManager.swift @@ -1,5 +1,4 @@ import CoreData -import os #if os(iOS) import UIKit @@ -9,6 +8,8 @@ import AppKit final class LocalStorageManager { + private let logger = Logging(for: String(describing: LocalStorageManager.self)) + public static var standard = LocalStorageManager() public let container: NSPersistentContainer private let containerName = "LocalStorageModel" @@ -22,11 +23,11 @@ final class LocalStorageManager { func saveContext() { if container.viewContext.hasChanges { do { - Self.logger.info("Saving context to local store started...") + logger.log("Saving context to local store started...") try container.viewContext.save() - Self.logger.notice("Context saved to local store.") + logger.log("Context saved to local store.") } catch { - logCrashAndSetFlag(error: LocalStoreError.couldNotSaveContext) + logger.logCrashAndSetFlag(error: LocalStoreError.couldNotSaveContext) } } } @@ -36,11 +37,11 @@ final class LocalStorageManager { let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) do { - Self.logger.info("Purging user collections from local store...") + logger.log("Purging user collections from local store...") try container.viewContext.executeAndMergeChanges(using: deleteRequest) - Self.logger.notice("User collections purged from local store.") + logger.log("User collections purged from local store.") } catch { - Self.logger.error("\(LocalStoreError.couldNotPurgeCollections.localizedDescription)") + logger.log("\(LocalStoreError.couldNotPurgeCollections.localizedDescription)", level: .error) throw LocalStoreError.couldNotPurgeCollections } } @@ -66,11 +67,11 @@ private extension LocalStorageManager { } container.loadPersistentStores { _, error in - Self.logger.info("Loading local store...") + self.logger.log("Loading local store...") if let error = error { - self.logCrashAndSetFlag(error: LocalStoreError.couldNotLoadStore(error.localizedDescription)) + self.logger.logCrashAndSetFlag(error: LocalStoreError.couldNotLoadStore(error.localizedDescription)) } - Self.logger.notice("Loaded local store.") + self.logger.log("Loaded local store.") } migrateStore(for: container) container.viewContext.automaticallyMergesChangesFromParent = true @@ -91,23 +92,25 @@ private extension LocalStorageManager { // Attempt to migrate the old store over to the shared store URL. do { - Self.logger.info("Migrating local store to shared store...") + self.logger.log("Migrating local store to shared store...") try coordinator.migratePersistentStore(oldStore, to: sharedStoreURL, options: nil, withType: NSSQLiteStoreType) - Self.logger.notice("Migrated local store to shared store.") + self.logger.log("Migrated local store to shared store.") } catch { - logCrashAndSetFlag(error: LocalStoreError.couldNotMigrateStore(error.localizedDescription)) + logger.logCrashAndSetFlag(error: LocalStoreError.couldNotMigrateStore(error.localizedDescription)) } // Attempt to delete the old store. do { - Self.logger.info("Deleting migrated local store...") + logger.log("Deleting migrated local store...") try FileManager.default.removeItem(at: oldStoreURL) - Self.logger.notice("Deleted migrated local store.") + logger.log("Deleted migrated local store.") } catch { - logCrashAndSetFlag(error: LocalStoreError.couldNotDeleteStoreAfterMigration(error.localizedDescription)) + logger.logCrashAndSetFlag( + error: LocalStoreError.couldNotDeleteStoreAfterMigration(error.localizedDescription) + ) } } @@ -133,20 +136,3 @@ private extension LocalStorageManager { } } - -private extension LocalStorageManager { - - private static let logger = Logger( - subsystem: Bundle.main.bundleIdentifier!, - category: String(describing: LocalStorageManager.self) - ) - - private func logCrashAndSetFlag(error: Error) { - let errorDescription = error.localizedDescription - UserDefaults.shared.set(true, forKey: WFDefaults.didHaveFatalError) - UserDefaults.shared.set(errorDescription, forKey: WFDefaults.fatalErrorDescription) - Self.logger.critical("\(errorDescription)") - fatalError(errorDescription) - } - -} diff --git a/Shared/Logging/Logging.swift b/Shared/Logging/Logging.swift new file mode 100644 index 0000000..b1e88a0 --- /dev/null +++ b/Shared/Logging/Logging.swift @@ -0,0 +1,40 @@ +// +// Logging.swift +// WriteFreely-MultiPlatform +// +// Created by Angelo Stavrow on 2022-06-25. +// + +import Foundation +import os + +final class Logging { + + private let logger: Logger + private let subsystem = Bundle.main.bundleIdentifier! + + init(for category: String) { + self.logger = Logger(subsystem: subsystem, category: category) + } + + func log( + _ message: String, + withSensitiveInfo privateInfo: String? = nil, + level: OSLogType = .default + ) { + if let privateInfo = privateInfo { + logger.log(level: level, "\(message): \(privateInfo, privacy: .sensitive)") + } else { + logger.log(level: level, "\(message)") + } + } + + func logCrashAndSetFlag(error: Error) { + let errorDescription = error.localizedDescription + UserDefaults.shared.set(true, forKey: WFDefaults.didHaveFatalError) + UserDefaults.shared.set(errorDescription, forKey: WFDefaults.fatalErrorDescription) + logger.critical("\(errorDescription)") + fatalError(errorDescription) + } + +} diff --git a/Shared/PostCollection/CollectionListModel.swift b/Shared/PostCollection/CollectionListModel.swift index d1cd2bb..ca2571d 100644 --- a/Shared/PostCollection/CollectionListModel.swift +++ b/Shared/PostCollection/CollectionListModel.swift @@ -1,8 +1,10 @@ import SwiftUI import CoreData -import os class CollectionListModel: NSObject, ObservableObject { + + private let logger = Logging(for: String(describing: CollectionListModel.self)) + @Published var list: [WFACollection] = [] private let collectionsController: NSFetchedResultsController @@ -17,12 +19,12 @@ class CollectionListModel: NSObject, ObservableObject { collectionsController.delegate = self do { - Self.logger.info("Fetching collections from local store...") + logger.log("Fetching collections from local store...") try collectionsController.performFetch() list = collectionsController.fetchedObjects ?? [] - Self.logger.notice("Fetched collections from local store.") + logger.log("Fetched collections from local store.") } catch { - logCrashAndSetFlag(error: LocalStoreError.couldNotFetchCollections) + logger.logCrashAndSetFlag(error: LocalStoreError.couldNotFetchCollections) } } } @@ -34,21 +36,6 @@ extension CollectionListModel: NSFetchedResultsControllerDelegate { } } -extension CollectionListModel { - private static let logger = Logger( - subsystem: Bundle.main.bundleIdentifier!, - category: String(describing: CollectionListModel.self) - ) - - private func logCrashAndSetFlag(error: Error) { - let errorDescription = error.localizedDescription - UserDefaults.shared.set(true, forKey: WFDefaults.didHaveFatalError) - UserDefaults.shared.set(errorDescription, forKey: WFDefaults.fatalErrorDescription) - Self.logger.critical("\(errorDescription)") - fatalError(errorDescription) - } -} - extension WFACollection { static var collectionsFetchRequest: NSFetchRequest { let request: NSFetchRequest = WFACollection.createFetchRequest() diff --git a/WriteFreely-MultiPlatform.xcodeproj/project.pbxproj b/WriteFreely-MultiPlatform.xcodeproj/project.pbxproj index c2f33e2..71cfc1a 100644 --- a/WriteFreely-MultiPlatform.xcodeproj/project.pbxproj +++ b/WriteFreely-MultiPlatform.xcodeproj/project.pbxproj @@ -7,6 +7,9 @@ objects = { /* Begin PBXBuildFile section */ + 17027E25286741B90062EB29 /* Logging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17027E24286741B80062EB29 /* Logging.swift */; }; + 17027E26286741B90062EB29 /* Logging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17027E24286741B80062EB29 /* Logging.swift */; }; + 17027E27286757650062EB29 /* Logging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17027E24286741B80062EB29 /* Logging.swift */; }; 170A7EC126F5186A00F1CBD4 /* CollectionListModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 170A7EC026F5186A00F1CBD4 /* CollectionListModel.swift */; }; 170A7EC226F5186A00F1CBD4 /* CollectionListModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 170A7EC026F5186A00F1CBD4 /* CollectionListModel.swift */; }; 170DFA34251BBC44001D82A0 /* PostEditorModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 170DFA33251BBC44001D82A0 /* PostEditorModel.swift */; }; @@ -178,6 +181,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 17027E24286741B80062EB29 /* Logging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logging.swift; sourceTree = ""; }; 1709ADDF251B9A110053AF79 /* EditorLaunchingPolicy.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = EditorLaunchingPolicy.md; sourceTree = ""; }; 170A7EC026F5186A00F1CBD4 /* CollectionListModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionListModel.swift; sourceTree = ""; }; 170DFA33251BBC44001D82A0 /* PostEditorModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PostEditorModel.swift; sourceTree = ""; }; @@ -315,6 +319,14 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 17027E23286741910062EB29 /* Logging */ = { + isa = PBXGroup; + children = ( + 17027E24286741B80062EB29 /* Logging.swift */, + ); + path = Logging; + sourceTree = ""; + }; 1709ADDE251B99D40053AF79 /* Technotes */ = { isa = PBXGroup; children = ( @@ -494,6 +506,7 @@ 17DF32D024C8B75C00BCE2E3 /* Account */, 1756AE7F24CB841200FD7257 /* Extensions */, 17275264280997BF003D0A6A /* ErrorHandling */, + 17027E23286741910062EB29 /* Logging */, 1762DCB124EB07680019C4EB /* Models */, 17DF32CC24C8B72300BCE2E3 /* Navigation */, 1739B8D324EAFAB700DA7421 /* PostEditor */, @@ -883,6 +896,7 @@ 172E10202735C64600061372 /* WFACollection+CoreDataClass.swift in Sources */, 172E10222735C64600061372 /* WFAPost+CoreDataProperties.swift in Sources */, 172E101D2735C5AB00061372 /* LocalStorageModel.xcdatamodeld in Sources */, + 17027E27286757650062EB29 /* Logging.swift in Sources */, 17836C14273EFB870047AF61 /* UserDefaults+Extensions.swift in Sources */, 172E10242735C72500061372 /* PreferencesModel.swift in Sources */, 172E10172735C2DF00061372 /* EnvironmentValues+Extensions.swift in Sources */, @@ -933,6 +947,7 @@ 1756DC0124FEE18400207AB8 /* WFACollection+CoreDataClass.swift in Sources */, 17DF32AA24C87D3500BCE2E3 /* WriteFreely_MultiPlatformApp.swift in Sources */, 17120DA724E19D11002B9F6C /* SettingsView.swift in Sources */, + 17027E25286741B90062EB29 /* Logging.swift in Sources */, 1727526628099802003D0A6A /* ErrorConstants.swift in Sources */, 1756DC0324FEE18400207AB8 /* WFACollection+CoreDataProperties.swift in Sources */, 17120DA224E1985C002B9F6C /* AccountModel.swift in Sources */, @@ -966,6 +981,7 @@ 17120DAD24E1B99F002B9F6C /* AccountLoginView.swift in Sources */, 17D4926727947D780035BD7E /* MacUpdatesViewModel.swift in Sources */, 17466626256C0D0600629997 /* MacEditorTextView.swift in Sources */, + 17027E26286741B90062EB29 /* Logging.swift in Sources */, 170A7EC226F5186A00F1CBD4 /* CollectionListModel.swift in Sources */, 1727526B2809991A003D0A6A /* ErrorHandling.swift in Sources */, 17E5DF8A2543610700DCDC9B /* PostTextEditingView.swift in Sources */,