diff --git a/Sources/KukaiCoreSwift/Clients/BetterCallDevClient.swift b/Sources/KukaiCoreSwift/Clients/BetterCallDevClient.swift index 7e3dc99d..726d12cd 100644 --- a/Sources/KukaiCoreSwift/Clients/BetterCallDevClient.swift +++ b/Sources/KukaiCoreSwift/Clients/BetterCallDevClient.swift @@ -71,7 +71,7 @@ public class BetterCallDevClient { completion(nil, nil) case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Parse error: %@", "\(error)") + Logger.kukaiCoreSwift.error("Parse error: \(error)") completion(nil, KukaiError.internalApplicationError(error: error)) } } diff --git a/Sources/KukaiCoreSwift/Clients/TezosNodeClient.swift b/Sources/KukaiCoreSwift/Clients/TezosNodeClient.swift index e5cb43b4..36bf252f 100644 --- a/Sources/KukaiCoreSwift/Clients/TezosNodeClient.swift +++ b/Sources/KukaiCoreSwift/Clients/TezosNodeClient.swift @@ -137,7 +137,7 @@ public class TezosNodeClient { self?.feeEstimatorService.estimate(operations: operations, operationMetadata: metadata, constants: constants, walletAddress: walletAddress, base58EncodedPublicKey: base58EncodedPublicKey, completion: completion) case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Unable to fetch metadata: %@", "\(error)") + Logger.kukaiCoreSwift.error("Unable to fetch metadata: \(error)") completion(Result.failure(error)) } } @@ -160,7 +160,7 @@ public class TezosNodeClient { self?.send(operationPayload: operationPayload, operationMetadata: metadata, withWallet: wallet, completion: completion) case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Unable to fetch metadata: %@", "\(error)") + Logger.kukaiCoreSwift.error("Unable to fetch metadata: \(error)") completion(Result.failure(error)) } } @@ -317,7 +317,7 @@ public class TezosNodeClient { dispatchGroup.enter() dexterQueriesQueue.async { [weak self] in guard let url = self?.config.primaryNodeURL else { - os_log(.default, log: .kukaiCoreSwift, "Invalid server url: %@", self?.config.primaryNodeURL.absoluteString ?? "nil") + Logger.kukaiCoreSwift.info("Invalid server url: \(self?.config.primaryNodeURL.absoluteString ?? "nil")") completion(false, KukaiError.internalApplicationError(error: NetworkService.NetworkError.invalidURL)) return } @@ -338,7 +338,7 @@ public class TezosNodeClient { dispatchGroup.enter() dexterQueriesQueue.async { [weak self] in guard let url = self?.config.primaryNodeURL else { - os_log(.default, log: .kukaiCoreSwift, "Invalid server url: %@", self?.config.primaryNodeURL.absoluteString ?? "nil") + Logger.kukaiCoreSwift.info("Invalid server url: \(self?.config.primaryNodeURL.absoluteString ?? "nil")") completion(false, KukaiError.internalApplicationError(error: NetworkService.NetworkError.invalidURL)) return } diff --git a/Sources/KukaiCoreSwift/Clients/TzKTClient.swift b/Sources/KukaiCoreSwift/Clients/TzKTClient.swift index 5cd55113..26d4d638 100644 --- a/Sources/KukaiCoreSwift/Clients/TzKTClient.swift +++ b/Sources/KukaiCoreSwift/Clients/TzKTClient.swift @@ -607,7 +607,7 @@ public class TzKTClient { completion(operations, nil) case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Parse error: %@", "\(error)") + Logger.tzkt.error("Parse error: \(error)") completion(nil, KukaiError.internalApplicationError(error: error)) } } @@ -636,12 +636,11 @@ public class TzKTClient { signalrConnection = HubConnectionBuilder(url: url).build() } - // Register for SignalR operation events signalrConnection?.on(method: "accounts", callback: { [weak self] argumentExtractor in do { let obj = try argumentExtractor.getArgument(type: AccountSubscriptionResponse.self) - os_log("Incoming object parsed: %@", log: .tzkt, type: .default, "\(obj)") + Logger.tzkt.info("Incoming object parsed: \(String(describing: obj))") if let data = obj.data { var changedAddress: [String] = [] @@ -653,7 +652,7 @@ public class TzKTClient { } } catch (let error) { - os_log("Failed to parse incoming websocket data: %@", log: .tzkt, type: .error, "\(error)") + Logger.tzkt.error("Failed to parse incoming websocket data: \(error)") self?.signalrConnection?.stop() self?.isListening = false //completion(false, error, KukaiError.internalApplicationError(error: error)) @@ -667,7 +666,7 @@ public class TzKTClient { Close the websocket from `listenForAccountChanges` */ public func stopListeningForAccountChanges() { - os_log(.default, log: .kukaiCoreSwift, "Cancelling listenForAccountChanges") + Logger.tzkt.info("Cancelling listenForAccountChanges") signalrConnection?.stop() isListening = false } @@ -949,7 +948,7 @@ public class TzKTClient { dispatchGroupTransactions.leave() case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Parse error 1: %@", "\(error)") + Logger.tzkt.error("Parse error 1: \(error)") dispatchGroupTransactions.leave() } } @@ -969,7 +968,7 @@ public class TzKTClient { dispatchGroupTransactions.leave() case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Parse error 2: %@", "\(error)") + Logger.tzkt.error("Parse error 2: \(error)") dispatchGroupTransactions.leave() } } @@ -1095,16 +1094,16 @@ extension TzKTClient: HubConnectionDelegate { let subscription = AccountSubscription(addresses: addressesToWatch) signalrConnection?.invoke(method: "SubscribeToAccounts", subscription) { [weak self] error in if let error = error { - os_log("Subscribe to account changes failed: %@", log: .tzkt, type: .error, "\(error)") + Logger.tzkt.error("Subscribe to account changes failed: \(error)") self?.signalrConnection?.stop() } else { - os_log("Subscribe to account changes succeeded, waiting for objects", log: .tzkt, type: .default) + Logger.tzkt.info("Subscribe to account changes succeeded, waiting for objects") } } } public func connectionDidClose(error: Error?) { - os_log("SignalR connection closed: %@", log: .tzkt, type: .default, String(describing: error)) + Logger.tzkt.error("SignalR connection closed: \(error)") if newAddressesToWatch.count > 0 { self.listenForAccountChanges(addresses: newAddressesToWatch) @@ -1113,6 +1112,6 @@ extension TzKTClient: HubConnectionDelegate { } public func connectionDidFailToOpen(error: Error) { - os_log("Failed to open SignalR connection to listen for changes: %@", log: .tzkt, type: .error, "\(error)") + Logger.tzkt.error("Failed to open SignalR connection to listen for changes: \(error)") } } diff --git a/Sources/KukaiCoreSwift/Extensions/OSLogs+categories.swift b/Sources/KukaiCoreSwift/Extensions/OSLogs+categories.swift index cf5d872c..e7081aa4 100644 --- a/Sources/KukaiCoreSwift/Extensions/OSLogs+categories.swift +++ b/Sources/KukaiCoreSwift/Extensions/OSLogs+categories.swift @@ -9,17 +9,17 @@ import Foundation import os.log /// Extension to OSLog to create some custom categories for logging -extension OSLog { +public extension Logger { private static var subsystem = Bundle.main.bundleIdentifier ?? "app.kukai.kukai-core-swift" - static let kukaiCoreSwift = OSLog(subsystem: subsystem, category: "KukaiCoreSwift") - static let walletCache = OSLog(subsystem: subsystem, category: "WalletCache") - static let kukaiCoreSwiftError = OSLog(subsystem: subsystem, category: "KukaiCoreSwift-error") - static let keychain = OSLog(subsystem: subsystem, category: "KukaiCoreSwift-keychain") - static let network = OSLog(subsystem: subsystem, category: "KukaiCoreSwift-network") - static let bcd = OSLog(subsystem: subsystem, category: "BetterCallDev") - static let tzkt = OSLog(subsystem: subsystem, category: "TzKT") - static let taquitoService = OSLog(subsystem: subsystem, category: "TaquitoService") - static let torus = OSLog(subsystem: subsystem, category: "Torus") - static let ledger = OSLog(subsystem: subsystem, category: "Ledger") + static let kukaiCoreSwift = Logger(subsystem: subsystem, category: "KukaiCoreSwift") + static let walletCache = Logger(subsystem: subsystem, category: "WalletCache") + static let kukaiCoreSwiftError = Logger(subsystem: subsystem, category: "KukaiCoreSwift-error") + static let keychain = Logger(subsystem: subsystem, category: "KukaiCoreSwift-keychain") + static let network = Logger(subsystem: subsystem, category: "KukaiCoreSwift-network") + static let bcd = Logger(subsystem: subsystem, category: "BetterCallDev") + static let tzkt = Logger(subsystem: subsystem, category: "TzKT") + static let taquitoService = Logger(subsystem: subsystem, category: "TaquitoService") + static let torus = Logger(subsystem: subsystem, category: "Torus") + static let ledger = Logger(subsystem: subsystem, category: "Ledger") } diff --git a/Sources/KukaiCoreSwift/Extensions/URL+extensions.swift b/Sources/KukaiCoreSwift/Extensions/URL+extensions.swift index f7229548..540a07c3 100644 --- a/Sources/KukaiCoreSwift/Extensions/URL+extensions.swift +++ b/Sources/KukaiCoreSwift/Extensions/URL+extensions.swift @@ -33,7 +33,7 @@ extension URL { if let u = urlComponents.url { self = u } else { - os_log("Unable to appendQueryItem %@ to URL", log: .kukaiCoreSwift, type: .error, name) + Logger.kukaiCoreSwift.error("Unable to appendQueryItem \(name) to URL") } } diff --git a/Sources/KukaiCoreSwift/Factories/OperationFactory.swift b/Sources/KukaiCoreSwift/Factories/OperationFactory.swift index 50a0b05e..5b554285 100644 --- a/Sources/KukaiCoreSwift/Factories/OperationFactory.swift +++ b/Sources/KukaiCoreSwift/Factories/OperationFactory.swift @@ -28,7 +28,7 @@ public class OperationFactory { // Return empty array if `TokenAmount` is a negaitve value if tokenAmount < TokenAmount.zeroBalance(decimalPlaces: tokenAmount.decimalPlaces) { - os_log(.error, log: .kukaiCoreSwift, "Negative value passed to OperationFactory.sendOperation") + Logger.kukaiCoreSwift.error("Negative value passed to OperationFactory.sendOperation") return [] } @@ -49,7 +49,7 @@ public class OperationFactory { case .nonfungible: // Can't send an entire NFT group, need to rethink this - os_log(.error, log: .kukaiCoreSwift, "Can't send an entire NFT group. Must send individual NFT's from token.nfts array, via the other sendOperation") + Logger.kukaiCoreSwift.error("Can't send an entire NFT group. Must send individual NFT's from token.nfts array, via the other sendOperation") return [] } } @@ -66,7 +66,7 @@ public class OperationFactory { // Return empty array if `amount` is a negaitve value if amount < 0 { - os_log(.error, log: .kukaiCoreSwift, "Negative value passed to OperationFactory.sendOperation") + Logger.kukaiCoreSwift.error("Negative value passed to OperationFactory.sendOperation") return [] } diff --git a/Sources/KukaiCoreSwift/Models/RPC.swift b/Sources/KukaiCoreSwift/Models/RPC.swift index e5c9c8af..ba565a35 100644 --- a/Sources/KukaiCoreSwift/Models/RPC.swift +++ b/Sources/KukaiCoreSwift/Models/RPC.swift @@ -53,7 +53,7 @@ public class RPC { return try JSONEncoder().encode(encodable) } catch(let error) { - os_log(.error, log: .kukaiCoreSwift, "Unable to encode object as string: %@", "\(error)") + Logger.kukaiCoreSwift.error("Unable to encode object as string: \(error)") return nil } } @@ -161,7 +161,7 @@ extension RPC where T == [OperationResponse] { /// Creates an RPC to preapply an operation. This `OperationPayload` must have had its signature and protocol set public static func preapply(operationPayload: OperationPayload) -> RPC<[OperationResponse]>? { if operationPayload.signature == nil || operationPayload.protocol == nil { - os_log(.error, log: .kukaiCoreSwift, "RPC preapply was passed an operationPayload without a signature and/or protocol") + Logger.kukaiCoreSwift.error("RPC preapply was passed an operationPayload without a signature and/or protocol") return nil } diff --git a/Sources/KukaiCoreSwift/Models/RegularWallet.swift b/Sources/KukaiCoreSwift/Models/RegularWallet.swift index 572390b7..87f7d3c8 100644 --- a/Sources/KukaiCoreSwift/Models/RegularWallet.swift +++ b/Sources/KukaiCoreSwift/Models/RegularWallet.swift @@ -48,7 +48,7 @@ public class RegularWallet: Wallet { guard let privateKey = PrivateKey(base58String, signingCurve: .secp256k1), let pubKey = KeyPair.secp256k1PublicKey(fromPrivateKeyBytes: privateKey.bytes), let tempAddress = pubKey.publicKeyHash else { - os_log("Failed to construct private/public key", log: .kukaiCoreSwift, type: .error) + Logger.kukaiCoreSwift.error("Failed to construct private/public key") return nil } diff --git a/Sources/KukaiCoreSwift/Models/Token.swift b/Sources/KukaiCoreSwift/Models/Token.swift index ab0fa3cd..cd4e2421 100644 --- a/Sources/KukaiCoreSwift/Models/Token.swift +++ b/Sources/KukaiCoreSwift/Models/Token.swift @@ -114,7 +114,7 @@ public class Token: Codable, CustomStringConvertible { // TODO: make failable init if let faVersion = faVersion, faVersion == .fa2 && tokenId == nil { - os_log("Error: FA2 tokens require having a tokenId set, %@", log: .kukaiCoreSwift, type: .error, name ?? tokenContractAddress ?? "") + Logger.kukaiCoreSwift.error("Error: FA2 tokens require having a tokenId set, \(name ?? tokenContractAddress ?? "")") } } @@ -139,7 +139,8 @@ public class Token: Codable, CustomStringConvertible { // TODO: make failable init if let faVersion = faVersion, faVersion == .fa2 && tokenId == nil { - os_log("Error: FA2 tokens require having a tokenId set, %@", log: .kukaiCoreSwift, type: .error, name ?? tokenContractAddress ?? "") + weak var weakSelf = self + Logger.kukaiCoreSwift.error("Error: FA2 tokens require having a tokenId set, \(weakSelf?.name ?? weakSelf?.tokenContractAddress ?? "")") } } @@ -164,7 +165,8 @@ public class Token: Codable, CustomStringConvertible { // TODO: make failable init if let faVersion = faVersion, faVersion == .fa2 && tokenId == nil { - os_log("Error: FA2 tokens require having a tokenId set, %@", log: .kukaiCoreSwift, type: .error, name ?? tokenContractAddress ?? "") + weak var weakSelf = self + Logger.kukaiCoreSwift.error("Error: FA2 tokens require having a tokenId set, \(weakSelf?.name ?? weakSelf?.tokenContractAddress ?? "")") } } diff --git a/Sources/KukaiCoreSwift/Models/TokenAmount.swift b/Sources/KukaiCoreSwift/Models/TokenAmount.swift index da778fc2..5e41eea3 100644 --- a/Sources/KukaiCoreSwift/Models/TokenAmount.swift +++ b/Sources/KukaiCoreSwift/Models/TokenAmount.swift @@ -85,7 +85,7 @@ public class TokenAmount: Codable { */ public init?(fromRpcAmount rpcAmount: String, decimalPlaces: Int) { guard CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: rpcAmount)) else { - os_log(.error, log: .kukaiCoreSwift, "Can't set balance on a Token of tokenType.empty, or pass in a string with non digit characters. Entered: %@", rpcAmount) + Logger.kukaiCoreSwift.error("Can't set balance on a Token of tokenType.empty, or pass in a string with non digit characters. Entered: \(rpcAmount)") return nil } @@ -126,7 +126,7 @@ public class TokenAmount: Codable { */ public convenience init?(fromNormalisedAmount normalisedAmount: String, decimalPlaces: Int) { guard let decimal = Decimal(string: normalisedAmount.replacingOccurrences(of: (Locale.current.decimalSeparator ?? "."), with: ".")) else { - os_log(.error, log: .kukaiCoreSwift, "Can't set balance as can't parse string") + Logger.kukaiCoreSwift.error("Can't set balance as can't parse string") return nil } @@ -277,7 +277,7 @@ public class TokenAmount: Codable { let result = (lhs.decimalPlaces == rhs.decimalPlaces) if !result { - os_log(.error, log: .kukaiCoreSwift, "Arithmetic function is not possible between tokens with different decimal places. Ignoring operation.") + Logger.kukaiCoreSwift.error("Arithmetic function is not possible between tokens with different decimal places. Ignoring operation.") } return result diff --git a/Sources/KukaiCoreSwift/Models/TorusWallet.swift b/Sources/KukaiCoreSwift/Models/TorusWallet.swift index 4dece7c5..7bfaa8f4 100644 --- a/Sources/KukaiCoreSwift/Models/TorusWallet.swift +++ b/Sources/KukaiCoreSwift/Models/TorusWallet.swift @@ -48,7 +48,7 @@ public class TorusWallet: RegularWallet { */ public init?(authProvider: TorusAuthProvider, username: String?, userId: String?, profilePicture: String?, torusPrivateKey: String) { guard let bytes = Sodium.shared.utils.hex2bin(torusPrivateKey) else { - os_log("Unable to convert hex to binary", log: .torus, type: .error) + Logger.torus.error("Unable to convert hex to binary") return nil } diff --git a/Sources/KukaiCoreSwift/Models/XTZAmount.swift b/Sources/KukaiCoreSwift/Models/XTZAmount.swift index 779125f3..5923bd9e 100644 --- a/Sources/KukaiCoreSwift/Models/XTZAmount.swift +++ b/Sources/KukaiCoreSwift/Models/XTZAmount.swift @@ -46,7 +46,7 @@ public class XTZAmount: TokenAmount { */ public convenience init?(fromNormalisedAmount normalisedAmount: String, decimalPlaces: Int) { guard let decimal = Decimal(string: normalisedAmount.replacingOccurrences(of: (Locale.current.decimalSeparator ?? "."), with: ".")) else { - os_log(.error, log: .kukaiCoreSwift, "Can't set balance as can't parse string") + Logger.kukaiCoreSwift.error("Can't set balance as can't parse string") return nil } diff --git a/Sources/KukaiCoreSwift/Services/DexCalculationService.swift b/Sources/KukaiCoreSwift/Services/DexCalculationService.swift index d23ab894..c7a8aa37 100644 --- a/Sources/KukaiCoreSwift/Services/DexCalculationService.swift +++ b/Sources/KukaiCoreSwift/Services/DexCalculationService.swift @@ -71,7 +71,7 @@ public class DexCalculationService { private init() { jsContext = JSContext() jsContext.exceptionHandler = { context, exception in - os_log("Dex calculation JSContext exception: %@", log: .kukaiCoreSwift, type: .error, exception?.toString() ?? "") + Logger.kukaiCoreSwift.error("Dex calculation JSContext exception: \(exception?.toString() ?? "")") } if let jsSourcePath = Bundle.module.url(forResource: "kukai-dex-calculations", withExtension: "js") { @@ -80,7 +80,7 @@ public class DexCalculationService { self.jsContext.evaluateScript(jsSourceContents) } catch (let error) { - os_log("Error parsing Dex calculation javascript file: %@", log: .kukaiCoreSwift, type: .error, "\(error)") + Logger.kukaiCoreSwift.error("Error parsing Dex calculation javascript file: \(error)") } } } @@ -238,7 +238,7 @@ public class DexCalculationService { let token = tokenAmount.rpcRepresentation guard slippage >= 0, slippage <= 1 else { - os_log("slippage value supplied to `xtzToTokenMinimumReturn` was not between 0 and 1: %@", log: .kukaiCoreSwift, type: .error, slippage) + Logger.kukaiCoreSwift.error("slippage value supplied to `xtzToTokenMinimumReturn` was not between 0 and 1: \(slippage)") return nil } @@ -403,7 +403,7 @@ public class DexCalculationService { let xtz = xtzAmount.rpcRepresentation guard slippage >= 0, slippage <= 1 else { - os_log("slippage value supplied to `tokenToXtzMinimumReturn` was not between 0 and 1: %@", log: .kukaiCoreSwift, type: .error, slippage) + Logger.kukaiCoreSwift.error("slippage value supplied to `tokenToXtzMinimumReturn` was not between 0 and 1: \(slippage)") return nil } @@ -545,7 +545,7 @@ public class DexCalculationService { */ public func addLiquidityReturn(xtzToDeposit: XTZAmount, xtzPool: XTZAmount, totalLiquidity: TokenAmount, slippage: Double, dex: DipDupExchangeName) -> (expected: TokenAmount, minimum: TokenAmount)? { guard slippage >= 0, slippage <= 1 else { - os_log("slippage value supplied to `addLiquidityReturn` was not between 0 and 1: %@", log: .kukaiCoreSwift, type: .error, slippage) + Logger.kukaiCoreSwift.error("slippage value supplied to `addLiquidityReturn` was not between 0 and 1: \(slippage)") return nil } @@ -629,7 +629,7 @@ public class DexCalculationService { */ public func removeLiquidityTokenReceived(liquidityBurned: TokenAmount, totalLiquidity: TokenAmount, tokenPool: TokenAmount, slippage: Double) -> (expected: TokenAmount, minimum: TokenAmount)? { guard slippage >= 0, slippage <= 1 else { - os_log("slippage value supplied to `removeLiquidityTokenReceived` was not between 0 and 1: %@", log: .kukaiCoreSwift, type: .error, slippage) + Logger.kukaiCoreSwift.error("slippage value supplied to `removeLiquidityTokenReceived` was not between 0 and 1: \(slippage)") return nil } @@ -664,7 +664,7 @@ public class DexCalculationService { */ public func removeLiquidityXtzReceived(liquidityBurned: TokenAmount, totalLiquidity: TokenAmount, xtzPool: XTZAmount, slippage: Double, dex: DipDupExchangeName) -> (expected: XTZAmount, minimum: XTZAmount)? { guard slippage >= 0, slippage <= 1 else { - os_log("slippage value supplied to `removeLiquidityXtzReceived` was not between 0 and 1: %@", log: .kukaiCoreSwift, type: .error, slippage) + Logger.kukaiCoreSwift.error("slippage value supplied to `removeLiquidityXtzReceived` was not between 0 and 1: \(slippage)") return nil } diff --git a/Sources/KukaiCoreSwift/Services/DiskService.swift b/Sources/KukaiCoreSwift/Services/DiskService.swift index 26249af0..142de233 100644 --- a/Sources/KukaiCoreSwift/Services/DiskService.swift +++ b/Sources/KukaiCoreSwift/Services/DiskService.swift @@ -22,7 +22,7 @@ public class DiskService { */ public static func write(data: Data, toFileName: String, isExcludedFromBackup: Bool = true) -> Bool { guard let dir = documentsDirectory(isExcludedFromBackup: isExcludedFromBackup) else { - os_log(.error, log: .kukaiCoreSwift, "Failed to find documents directory") + Logger.kukaiCoreSwift.error("Failed to find documents directory") return false } @@ -30,7 +30,7 @@ public class DiskService { // delete any old file first if !delete(fileName: toFileName) { - os_log(.error, log: .kukaiCoreSwift, "Failed to clear old file") + Logger.kukaiCoreSwift.error("Failed to clear old file") return false } @@ -38,11 +38,11 @@ public class DiskService { do { try data.write(to: fileURL) - os_log(.default, log: .kukaiCoreSwift, "Serialised encodable to: %@", toFileName) + Logger.kukaiCoreSwift.info("Serialised encodable to: \(toFileName)") return true } catch (let error) { - os_log(.error, log: .kukaiCoreSwift, "Failed to write to %@: %@", toFileName, "\(error)") + Logger.kukaiCoreSwift.error("Failed to write to \(toFileName): \((error))") return false } } @@ -57,7 +57,7 @@ public class DiskService { return write(data: encodedData, toFileName: toFileName, isExcludedFromBackup: isExcludedFromBackup) } catch (let error) { - os_log(.error, log: .kukaiCoreSwift, "Failed to write to %@: %@", toFileName, "\(error)") + Logger.kukaiCoreSwift.error("Failed to write to \(toFileName): \(error)") return false } } @@ -72,7 +72,7 @@ public class DiskService { */ public static func readData(fromFileName: String) -> Data? { guard let dir = documentsDirectory() else { - os_log(.error, log: .kukaiCoreSwift, "Failed to find documents directory") + Logger.kukaiCoreSwift.error("Failed to find documents directory") return nil } @@ -83,7 +83,7 @@ public class DiskService { return try Data(contentsOf: fileURL) } catch (let error) { - os_log(.error, log: .kukaiCoreSwift, "Failed to read from %@: %@", fromFileName, "\(error)") + Logger.kukaiCoreSwift.error("Failed to read from \(fromFileName): \(error)") return nil } } @@ -102,7 +102,7 @@ public class DiskService { return try JSONDecoder().decode(T.self, from: data) } catch (let error) { - os_log(.error, log: .kukaiCoreSwift, "Failed to parse decodable from %@: %@", fromFileName, "\(error)") + Logger.kukaiCoreSwift.error("Failed to parse decodable from \(fromFileName): \(error)") return nil } } @@ -125,7 +125,7 @@ public class DiskService { return true } catch (let error) { - os_log(.error, log: .kukaiCoreSwift, "Failed to delete file %@: %@", fileName, "\(error)") + Logger.kukaiCoreSwift.error("Failed to delete file \(fileName): \(error)") return false } } @@ -158,7 +158,7 @@ public class DiskService { return url } catch (let error) { - os_log(.error, log: .kukaiCoreSwift, "Error fetching documents directory: %@", "\(error)") + Logger.kukaiCoreSwift.error("Error fetching documents directory: \(error)") return nil } } diff --git a/Sources/KukaiCoreSwift/Services/ErrorHandlingService.swift b/Sources/KukaiCoreSwift/Services/ErrorHandlingService.swift index 5800483c..20bdc311 100644 --- a/Sources/KukaiCoreSwift/Services/ErrorHandlingService.swift +++ b/Sources/KukaiCoreSwift/Services/ErrorHandlingService.swift @@ -290,7 +290,7 @@ public class ErrorHandlingService { // MARK: - Logging private class func logAndCallback(withKukaiError kukaiError: KukaiError) { - os_log(.error, log: .kukaiCoreSwift, "%@", kukaiError.description) + Logger.kukaiCoreSwift.error("\(kukaiError.description)") if let closure = ErrorHandlingService.shared.errorEventClosure { closure(kukaiError) diff --git a/Sources/KukaiCoreSwift/Services/FeeEstimatorService.swift b/Sources/KukaiCoreSwift/Services/FeeEstimatorService.swift index 8699f29a..1a66bf71 100644 --- a/Sources/KukaiCoreSwift/Services/FeeEstimatorService.swift +++ b/Sources/KukaiCoreSwift/Services/FeeEstimatorService.swift @@ -159,7 +159,7 @@ public class FeeEstimatorService { /// Breaking out part of the estimation process to keep code cleaner private func estimate(runOperationPayload: RunOperationPayload, preparedOperationsCopy: [Operation], constants: NetworkConstants, forgedHex: String, originalRemoteOps: [Operation], completion: @escaping ((Result) -> Void)) { guard let rpc = RPC.runOperation(runOperationPayload: runOperationPayload) else { - os_log(.error, log: .kukaiCoreSwift, "Unable to create runOperation RPC, cancelling event") + Logger.kukaiCoreSwift.error("Unable to create runOperation RPC, cancelling event") completion(Result.failure(KukaiError.internalApplicationError(error: FeeEstimatorServiceError.unableToSetupRunOperation))) return } diff --git a/Sources/KukaiCoreSwift/Services/LedgerService.swift b/Sources/KukaiCoreSwift/Services/LedgerService.swift index 8dce8ba0..a60c4384 100644 --- a/Sources/KukaiCoreSwift/Services/LedgerService.swift +++ b/Sources/KukaiCoreSwift/Services/LedgerService.swift @@ -157,7 +157,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele private override init() { jsContext = JSContext() jsContext.exceptionHandler = { context, exception in - os_log("Ledger JSContext exception: %@", log: .kukaiCoreSwift, type: .error, exception?.toString() ?? "") + Logger.ledger.error("Ledger JSContext exception: \(exception?.toString() ?? "")") } @@ -168,7 +168,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele self.jsContext.evaluateScript(jsSourceContents) } catch (let error) { - os_log("Error parsing Ledger javascript file: %@", log: .kukaiCoreSwift, type: .error, "\(error)") + Logger.ledger.error("Error parsing Ledger javascript file: \(error)") } } @@ -177,7 +177,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele // Register a native function, to be passed into the js functions, that will write chunks of data to the device let nativeWriteHandler: @convention(block) (String, Int) -> Void = { [weak self] (apdu, expectedNumberOfAPDUs) in - os_log("Inside nativeWriteHandler", log: .ledger, type: .default) + Logger.ledger.info("Inside nativeWriteHandler") // Keep track of the number of times its called for each request self?.counter += 1 @@ -358,7 +358,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele /// CBCentralManagerDelegate function, must be marked public because of protocol definition public func centralManagerDidUpdateState(_ central: CBCentralManager) { - os_log("centralManagerDidUpdateState", log: .ledger, type: .default) + Logger.ledger.info("centralManagerDidUpdateState") self.bluetoothSetup = (central.state == .poweredOn) } @@ -367,7 +367,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele // If we have been requested to connect to a speicific UUID, only listen for that one and connect immediately if found if let requested = self.requestedUUID, peripheral.identifier.uuidString == requested { - os_log("Found requested ledger UUID, connecting ...", log: .ledger, type: .default) + Logger.ledger.info("Found requested ledger UUID, connecting ...") self.connectedDevice = peripheral self.centralManager?.connect(peripheral, options: ["requestMTU": 156]) @@ -375,7 +375,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele // Else if we haven't been requested to find a specific one, store each unique device and fire a delegate callback, until scan stopped manually } else if self.requestedUUID == nil, deviceList[peripheral.identifier.uuidString] == nil { - os_log("Found a new ledger device. Name: %@, UUID: %@", log: .ledger, type: .default, peripheral.name ?? "-", peripheral.identifier.uuidString) + Logger.ledger.info("Found a new ledger device. Name: \(peripheral.name ?? "-"), UUID: \(peripheral.identifier.uuidString)") self.deviceList[peripheral.identifier.uuidString] = peripheral.name ?? "" } @@ -383,7 +383,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele /// CBCentralManagerDelegate function, must be marked public because of protocol definition public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { - os_log("Connected to %@, %@", log: .ledger, type: .default, peripheral.name ?? "", peripheral.identifier.uuidString) + Logger.ledger.info("Connected to \(peripheral.name ?? ""), \(peripheral.identifier.uuidString)") // record the connected device and set LedgerService as the delegate. Don't report successfully connected to ledgerService.delegate until // we have received the callbacks for services and characteristics. Otherwise we can't use the device @@ -394,7 +394,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele /// CBCentralManagerDelegate function, must be marked public because of protocol definition public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { - os_log("Failed to connect to %@, %@", log: .ledger, type: .default, peripheral.name ?? "", peripheral.identifier.uuidString) + Logger.ledger.info("Failed to connect to \(peripheral.name ?? ""), \(peripheral.identifier.uuidString)") self.connectedDevice = nil self.deviceConnectedPublisher.send(false) } @@ -402,7 +402,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele /// CBCentralManagerDelegate function, must be marked public because of protocol definition public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let services = peripheral.services else { - os_log("Unable to locate services for: %@, %@. Error: %@", log: .ledger, type: .default, peripheral.name ?? "", peripheral.identifier.uuidString, "\(String(describing: error))") + Logger.ledger.info("Unable to locate services for: \(peripheral.name ?? ""), \(peripheral.identifier.uuidString). Error: \(error)") self.connectedDevice = nil self.deviceConnectedPublisher.send(false) return @@ -419,7 +419,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele /// CBCentralManagerDelegate function, must be marked public because of protocol definition public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard let characteristics = service.characteristics else { - os_log("Unable to locate characteristics for: %@, %@. Error: %@", log: .ledger, type: .default, peripheral.name ?? "", peripheral.identifier.uuidString, "\(String(describing: error))") + Logger.ledger.info("Unable to locate characteristics for: \(peripheral.name ?? ""), \(peripheral.identifier.uuidString). Error: \(error)") self.connectedDevice = nil self.deviceConnectedPublisher.send(false) return @@ -427,16 +427,16 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele for characteristic in characteristics { if characteristic.uuid == LedgerNanoXConstant.writeUUID { - os_log("Located write characteristic", log: .ledger, type: .default) + Logger.ledger.info("Located write characteristic") writeCharacteristic = characteristic } else if characteristic.uuid == LedgerNanoXConstant.notifyUUID { - os_log("Located notify characteristic", log: .ledger, type: .default) + Logger.ledger.info("Located notify characteristic") notifyCharacteristic = characteristic } if let _ = writeCharacteristic, let notify = notifyCharacteristic { - os_log("Registering for notifications on notify characteristic", log: .ledger, type: .default) + Logger.ledger.info("Registering for notifications on notify characteristic") peripheral.setNotifyValue(true, for: notify) self.deviceConnectedPublisher.send(true) @@ -448,11 +448,11 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele /// CBCentralManagerDelegate function, must be marked public because of protocol definition public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { if let err = error { - os_log("Error during write: %@", log: .ledger, type: .default, "\( err )") + Logger.ledger.error("Error during write: \(err)") returnErrorToPublisher(statusCode: GeneralErrorCodes.UNKNOWN.rawValue) } else { - os_log("Successfully wrote to write characteristic", log: .ledger, type: .default) + Logger.ledger.info("Successfully wrote to write characteristic") } } @@ -462,7 +462,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele return } - os_log("Receiveing value from notify characteristic", log: .ledger, type: .default) + Logger.ledger.info("Receiveing value from notify characteristic") // Extract the payload, convert it to an APDU so the result can be extracted @@ -486,7 +486,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele if resultString.count <= 6 { - os_log("Received APDU Status code", log: .ledger, type: .default) + Logger.ledger.info("Received APDU Status code") receivedAPDU_statusCode.send(resultString) if resultString == LedgerService.successCode { @@ -496,7 +496,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele return } else { - os_log("Received APDU Payload", log: .ledger, type: .default) + Logger.ledger.info("Received APDU Payload") receivedAPDU_payload.send(resultString) return } @@ -519,7 +519,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele .collect() .sink { [weak self] apdus in guard let self = self, let writeChar = self.writeCharacteristic else { - os_log("setupWriteSubject - couldn't find self/write", log: .ledger, type: .error) + Logger.ledger.error("setupWriteSubject - couldn't find self/write") return } @@ -537,7 +537,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele // This allows us to run the code for + send each APDU and wait a response from the device, before moving to the next APDU. // This allows us to catch errors when they first occur, and return immeidately, instead of firing error for each APDU packet, causing UI issues guard let concatenatedPublishers = futures.concatenatePublishers() else { - os_log("setupWriteSubject - unable to create concatenatedPublishers", log: .ledger, type: .error) + Logger.ledger.error("setupWriteSubject - unable to create concatenatedPublishers") return } @@ -550,12 +550,12 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele guard let res = try? concatenatedResult.get() else { let error = (try? concatenatedResult.getError()) ?? KukaiError.unknown() - os_log("setupWriteSubject - received error: %@", log: .ledger, type: .default, "\(error)") + Logger.ledger.error("setupWriteSubject - received error: \(error)") self.returnKukaiErrorToPublisher(kukaiError: error) return } - os_log("setupWriteSubject - received value: %@", log: .ledger, type: .default, "\( res )") + Logger.ledger.info("setupWriteSubject - received value: \(res)") switch self.requestType { case .address: self.convertAPDUToAddress(payload: res) @@ -564,7 +564,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele self.convertAPDUToSignature(payload: res) case .none: - os_log("Received a value, but no request type set", log: .ledger, type: .error) + Logger.ledger.error("Received a value, but no request type set") } } .store(in: &self.bag_writer) @@ -577,7 +577,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele return Deferred { Future { [weak self] promise in guard let self = self else { - os_log("sendAPDU - couldn't find self", log: .ledger, type: .error) + Logger.ledger.error("sendAPDU - couldn't find self") promise(.failure(KukaiError.unknown())) return } @@ -588,7 +588,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele if component != "" { let data = (try? Data(hexString: component)) ?? Data() - os_log("sendAPDU - writing payload", log: .ledger, type: .default) + Logger.ledger.info("sendAPDU - writing payload") self.connectedDevice?.writeValue(data, for: writeCharacteristic, type: .withResponse) } } @@ -597,11 +597,11 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele // Listen for responses self.receivedAPDU_statusCode.sink { statusCode in if statusCode == LedgerService.successCode { - os_log("sendAPDU - received success statusCode", log: .ledger, type: .default) + Logger.ledger.info("sendAPDU - received success statusCode") promise(.success(nil)) } else { - os_log("sendAPDU - received error statusCode: %@", log: .ledger, type: .error, statusCode) + Logger.ledger.error("sendAPDU - received error statusCode: \(statusCode)") promise(.failure( self.kukaiErrorFrom(statusCode: statusCode) )) } @@ -610,7 +610,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele self.receivedAPDU_payload.sink { payload in - os_log("sendAPDU - received payload: %@", log: .ledger, type: .default, payload) + Logger.ledger.info("sendAPDU - received payload: \(payload)") promise(.success(payload)) } .store(in: &self.bag_apdu) @@ -626,18 +626,18 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele } guard let dict = jsContext.evaluateScript("ledger_app_tezos.convertAPDUtoAddress(\"\(payload)\")").toObject() as? [String: String] else { - os_log("Didn't receive address object", log: .ledger, type: .error) + Logger.ledger.error("Didn't receive address object") returnErrorToPublisher(statusCode: GeneralErrorCodes.UNKNOWN.rawValue) return } guard let address = dict["address"], let publicKey = dict["publicKey"] else { if let err = dict["error"] { - os_log("Internal script error: %@", log: .ledger, type: .error, err) + Logger.ledger.error("Internal script error: \(err)") returnErrorToPublisher(statusCode: GeneralErrorCodes.UNKNOWN.rawValue) } else { - os_log("Unknown error", log: .ledger, type: .error) + Logger.ledger.error("Unknown error") returnErrorToPublisher(statusCode: GeneralErrorCodes.UNKNOWN.rawValue) } return @@ -654,7 +654,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele } guard let resultHex = jsContext.evaluateScript("ledger_app_tezos.convertAPDUtoSignature(\"\(payload)\").signature").toString() else { - os_log("Didn't receive signature", log: .ledger, type: .error) + Logger.ledger.error("Didn't receive signature") returnErrorToPublisher(statusCode: GeneralErrorCodes.UNKNOWN.rawValue) return } @@ -664,14 +664,14 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele self.signaturePublisher.send(completion: .finished) } else { - os_log("Unknown error. APDU: %@", log: .ledger, type: .error, resultHex) + Logger.ledger.error("Unknown error. APDU: \(resultHex)") returnErrorToPublisher(statusCode: GeneralErrorCodes.UNKNOWN.rawValue) } } /// Create and error response from a statusCode private func kukaiErrorFrom(statusCode: String) -> KukaiError { - os_log("Error parsing data. statusCode: %@", log: .ledger, type: .error, statusCode) + Logger.ledger.error("Error parsing data. statusCode: \(statusCode)") var code = GeneralErrorCodes.UNKNOWN.rawValue var type: Error = GeneralErrorCodes.UNKNOWN @@ -685,7 +685,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele type = generalCode } - os_log("Ledger error code: %@", log: .ledger, type: .error, code) + Logger.ledger.error("Ledger error code: \(code)") return KukaiError.internalApplicationError(error: type) } @@ -705,7 +705,7 @@ public class LedgerService: NSObject, CBPeripheralDelegate, CBCentralManagerDele self.signaturePublisher.send(completion: .failure(kukaiError)) case .none: - os_log("Requesting error for unknown requestType: %@", log: .ledger, type: .error, "\(kukaiError)") + Logger.ledger.error("Requesting error for unknown requestType: \(kukaiError)") } } } diff --git a/Sources/KukaiCoreSwift/Services/MediaProxyService.swift b/Sources/KukaiCoreSwift/Services/MediaProxyService.swift index 40c2527a..1adbfafa 100644 --- a/Sources/KukaiCoreSwift/Services/MediaProxyService.swift +++ b/Sources/KukaiCoreSwift/Services/MediaProxyService.swift @@ -317,7 +317,7 @@ public class MediaProxyService: NSObject { imageView.kf.indicatorType = .activity imageView.kf.setImage(with: url, options: processors) { result in guard let res = try? result.get() else { - os_log("Error fetching: %@, Error: %@", log: .kukaiCoreSwift, type: .error, url.absoluteString, String(describing: try? result.getError())) + Logger.kukaiCoreSwift.error("Error fetching: \(url.absoluteString), Error: \(String(describing: try? result.getError()))") imageView.image = fallback if let comp = completion { comp(nil) } return @@ -366,7 +366,7 @@ public class MediaProxyService: NSObject { } case .failure(let error): - os_log("Error downloading + caching image: %@", log: .kukaiCoreSwift, type: .default, "\(error)") + Logger.kukaiCoreSwift.error("Error downloading + caching image: \(error)") completion(nil) } } @@ -400,7 +400,7 @@ public class MediaProxyService: NSObject { completion(value.image?.size) case .failure(let error): - os_log("Error fetching from cache: %@", log: .kukaiCoreSwift, type: .default, "\(error)") + Logger.kukaiCoreSwift.error("Error fetching from cache: \(error)") completion(nil) } } diff --git a/Sources/KukaiCoreSwift/Services/NetworkService.swift b/Sources/KukaiCoreSwift/Services/NetworkService.swift index aa8716c0..ba3dc2cc 100644 --- a/Sources/KukaiCoreSwift/Services/NetworkService.swift +++ b/Sources/KukaiCoreSwift/Services/NetworkService.swift @@ -213,9 +213,9 @@ public class NetworkService { let dataString = NetworkService.dataToStringStippingMichelsonContractCode(data: responseData) if isPost { - os_log(.error, log: .network, "Request Failed to: %@ \nRequest Body: %@ \nError: %@ \nStatusCode: %@ \nResponse: %@ \n_", fullURL.absoluteString, payloadString, String(describing: error), "\(String(describing: statusCode))", dataString) + Logger.network.error("Request Failed to: \(fullURL.absoluteString) \nRequest Body: \(payloadString) \nError: \(String(describing: error)) \nStatusCode: \(String(describing: statusCode)) \nResponse: \(dataString) \n_") } else { - os_log(.error, log: .network, "Request Failed to: %@ \nError: %@ \nResponse: %@ \n_", fullURL.absoluteString, String(describing: error), dataString) + Logger.network.error("Request Failed to: \(fullURL.absoluteString) \nError: \(String(describing: error)) \nResponse: \(dataString) \n_") } } @@ -227,9 +227,9 @@ public class NetworkService { let dataString = NetworkService.dataToStringStippingMichelsonContractCode(data: responseData) if isPost { - os_log(.default, log: .network, "Request Succeeded to: %@ \nRequest Body: %@ \nResponse: %@ \n_", fullURL.absoluteString, payloadString, dataString) + Logger.network.info("Request Succeeded to: \(fullURL.absoluteString) \nRequest Body: \(payloadString) \nResponse: \(dataString) \n_") } else { - os_log(.default, log: .network, "Request Succeeded to: %@ \nResponse: %@ \n_", fullURL.absoluteString, dataString) + Logger.network.info("Request Succeeded to: \(fullURL.absoluteString) \nResponse: \(dataString) \n_") } } @@ -237,7 +237,7 @@ public class NetworkService { public static func logRequestStart(loggingConfig: LoggingConfig?, fullURL: URL) { if !(loggingConfig?.logNetworkFailures ?? false) && !(loggingConfig?.logNetworkSuccesses ?? false) { return } - os_log(.default, log: .network, "Sending request to: %@", fullURL.absoluteString) + Logger.network.info("Sending request to: \(fullURL.absoluteString)") } /** diff --git a/Sources/KukaiCoreSwift/Services/OperationService.swift b/Sources/KukaiCoreSwift/Services/OperationService.swift index ca5f9fbe..09d7949a 100644 --- a/Sources/KukaiCoreSwift/Services/OperationService.swift +++ b/Sources/KukaiCoreSwift/Services/OperationService.swift @@ -84,7 +84,7 @@ public class OperationService { case .success(let hash): // With a successful Parse, we can continue on to Sign, Preapply (to check for errors) and if no errors, inject the operation - os_log(.default, log: .kukaiCoreSwift, "Remote parse successful") + Logger.kukaiCoreSwift.info("Remote parse successful") self?.signPreapplyAndInject(wallet: wallet, forgedHash: hash, operationPayload: operationPayload, operationMetadata: operationMetadata, completion: completion) case .failure(let parseError): @@ -197,7 +197,7 @@ public class OperationService { public func remoteForge(operationPayload: OperationPayload, completion: @escaping ((Result) -> Void)) { guard let rpc = RPC.forge(operationPayload: operationPayload) else { - os_log(.error, log: .kukaiCoreSwift, "Unable to create forge RPC, cancelling event") + Logger.kukaiCoreSwift.error("Unable to create forge RPC, cancelling event") completion(Result.failure(KukaiError.internalApplicationError(error: OperationServiceError.unableToSetupForge))) return } @@ -208,7 +208,7 @@ public class OperationService { completion(Result.success(string)) case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Unable to remote forge: %@", "\(error)") + Logger.kukaiCoreSwift.error("Unable to remote forge: \(error)") completion(Result.failure(error)) } } @@ -243,7 +243,7 @@ public class OperationService { // Continue with parse guard let rpc = RPC.parse(hashToParse: remoteForgedHash, metadata: operationMetadata) else { - os_log(.error, log: .kukaiCoreSwift, "Unable to create parse RPC, cancelling event") + Logger.kukaiCoreSwift.error("Unable to create parse RPC, cancelling event") completion(Result.failure(KukaiError.internalApplicationError(error: OperationServiceError.unableToSetupParse))) return } @@ -259,7 +259,7 @@ public class OperationService { } case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Unable to remote forge: %@", "\(error)") + Logger.kukaiCoreSwift.error("Unable to remote forge: \(error)") completion(Result.failure(error)) } } @@ -274,7 +274,7 @@ public class OperationService { public func preapply(operationPayload: OperationPayload, completion: @escaping ((Result<[OperationResponse], KukaiError>) -> Void)) { guard let rpc = RPC.preapply(operationPayload: operationPayload) else { - os_log(.error, log: .kukaiCoreSwift, "Unable to create preapply RPC, cancelling event") + Logger.kukaiCoreSwift.error("Unable to create preapply RPC, cancelling event") completion(Result.failure(KukaiError.internalApplicationError(error: OperationServiceError.unableToSetupPreapply))) return } @@ -285,7 +285,7 @@ public class OperationService { completion(Result.success(operationResponse)) case .failure(let error): - os_log(.error, log: .kukaiCoreSwift, "Preapply returned an error: %@", "\(error)") + Logger.kukaiCoreSwift.error("Preapply returned an error: \(error)") completion(Result.failure(error)) } } @@ -321,7 +321,7 @@ public class OperationService { // Continue on with the injection guard let rpc = RPC.inject(signedBytes: signedBytes) else { - os_log(.error, log: .kukaiCoreSwift, "Unable to create inject RPC, cancelling event") + Logger.kukaiCoreSwift.error("Unable to create inject RPC, cancelling event") completion(Result.failure(KukaiError.internalApplicationError(error: OperationServiceError.unableToSetupInject))) return } diff --git a/Sources/KukaiCoreSwift/Services/TaquitoService.swift b/Sources/KukaiCoreSwift/Services/TaquitoService.swift index 009dec23..4be6cdf4 100644 --- a/Sources/KukaiCoreSwift/Services/TaquitoService.swift +++ b/Sources/KukaiCoreSwift/Services/TaquitoService.swift @@ -47,7 +47,7 @@ public class TaquitoService { private init() { jsContext = JSContext() jsContext.exceptionHandler = { [weak self] context, exception in - os_log("Taquito JSContext exception: %@", log: .kukaiCoreSwift, type: .error, exception?.toString() ?? "") + Logger.taquitoService.error("Taquito JSContext exception: \(exception?.toString() ?? "")") if self?.isForging == true, let lastForge = self?.lastForgeCompletionHandler { self?.isForging = false @@ -66,7 +66,7 @@ public class TaquitoService { self.jsContext.evaluateScript("var forger = new taquito_local_forging.LocalForger();") } catch (let error) { - os_log("Error parsing dexter javascript file: %@", log: .kukaiCoreSwift, type: .error, "\(error)") + Logger.taquitoService.error("Error parsing dexter javascript file: \(error)") } } } @@ -97,7 +97,7 @@ public class TaquitoService { // Assign callback handlers for internal JS promise success and error states let forgeSuccessHandler: @convention(block) (String) -> Void = { [weak self] (result) in - os_log("JavascriptContext forge successful", log: .taquitoService, type: .default) + Logger.taquitoService.info("JavascriptContext forge successful") self?.isForging = false self?.lastForgeCompletionHandler = nil completion(Result.success(result)) @@ -107,7 +107,7 @@ public class TaquitoService { jsContext.setObject(forgeSuccessBlock, forKeyedSubscript: "forgeSuccessHandler" as (NSCopying & NSObjectProtocol)) let forgeErrorHandler: @convention(block) (String) -> Void = { [weak self] (result) in - os_log("JavascriptContext forge error: %@", log: .taquitoService, type: .error, result) + Logger.taquitoService.error("JavascriptContext forge error: \(result)") self?.isForging = false self?.lastForgeCompletionHandler = nil completion(Result.failure(KukaiError.unknown(withString: result))) @@ -131,7 +131,7 @@ public class TaquitoService { """) } catch (let error) { - os_log("JavascriptContext forge error: %@", log: .taquitoService, type: .error, "\(error)") + Logger.taquitoService.error("JavascriptContext forge error: \(error)") isForging = false lastForgeCompletionHandler = nil completion(Result.failure(KukaiError.internalApplicationError(error: error))) @@ -159,7 +159,7 @@ public class TaquitoService { // Assign callback handlers for internal JS promise success and error states let parseSuccessHandler: @convention(block) (String) -> Void = { [weak self] (result) in - os_log("JavascriptContext parse successful", log: .taquitoService, type: .default) + Logger.taquitoService.info("JavascriptContext parse successful") self?.lastParseCompletionHandler = nil self?.isParsing = false @@ -175,7 +175,7 @@ public class TaquitoService { jsContext.setObject(parseSuccessBlock, forKeyedSubscript: "parseSuccessHandler" as (NSCopying & NSObjectProtocol)) let parseErrorHandler: @convention(block) (String) -> Void = { [weak self] (result) in - os_log("JavascriptContext parse error: %@", log: .taquitoService, type: .error, result) + Logger.taquitoService.error("JavascriptContext parse error: \(result)") self?.lastParseCompletionHandler = nil self?.isParsing = false completion(Result.failure(KukaiError.unknown(withString: result))) diff --git a/Sources/KukaiCoreSwift/Services/TorusAuthService.swift b/Sources/KukaiCoreSwift/Services/TorusAuthService.swift index d422994b..ad366b60 100644 --- a/Sources/KukaiCoreSwift/Services/TorusAuthService.swift +++ b/Sources/KukaiCoreSwift/Services/TorusAuthService.swift @@ -200,7 +200,7 @@ public class TorusAuthService: NSObject { Task { @MainActor in do { let data = try await torus.triggerLogin() - os_log("Torus returned succesful data", log: .torus, type: .default) + Logger.torus.info("Torus returned succesful data") var username: String? = nil var userId: String? = nil @@ -244,14 +244,14 @@ public class TorusAuthService: NSObject { // Create wallet with details and return guard let privateKeyString = pk, let wallet = TorusWallet(authProvider: authType, username: username, userId: userId, profilePicture: profile, torusPrivateKey: privateKeyString) else { - os_log("Error torus contained no, or invlaid private key", log: .torus, type: .error) + Logger.torus.error("Error torus contained no, or invlaid private key") completion(Result.failure(KukaiError.internalApplicationError(error: TorusAuthError.invalidTorusResponse))) return } completion(Result.success(wallet)) } catch { - os_log("Error logging in: %@", log: .torus, type: .error, "\(error)") + Logger.torus.error("Error logging in: \(error)") completion(Result.failure(KukaiError.internalApplicationError(error: error))) return } @@ -310,7 +310,7 @@ public class TorusAuthService: NSObject { let pubY = data.y, let bytesX = Sodium.shared.utils.hex2bin(pubX), let bytesY = Sodium.shared.utils.hex2bin(pubY) else { - os_log("Finding address - no valid pub key x and y returned", log: .torus, type: .error) + Logger.torus.error("Finding address - no valid pub key x and y returned") completion(Result.failure(KukaiError.internalApplicationError(error: TorusAuthError.invalidTorusResponse))) return } @@ -326,7 +326,7 @@ public class TorusAuthService: NSObject { // Run Blake2b hashing on public key guard let hash = Sodium.shared.genericHash.hash(message: publicKey, outputLength: 20) else { - os_log("Finding address - generating hash failed", log: .torus, type: .error) + Logger.torus.error("Finding address - generating hash failed") completion(Result.failure(KukaiError.internalApplicationError(error: TorusAuthError.cryptoError))) return } @@ -336,7 +336,7 @@ public class TorusAuthService: NSObject { completion(Result.success(tz2Address)) } catch { - os_log("Error logging in: %@", log: .torus, type: .error, "\(error)") + Logger.torus.error("Error logging in: \(error)") completion(Result.failure(KukaiError.internalApplicationError(error: error))) return } @@ -419,7 +419,7 @@ extension TorusAuthService: ASAuthorizationControllerDelegate, ASAuthorizationCo let data = try await tdsdk.getAggregateTorusKey(verifier: verifierWrapper.aggregateVerifierName ?? "", verifierId: sub, idToken: token, subVerifierDetails: verifierWrapper.subverifier) guard let privateKeyString = data["privateKey"] as? String, let wallet = TorusWallet(authProvider: .apple, username: displayName, userId: userIdentifier, profilePicture: nil, torusPrivateKey: privateKeyString) else { - os_log("Error torus contained no, or invlaid private key", log: .torus, type: .error) + Logger.torus.error("Error torus contained no, or invlaid private key") self.createWalletCompletion(Result.failure(KukaiError.internalApplicationError(error: TorusAuthError.invalidTorusResponse))) return } diff --git a/Sources/KukaiCoreSwift/Services/WalletCacheService.swift b/Sources/KukaiCoreSwift/Services/WalletCacheService.swift index 64d1c2c9..2e8fd2c0 100644 --- a/Sources/KukaiCoreSwift/Services/WalletCacheService.swift +++ b/Sources/KukaiCoreSwift/Services/WalletCacheService.swift @@ -84,12 +84,12 @@ public class WalletCacheService { */ public func cache(wallet: T, childOfIndex: Int?, backedUp: Bool) -> Bool { guard let existingWallets = readWalletsFromDiskAndDecrypt(), existingWallets[wallet.address] == nil else { - os_log(.error, log: .walletCache, "cache - Unable to cache wallet, as can't decrypt existing wallets") + Logger.walletCache.error("cache - Unable to cache wallet, as can't decrypt existing wallets") return false } guard existingWallets[wallet.address] == nil else { - os_log(.error, log: .walletCache, "cache - Unable to cache wallet, as wallet has no address") + Logger.walletCache.error("cache - Unable to cache wallet, as wallet has no address") return false } @@ -99,7 +99,7 @@ public class WalletCacheService { var newMetadata = readMetadataFromDiskAndDecrypt() if let index = childOfIndex { if index >= newMetadata.hdWallets.count { - os_log(.error, log: .walletCache, "WalletCacheService metadata insertion issue. Requested to add to HDWallet at index \"%@\", when there are currently only \"%@\" items", index, newMetadata.hdWallets.count) + Logger.walletCache.error("WalletCacheService metadata insertion issue. Requested to add to HDWallet at index \"\(index)\", when there are currently only \"\(newMetadata.hdWallets.count)\" items") return false } @@ -149,7 +149,7 @@ public class WalletCacheService { */ public func deleteWallet(withAddress: String, parentIndex: Int?) -> Bool { guard let existingWallets = readWalletsFromDiskAndDecrypt() else { - os_log(.error, log: .walletCache, "Unable to fetch wallets") + Logger.walletCache.error("Unable to fetch wallets") return false } @@ -159,7 +159,7 @@ public class WalletCacheService { var newMetadata = readMetadataFromDiskAndDecrypt() if let hdWalletIndex = parentIndex { guard hdWalletIndex < newMetadata.hdWallets.count, let childIndex = newMetadata.hdWallets[hdWalletIndex].children.firstIndex(where: { $0.address == withAddress }) else { - os_log(.error, log: .walletCache, "Unable to locate wallet") + Logger.walletCache.error("Unable to locate wallet") return false } @@ -187,7 +187,7 @@ public class WalletCacheService { let _ = newMetadata.ledgerWallets.remove(at: index) } else { - os_log(.error, log: .walletCache, "Unable to locate wallet") + Logger.walletCache.error("Unable to locate wallet") return false } } @@ -211,7 +211,7 @@ public class WalletCacheService { */ public func fetchWallet(forAddress address: String) -> Wallet? { guard let cacheItems = readWalletsFromDiskAndDecrypt() else { - os_log(.error, log: .walletCache, "Unable to read wallet items") + Logger.walletCache.error("Unable to read wallet items") return nil } @@ -289,14 +289,14 @@ public class WalletCacheService { let plaintext = String(data: jsonData, encoding: .utf8), let ciphertextData = try? encrypt(plaintext), DiskService.write(data: ciphertextData, toFileName: WalletCacheService.walletCacheFileName) else { - os_log(.error, log: .walletCache, "encryptAndWriteToDisk - Unable to save wallet items") + Logger.walletCache.error("encryptAndWriteToDisk - Unable to save wallet items") return false } return true } catch (let error) { - os_log(.error, log: .walletCache, "encryptAndWriteToDisk - Unable to save wallet items: %@", "\(error)") + Logger.walletCache.error("encryptAndWriteToDisk - Unable to save wallet items: \(error)") return false } } @@ -307,14 +307,14 @@ public class WalletCacheService { */ public func readWalletsFromDiskAndDecrypt() -> [String: Wallet]? { guard let data = DiskService.readData(fromFileName: WalletCacheService.walletCacheFileName) else { - os_log(.default, log: .walletCache, "readWalletsFromDiskAndDecrypt - no cache file found, returning empty") + Logger.walletCache.info("readWalletsFromDiskAndDecrypt - no cache file found, returning empty") return [:] // No such file } guard loadOrCreateKeys(), let plaintext = try? decrypt(data), let plaintextData = plaintext.data(using: .utf8) else { - os_log(.error, log: .walletCache, "readWalletsFromDiskAndDecrypt - Unable to read wallet items") + Logger.walletCache.error("readWalletsFromDiskAndDecrypt - Unable to read wallet items") return nil } @@ -324,13 +324,13 @@ public class WalletCacheService { /// Once we have that, we simply call `JSONDecode` for each obj, with the correct class and put in an array var wallets: [String: Wallet] = [:] guard let jsonDict = try JSONSerialization.jsonObject(with: plaintextData, options: .allowFragments) as? [String: [String: Any]] else { - os_log(.error, log: .walletCache, "readWalletsFromDiskAndDecrypt - JSON did not conform to expected format") + Logger.walletCache.error("readWalletsFromDiskAndDecrypt - JSON did not conform to expected format") return [:] } for jsonObj in jsonDict.values { guard let type = WalletType(rawValue: (jsonObj["type"] as? String) ?? "") else { - os_log("readWalletsFromDiskAndDecrypt - Unable to parse wallet object of type: %@", log: .walletCache, type: .error, (jsonObj["type"] as? String) ?? "") + Logger.walletCache.error("readWalletsFromDiskAndDecrypt - Unable to parse wallet object of type: \((jsonObj["type"] as? String) ?? "")") continue } @@ -358,7 +358,7 @@ public class WalletCacheService { return wallets } catch (let error) { - os_log(.error, log: .walletCache, "readWalletsFromDiskAndDecrypt - Unable to read wallet items: %@", "\(error)") + Logger.walletCache.error("readWalletsFromDiskAndDecrypt - Unable to read wallet items: \(error)") return nil } } @@ -375,14 +375,14 @@ public class WalletCacheService { let plaintext = String(data: jsonData, encoding: .utf8), let ciphertextData = try? encrypt(plaintext), DiskService.write(data: ciphertextData, toFileName: WalletCacheService.metadataCacheFileName) else { - os_log(.error, log: .walletCache, "encryptAndWriteMetadataToDisk - Unable to save wallet items") + Logger.walletCache.error("encryptAndWriteMetadataToDisk - Unable to save wallet items") return false } return true } catch (let error) { - os_log(.error, log: .walletCache, "encryptAndWriteToDisk - Unable to save wallet items: %@", "\(error)") + Logger.walletCache.error("encryptAndWriteToDisk - Unable to save wallet items: \(error)") return false } } @@ -394,14 +394,14 @@ public class WalletCacheService { let emptyWalletList = WalletMetadataList(socialWallets: [], hdWallets: [], linearWallets: [], ledgerWallets: [], watchWallets: []) guard let data = DiskService.readData(fromFileName: WalletCacheService.metadataCacheFileName) else { - os_log(.default, log: .walletCache, "readMetadataFromDiskAndDecrypt - no cache file found, returning empty") + Logger.walletCache.info("readMetadataFromDiskAndDecrypt - no cache file found, returning empty") return emptyWalletList // No such file } guard loadOrCreateKeys(), let plaintext = try? decrypt(data), let plaintextData = plaintext.data(using: .utf8) else { - os_log(.error, log: .walletCache, "readMetadataFromDiskAndDecrypt - Unable to read wallet items") + Logger.walletCache.error("readMetadataFromDiskAndDecrypt - Unable to read wallet items") return emptyWalletList } @@ -410,7 +410,7 @@ public class WalletCacheService { return metadata } catch (let error) { - os_log(.error, log: .walletCache, "readMetadataFromDiskAndDecrypt - Unable to read wallet items: %@", "\(error)") + Logger.walletCache.error("readMetadataFromDiskAndDecrypt - Unable to read wallet items: \(error)") return emptyWalletList } } @@ -430,7 +430,7 @@ extension WalletCacheService { /// Can't use the secure enclave when running unit tests in SPM. For now, hacky workaround to just just mock ones if Thread.current.isRunningXCTest { - os_log(.error, log: .walletCache, "loadOrCreateKeys - loading mocks") + Logger.walletCache.error("loadOrCreateKeys - loading mocks") let keyTuple = loadMockKeys() self.publicKey = keyTuple.public self.privateKey = keyTuple.private @@ -444,19 +444,19 @@ extension WalletCacheService { if let key = try loadKey() { privateKey = key publicKey = SecKeyCopyPublicKey(key) - os_log(.default, log: .walletCache, "loadOrCreateKeys - loaded") + Logger.walletCache.info("loadOrCreateKeys - loaded") } else { let keyTuple = try createKeys() self.publicKey = keyTuple.public self.privateKey = keyTuple.private - os_log(.default, log: .walletCache, "loadOrCreateKeys - created") + Logger.walletCache.info("loadOrCreateKeys - created") } return true } catch (let error) { - os_log(.error, log: .walletCache, "loadOrCreateKeys - Unable to load or create keys: %@", "\(error)") + Logger.walletCache.error("loadOrCreateKeys - Unable to load or create keys: \(error)") return false } } @@ -479,11 +479,11 @@ extension WalletCacheService { let privateKeyAccessControl: SecAccessControlCreateFlags = !CurrentDevice.isSimulator ? [.privateKeyUsage] : [] guard let privateKeyAccess = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, privateKeyAccessControl, &error) else { if let err = error { - os_log(.error, log: .walletCache, "createKeys - createWithFlags returned error") + Logger.walletCache.error("createKeys - createWithFlags returned error") throw err.takeRetainedValue() as Error } else { - os_log(.error, log: .walletCache, "createKeys - createWithFlags failed for unknown reason") + Logger.walletCache.error("createKeys - createWithFlags failed for unknown reason") throw WalletCacheError.unableToAccessEnclaveOrKeychain } } @@ -505,27 +505,27 @@ extension WalletCacheService { // If not simulator, use secure encalve if !CurrentDevice.isSimulator { - os_log(.default, log: .keychain, "createKeys - Using secure enclave") + Logger.walletCache.info("createKeys - Using secure enclave") commonKeyAttributes[kSecAttrTokenID as String] = kSecAttrTokenIDSecureEnclave commonKeyAttributes[kSecPrivateKeyAttrs as String] = privateKeyAttributes privateKeyAttributes[kSecAttrAccessControl as String] = privateKeyAccessControl } else { - os_log(.default, log: .keychain, "createKeys - unable to use secure enclave") + Logger.walletCache.info("createKeys - unable to use secure enclave") } guard let privateKey = SecKeyCreateRandomKey(commonKeyAttributes as CFDictionary, &error) else { if let err = error { - os_log(.default, log: .keychain, "createKeys - createRandom returned error") + Logger.walletCache.info("createKeys - createRandom returned error") throw err.takeRetainedValue() as Error } else { - os_log(.default, log: .keychain, "createKeys - createRandom errored for unknown reason") + Logger.walletCache.info("createKeys - createRandom errored for unknown reason") throw WalletCacheError.unableToCreatePrivateKey } } guard let publicKey = SecKeyCopyPublicKey(privateKey) else { - os_log(.default, log: .keychain, "createKeys - copy public failed") + Logger.walletCache.info("createKeys - copy public failed") throw WalletCacheError.unableToCreatePrivateKey } @@ -582,20 +582,20 @@ extension WalletCacheService { // If not simulator, use secure encalve if !CurrentDevice.isSimulator { - os_log(.default, log: .walletCache, "loadKey - Using secure enclave") + Logger.walletCache.info("loadKey - Using secure enclave") query[kSecAttrTokenID as String] = kSecAttrTokenIDSecureEnclave } else { - os_log(.default, log: .walletCache, "loadKey - unable to use secure enclave") + Logger.walletCache.info("loadKey - unable to use secure enclave") } var key: CFTypeRef? if SecItemCopyMatching(query as CFDictionary, &key) == errSecSuccess { - os_log(.default, log: .walletCache, "loadKey - returning key") + Logger.walletCache.info("loadKey - returning key") return (key as! SecKey) } - os_log(.error, log: .walletCache, "loadKey - returning nil") + Logger.walletCache.error("loadKey - returning nil") return nil } @@ -607,7 +607,7 @@ extension WalletCacheService { let result = SecItemDelete(query as CFDictionary) if result != errSecSuccess { - os_log(.error, log: .keychain, "Error removing keys. OSSatus - %@", "\(result)") + Logger.walletCache.error("Error removing keys. OSSatus - ˘\(result)") throw WalletCacheError.unableToDeleteKey } } @@ -620,12 +620,12 @@ extension WalletCacheService { */ public func encrypt(_ string: String) throws -> Data { guard let data = string.data(using: .utf8) else { - os_log(.error, log: .walletCache, "encrypt - can't turn string to data") + Logger.walletCache.error("encrypt - can't turn string to data") throw WalletCacheError.unableToParseAsUTF8Data } guard let pubKey = self.publicKey, SecKeyIsAlgorithmSupported(pubKey, .encrypt, WalletCacheService.encryptionAlgorithm) else { - os_log(.error, log: .walletCache, "encrypt - can't find public key") + Logger.walletCache.error("encrypt - can't find public key") throw WalletCacheError.noPublicKeyFound } @@ -634,11 +634,11 @@ extension WalletCacheService { //guard let cipherText = SecKeyCreateEncryptedData(pubKey, .rsaEncryptionOAEPSHA512AESGCM, data as CFData, &error) as Data? else { guard let cipherText = SecKeyCreateEncryptedData(pubKey, WalletCacheService.encryptionAlgorithm, data as CFData, &error) as Data? else { if let err = error { - os_log(.error, log: .walletCache, "encrypt - createEncryptedData failed with error") + Logger.walletCache.error("encrypt - createEncryptedData failed with error") throw err.takeRetainedValue() as Error } else { - os_log(.error, log: .walletCache, "encrypt - createEncryptedData failed with unknown error") + Logger.walletCache.error("encrypt - createEncryptedData failed with unknown error") throw WalletCacheError.unableToEncrypt } } @@ -655,7 +655,7 @@ extension WalletCacheService { public func decrypt(_ cipherText: Data) throws -> String { guard let privateKey = privateKey, SecKeyIsAlgorithmSupported(privateKey, .decrypt, WalletCacheService.encryptionAlgorithm) else { - os_log(.error, log: .walletCache, "decrypt - can't find key") + Logger.walletCache.error("decrypt - can't find key") throw WalletCacheError.noPrivateKeyFound } @@ -663,11 +663,11 @@ extension WalletCacheService { guard let clearText = SecKeyCreateDecryptedData(privateKey, WalletCacheService.encryptionAlgorithm, cipherText as CFData, &error) as Data?, let textAsString = String(data: clearText, encoding: .utf8) else { if let err = error { - os_log(.error, log: .walletCache, "decrypt - decryptData failed with error") + Logger.walletCache.error("decrypt - decryptData failed with error") throw err.takeRetainedValue() as Error } else { - os_log(.error, log: .walletCache, "decrypt - decryptData failed for unknown reason") + Logger.walletCache.error("decrypt - decryptData failed for unknown reason") throw WalletCacheError.unableToDecrypt }