diff --git a/Examples/UserManagement/Supabase.swift b/Examples/UserManagement/Supabase.swift index fdc04748..9b132003 100644 --- a/Examples/UserManagement/Supabase.swift +++ b/Examples/UserManagement/Supabase.swift @@ -6,13 +6,31 @@ // import Foundation +import OSLog import Supabase let supabase = SupabaseClient( supabaseURL: URL(string: "https://PROJECT_ID.supabase.co")!, supabaseKey: "YOUR_SUPABASE_ANON_KEY", - options: .init(auth: .init(storage: KeychainLocalStorage( - service: "supabase.gotrue.swift", - accessGroup: nil - ))) + options: .init( + auth: .init( + storage: KeychainLocalStorage(service: "supabase.gotrue.swift", accessGroup: nil) + ), + global: .init(logger: AppLogger()) + ) ) + +struct AppLogger: SupabaseLogger { + let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "supabase") + + func log(message: SupabaseLogMessage) { + switch message.level { + case .verbose: + logger.log(level: .info, "\(message.description)") + case .debug: + logger.log(level: .debug, "\(message.description)") + case .warning, .error: + logger.log(level: .error, "\(message.description)") + } + } +} diff --git a/Package.resolved b/Package.resolved index 5c8656bb..4ac5291a 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,14 @@ { "pins" : [ + { + "identity" : "keychainaccess", + "kind" : "remoteSourceControl", + "location" : "https://github.com/kishikawakatsumi/KeychainAccess", + "state" : { + "revision" : "84e546727d66f1adc5439debad16270d0fdd04e7", + "version" : "4.2.2" + } + }, { "identity" : "swift-concurrency-extras", "kind" : "remoteSourceControl", @@ -47,4 +56,4 @@ } ], "version" : 2 -} \ No newline at end of file +} diff --git a/Sources/Auth/AuthClient.swift b/Sources/Auth/AuthClient.swift index e7cfdf97..35521872 100644 --- a/Sources/Auth/AuthClient.swift +++ b/Sources/Auth/AuthClient.swift @@ -16,7 +16,7 @@ public actor AuthClient { public var headers: [String: String] public let flowType: AuthFlowType public let localStorage: AuthLocalStorage - public let loggingConfiguration: SupabaseLoggingConfiguration + public let logger: SupabaseLogger? public let encoder: JSONEncoder public let decoder: JSONDecoder public let fetch: FetchHandler @@ -28,7 +28,7 @@ public actor AuthClient { /// - headers: Custom headers to be included in requests. /// - flowType: The authentication flow type. /// - localStorage: The storage mechanism for local data. - /// - loggingConfiguration: The configuration used for the internal logger. + /// - logger: The logger to use. /// - encoder: The JSON encoder to use for encoding requests. /// - decoder: The JSON decoder to use for decoding responses. /// - fetch: The asynchronous fetch handler for network requests. @@ -37,7 +37,7 @@ public actor AuthClient { headers: [String: String] = [:], flowType: AuthFlowType = Configuration.defaultFlowType, localStorage: AuthLocalStorage, - loggingConfiguration: SupabaseLoggingConfiguration = SupabaseLoggingConfiguration(), + logger: SupabaseLogger? = nil, encoder: JSONEncoder = AuthClient.Configuration.jsonEncoder, decoder: JSONDecoder = AuthClient.Configuration.jsonDecoder, fetch: @escaping FetchHandler = { try await URLSession.shared.data(for: $0) } @@ -48,7 +48,7 @@ public actor AuthClient { self.headers = headers self.flowType = flowType self.localStorage = localStorage - self.loggingConfiguration = loggingConfiguration + self.logger = logger self.encoder = encoder self.decoder = decoder self.fetch = fetch @@ -79,7 +79,7 @@ public actor AuthClient { Dependencies.current.value!.currentDate } - private var logger: SupabaseLogger { + private var logger: SupabaseLogger? { Dependencies.current.value!.logger } @@ -102,7 +102,7 @@ public actor AuthClient { /// - headers: Custom headers to be included in requests. /// - flowType: The authentication flow type.. /// - localStorage: The storage mechanism for local data.. - /// - loggingConfiguration: The configuration used for the internal logger. + /// - logger: The logger to use. /// - encoder: The JSON encoder to use for encoding requests. /// - decoder: The JSON decoder to use for decoding responses. /// - fetch: The asynchronous fetch handler for network requests. @@ -111,7 +111,7 @@ public actor AuthClient { headers: [String: String] = [:], flowType: AuthFlowType = AuthClient.Configuration.defaultFlowType, localStorage: AuthLocalStorage, - loggingConfiguration: SupabaseLoggingConfiguration = SupabaseLoggingConfiguration(), + logger: SupabaseLogger? = nil, encoder: JSONEncoder = AuthClient.Configuration.jsonEncoder, decoder: JSONDecoder = AuthClient.Configuration.jsonDecoder, fetch: @escaping FetchHandler = { try await URLSession.shared.data(for: $0) } @@ -122,7 +122,7 @@ public actor AuthClient { headers: headers, flowType: flowType, localStorage: localStorage, - loggingConfiguration: loggingConfiguration, + logger: logger, encoder: encoder, decoder: decoder, fetch: fetch @@ -135,7 +135,10 @@ public actor AuthClient { /// - Parameters: /// - configuration: The client configuration. public init(configuration: Configuration) { - let api = APIClient.live(http: HTTPClient(fetchHandler: configuration.fetch)) + let api = APIClient.live(http: HTTPClient( + logger: configuration.logger, + fetchHandler: configuration.fetch + )) self.init( configuration: configuration, @@ -144,10 +147,7 @@ public actor AuthClient { api: api, eventEmitter: .live, sessionStorage: .live, - logger: SupabaseLogger( - system: "AuthClient", - configuration: configuration.loggingConfiguration - ) + logger: configuration.logger ) } @@ -159,7 +159,7 @@ public actor AuthClient { api: APIClient, eventEmitter: EventEmitter, sessionStorage: SessionStorage, - logger: SupabaseLogger + logger: SupabaseLogger? ) { mfa = AuthMFA() @@ -189,11 +189,11 @@ public actor AuthClient { session: Session? )> { let (id, stream) = eventEmitter.attachListener() - logger.debug("auth state change listener with id '\(id.uuidString)' attached.") + logger?.debug("auth state change listener with id '\(id.uuidString)' attached.") Task { [id] in await emitInitialSession(forStreamWithID: id) - logger.debug("initial session for listener with id '\(id.uuidString)' emitted.") + logger?.debug("initial session for listener with id '\(id.uuidString)' emitted.") } return stream diff --git a/Sources/Auth/Internal/Dependencies.swift b/Sources/Auth/Internal/Dependencies.swift index 4bded161..99722b0b 100644 --- a/Sources/Auth/Internal/Dependencies.swift +++ b/Sources/Auth/Internal/Dependencies.swift @@ -13,5 +13,5 @@ struct Dependencies: Sendable { var sessionRefresher: SessionRefresher var codeVerifierStorage: CodeVerifierStorage var currentDate: @Sendable () -> Date = { Date() } - var logger: SupabaseLogger + var logger: SupabaseLogger? } diff --git a/Sources/PostgREST/PostgrestBuilder.swift b/Sources/PostgREST/PostgrestBuilder.swift index b09ee1b9..d2bcea42 100644 --- a/Sources/PostgREST/PostgrestBuilder.swift +++ b/Sources/PostgREST/PostgrestBuilder.swift @@ -26,7 +26,7 @@ public class PostgrestBuilder: @unchecked Sendable { request: Request ) { self.configuration = configuration - http = HTTPClient(fetchHandler: configuration.fetch) + http = HTTPClient(logger: configuration.logger, fetchHandler: configuration.fetch) mutableState = LockIsolated( MutableState( @@ -74,7 +74,7 @@ public class PostgrestBuilder: @unchecked Sendable { do { return try configuration.decoder.decode(T.self, from: data) } catch { - configuration.logger.error("Fail to decode type '\(T.self) with error: \(error)") + configuration.logger?.error("Fail to decode type '\(T.self) with error: \(error)") throw error } } diff --git a/Sources/PostgREST/PostgrestClient.swift b/Sources/PostgREST/PostgrestClient.swift index e0174bfb..f171cc0a 100644 --- a/Sources/PostgREST/PostgrestClient.swift +++ b/Sources/PostgREST/PostgrestClient.swift @@ -20,14 +20,14 @@ public actor PostgrestClient { public var encoder: JSONEncoder public var decoder: JSONDecoder - let logger: SupabaseLogger + let logger: SupabaseLogger? /// Initializes a new configuration for the PostgREST client. /// - Parameters: /// - url: The URL of the PostgREST server. /// - schema: The schema to use. /// - headers: The headers to include in requests. - /// - loggingConfiguration: The configuration used for the internal logger. + /// - logger: The logger to use. /// - fetch: The fetch handler to use for requests. /// - encoder: The JSONEncoder to use for encoding. /// - decoder: The JSONDecoder to use for decoding. @@ -35,7 +35,7 @@ public actor PostgrestClient { url: URL, schema: String? = nil, headers: [String: String] = [:], - loggingConfiguration: SupabaseLoggingConfiguration = SupabaseLoggingConfiguration(), + logger: SupabaseLogger? = nil, fetch: @escaping FetchHandler = { try await URLSession.shared.data(for: $0) }, encoder: JSONEncoder = PostgrestClient.Configuration.jsonEncoder, decoder: JSONDecoder = PostgrestClient.Configuration.jsonDecoder @@ -43,11 +43,10 @@ public actor PostgrestClient { self.url = url self.schema = schema self.headers = headers + self.logger = logger self.fetch = fetch self.encoder = encoder self.decoder = decoder - - logger = SupabaseLogger(system: "Postgrest", configuration: loggingConfiguration) } } @@ -66,7 +65,7 @@ public actor PostgrestClient { /// - url: The URL of the PostgREST server. /// - schema: The schema to use. /// - headers: The headers to include in requests. - /// - loggingConfiguration: The configuration used for the internal logger. + /// - logger: The logger to use. /// - session: The URLSession to use for requests. /// - encoder: The JSONEncoder to use for encoding. /// - decoder: The JSONDecoder to use for decoding. @@ -74,7 +73,7 @@ public actor PostgrestClient { url: URL, schema: String? = nil, headers: [String: String] = [:], - loggingConfiguration: SupabaseLoggingConfiguration = SupabaseLoggingConfiguration(), + logger: SupabaseLogger? = nil, fetch: @escaping FetchHandler = { try await URLSession.shared.data(for: $0) }, encoder: JSONEncoder = PostgrestClient.Configuration.jsonEncoder, decoder: JSONDecoder = PostgrestClient.Configuration.jsonDecoder @@ -84,7 +83,7 @@ public actor PostgrestClient { url: url, schema: schema, headers: headers, - loggingConfiguration: loggingConfiguration, + logger: logger, fetch: fetch, encoder: encoder, decoder: decoder diff --git a/Sources/Realtime/RealtimeClient.swift b/Sources/Realtime/RealtimeClient.swift index 3f9d1659..9ab9fe31 100644 --- a/Sources/Realtime/RealtimeClient.swift +++ b/Sources/Realtime/RealtimeClient.swift @@ -186,14 +186,16 @@ public class RealtimeClient: PhoenixTransportDelegate { _ endPoint: String, headers: [String: String] = [:], params: Payload? = nil, - vsn: String = Defaults.vsn + vsn: String = Defaults.vsn, + logger: SupabaseLogger? = nil ) { self.init( endPoint: endPoint, headers: headers, transport: { url in URLSessionTransport(url: url) }, paramsClosure: { params }, - vsn: vsn + vsn: vsn, + logger: logger ) } @@ -202,14 +204,16 @@ public class RealtimeClient: PhoenixTransportDelegate { _ endPoint: String, headers: [String: String] = [:], paramsClosure: PayloadClosure?, - vsn: String = Defaults.vsn + vsn: String = Defaults.vsn, + logger: SupabaseLogger? = nil ) { self.init( endPoint: endPoint, headers: headers, transport: { url in URLSessionTransport(url: url) }, paramsClosure: paramsClosure, - vsn: vsn + vsn: vsn, + logger: logger ) } @@ -218,7 +222,8 @@ public class RealtimeClient: PhoenixTransportDelegate { headers: [String: String] = [:], transport: @escaping ((URL) -> PhoenixTransport), paramsClosure: PayloadClosure? = nil, - vsn: String = Defaults.vsn + vsn: String = Defaults.vsn, + logger: SupabaseLogger? = nil ) { self.transport = transport self.paramsClosure = paramsClosure @@ -230,7 +235,7 @@ public class RealtimeClient: PhoenixTransportDelegate { headers["X-Client-Info"] = "realtime-swift/\(version)" } self.headers = headers - http = HTTPClient(fetchHandler: { try await URLSession.shared.data(for: $0) }) + http = HTTPClient(logger: logger, fetchHandler: { try await URLSession.shared.data(for: $0) }) let params = paramsClosure?() if let jwt = (params?["Authorization"] as? String)?.split(separator: " ").last { diff --git a/Sources/Storage/StorageApi.swift b/Sources/Storage/StorageApi.swift index 57b115bf..69f3421f 100644 --- a/Sources/Storage/StorageApi.swift +++ b/Sources/Storage/StorageApi.swift @@ -16,7 +16,7 @@ public class StorageApi: @unchecked Sendable { configuration.headers["X-Client-Info"] = "storage-swift/\(version)" } self.configuration = configuration - http = HTTPClient(fetchHandler: configuration.session.fetch) + http = HTTPClient(logger: configuration.logger, fetchHandler: configuration.session.fetch) } @discardableResult diff --git a/Sources/Storage/SupabaseStorage.swift b/Sources/Storage/SupabaseStorage.swift index 1b7c283c..9fc2d5f5 100644 --- a/Sources/Storage/SupabaseStorage.swift +++ b/Sources/Storage/SupabaseStorage.swift @@ -1,3 +1,4 @@ +import _Helpers import Foundation public struct StorageClientConfiguration { @@ -6,19 +7,22 @@ public struct StorageClientConfiguration { public let encoder: JSONEncoder public let decoder: JSONDecoder public let session: StorageHTTPSession + public let logger: SupabaseLogger? public init( url: URL, headers: [String: String], encoder: JSONEncoder = .defaultStorageEncoder, decoder: JSONDecoder = .defaultStorageDecoder, - session: StorageHTTPSession = .init() + session: StorageHTTPSession = .init(), + logger: SupabaseLogger? = nil ) { self.url = url self.headers = headers self.encoder = encoder self.decoder = decoder self.session = session + self.logger = logger } } diff --git a/Sources/Supabase/SupabaseClient.swift b/Sources/Supabase/SupabaseClient.swift index 6a128cd1..087e58d7 100644 --- a/Sources/Supabase/SupabaseClient.swift +++ b/Sources/Supabase/SupabaseClient.swift @@ -11,6 +11,10 @@ import Foundation import FoundationNetworking #endif +public typealias SupabaseLogger = _Helpers.SupabaseLogger +public typealias SupabaseLogLevel = _Helpers.SupabaseLogLevel +public typealias SupabaseLogMessage = _Helpers.SupabaseLogMessage + let version = _Helpers.version /// Supabase Client. @@ -31,7 +35,7 @@ public final class SupabaseClient: @unchecked Sendable { url: databaseURL, schema: options.db.schema, headers: defaultHeaders, - loggingConfiguration: options.global.loggingConfiguration, + logger: options.global.logger, fetch: fetchWithAuth, encoder: options.db.encoder, decoder: options.db.decoder @@ -42,7 +46,8 @@ public final class SupabaseClient: @unchecked Sendable { configuration: StorageClientConfiguration( url: storageURL, headers: defaultHeaders, - session: StorageHTTPSession(fetch: fetchWithAuth, upload: uploadWithAuth) + session: StorageHTTPSession(fetch: fetchWithAuth, upload: uploadWithAuth), + logger: options.global.logger ) ) @@ -94,7 +99,7 @@ public final class SupabaseClient: @unchecked Sendable { headers: defaultHeaders, flowType: options.auth.flowType, localStorage: options.auth.storage, - loggingConfiguration: options.global.loggingConfiguration, + logger: options.global.logger, encoder: options.auth.encoder, decoder: options.auth.decoder, fetch: { @@ -106,7 +111,8 @@ public final class SupabaseClient: @unchecked Sendable { realtime = RealtimeClient( supabaseURL.appendingPathComponent("/realtime/v1").absoluteString, headers: defaultHeaders, - params: defaultHeaders + params: defaultHeaders, + logger: options.global.logger ) listenForAuthEvents() diff --git a/Sources/Supabase/Types.swift b/Sources/Supabase/Types.swift index 06cb99fc..5fba375d 100644 --- a/Sources/Supabase/Types.swift +++ b/Sources/Supabase/Types.swift @@ -68,17 +68,17 @@ public struct SupabaseClientOptions: Sendable { /// A session to use for making requests, defaults to `URLSession.shared`. public let session: URLSession - /// The log configuration to use across all Supabase sub-packages. - public let loggingConfiguration: SupabaseLoggingConfiguration + /// The logger to use across all Supabase sub-packages. + public let logger: SupabaseLogger? public init( headers: [String: String] = [:], session: URLSession = .shared, - loggingConfiguration: SupabaseLoggingConfiguration = SupabaseLoggingConfiguration() + logger: SupabaseLogger? = nil ) { self.headers = headers self.session = session - self.loggingConfiguration = loggingConfiguration + self.logger = logger } } diff --git a/Sources/_Helpers/Request.swift b/Sources/_Helpers/Request.swift index 3fc13be2..ca9c20e5 100644 --- a/Sources/_Helpers/Request.swift +++ b/Sources/_Helpers/Request.swift @@ -8,15 +8,20 @@ import Foundation public struct HTTPClient: Sendable { public typealias FetchHandler = @Sendable (URLRequest) async throws -> (Data, URLResponse) + let logger: SupabaseLogger? let fetchHandler: FetchHandler - public init(fetchHandler: @escaping FetchHandler) { + public init(logger: SupabaseLogger?, fetchHandler: @escaping FetchHandler) { + self.logger = logger self.fetchHandler = fetchHandler } public func fetch(_ request: Request, baseURL: URL) async throws -> Response { + let id = UUID().uuidString let urlRequest = try request.urlRequest(withBaseURL: baseURL) + logger?.verbose("Request [\(id)]: \(urlRequest)") let (data, response) = try await fetchHandler(urlRequest) + logger?.verbose("Response [\(id)]: \(response)") guard let httpResponse = response as? HTTPURLResponse else { throw URLError(.badServerResponse) diff --git a/Sources/_Helpers/SupabaseLogger.swift b/Sources/_Helpers/SupabaseLogger.swift new file mode 100644 index 00000000..d181a696 --- /dev/null +++ b/Sources/_Helpers/SupabaseLogger.swift @@ -0,0 +1,103 @@ +import Foundation + +public enum SupabaseLogLevel: Int, Codable, CustomStringConvertible, Sendable { + case verbose + case debug + case warning + case error + + public var description: String { + switch self { + case .verbose: "verbose" + case .debug: "debug" + case .warning: "warning" + case .error: "error" + } + } +} + +public struct SupabaseLogMessage: Codable, CustomStringConvertible { + public let system: String + public let level: SupabaseLogLevel + public let message: String + public let fileID: String + public let function: String + public let line: UInt + public let timestamp: TimeInterval + + public var description: String { + let date = iso8601Formatter.string(from: Date(timeIntervalSince1970: timestamp)) + let file = fileID.split(separator: ".", maxSplits: 1).first.map(String.init) ?? fileID + return "\(date) [\(level)] [\(system)] [\(file).\(function):\(line)] \(message)" + } +} + +private let iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime] + return formatter +}() + +public protocol SupabaseLogger: Sendable { + func log(message: SupabaseLogMessage) +} + +extension SupabaseLogger { + public func log( + _ level: SupabaseLogLevel, + message: @autoclosure () -> String, + fileID: StaticString = #fileID, + function: StaticString = #function, + line: UInt = #line + ) { + let system = "\(fileID)".split(separator: "/").first ?? "" + + log( + message: SupabaseLogMessage( + system: "\(system)", + level: level, + message: message(), + fileID: "\(fileID)", + function: "\(function)", + line: line, + timestamp: Date().timeIntervalSince1970 + ) + ) + } + + public func verbose( + _ message: @autoclosure () -> String, + fileID: StaticString = #fileID, + function: StaticString = #function, + line: UInt = #line + ) { + log(.verbose, message: message(), fileID: fileID, function: function, line: line) + } + + public func debug( + _ message: @autoclosure () -> String, + fileID: StaticString = #fileID, + function: StaticString = #function, + line: UInt = #line + ) { + log(.debug, message: message(), fileID: fileID, function: function, line: line) + } + + public func warning( + _ message: @autoclosure () -> String, + fileID: StaticString = #fileID, + function: StaticString = #function, + line: UInt = #line + ) { + log(.warning, message: message(), fileID: fileID, function: function, line: line) + } + + public func error( + _ message: @autoclosure () -> String, + fileID: StaticString = #fileID, + function: StaticString = #function, + line: UInt = #line + ) { + log(.error, message: message(), fileID: fileID, function: function, line: line) + } +} diff --git a/Sources/_Helpers/SupabaseLogger/Entry.swift b/Sources/_Helpers/SupabaseLogger/Entry.swift deleted file mode 100644 index 072e752d..00000000 --- a/Sources/_Helpers/SupabaseLogger/Entry.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// Entry.swift -// -// -// Created by Guilherme Souza on 15/01/24. -// - -import Foundation - -extension SupabaseLogger { - struct Entry: Codable, CustomStringConvertible { - let system: String - let level: SupabaseLogLevel - let message: String - let fileID: String - let function: String - let line: UInt - let timestamp: TimeInterval - - var description: String { - let date = iso8601Formatter.string(from: Date(timeIntervalSince1970: timestamp)) - let file = fileID.split(separator: ".", maxSplits: 1).first.map(String.init) ?? fileID - return "\(date) [\(level)] [\(system)] [\(file).\(function):\(line)] \(message)" - } - } -} - -private let iso8601Formatter: ISO8601DateFormatter = { - let formatter = ISO8601DateFormatter() - formatter.formatOptions = [.withInternetDateTime] - return formatter -}() diff --git a/Sources/_Helpers/SupabaseLogger/SupabaseLogHandler.swift b/Sources/_Helpers/SupabaseLogger/SupabaseLogHandler.swift deleted file mode 100644 index bceb5155..00000000 --- a/Sources/_Helpers/SupabaseLogger/SupabaseLogHandler.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// SupabaseLogHandler.swift -// -// -// Created by Guilherme Souza on 15/01/24. -// - -import ConcurrencyExtras -import Foundation - -protocol SupabaseLogHandler: Sendable { - func didLog(_ entry: SupabaseLogger.Entry) -} - -final class DefaultSupabaseLogHandler: SupabaseLogHandler { - private static let cachedInstances = LockIsolated([URL: DefaultSupabaseLogHandler]()) - static func instance(for url: URL) -> DefaultSupabaseLogHandler { - if let instance = cachedInstances[url] { - return instance - } - - let instance = cachedInstances.withValue { - let instance = try! DefaultSupabaseLogHandler(localFile: url) - $0[url] = instance - return instance - } - - return instance - } - - let fileHandle: FileHandle - - private init(localFile url: URL) throws { - if !FileManager.default.fileExists(atPath: url.path) { - FileManager.default.createFile(atPath: url.path, contents: nil) - } - - fileHandle = try FileHandle(forWritingTo: url) - fileHandle.seekToEndOfFile() - } - - func didLog(_ entry: SupabaseLogger.Entry) { - let logLine = "\(entry.description)\n" - guard let data = logLine.data(using: .utf8) else { return } - fileHandle.write(data) - - #if DEBUG - print(entry.description) - #endif - } -} diff --git a/Sources/_Helpers/SupabaseLogger/SupabaseLogLevel.swift b/Sources/_Helpers/SupabaseLogger/SupabaseLogLevel.swift deleted file mode 100644 index bc88d84b..00000000 --- a/Sources/_Helpers/SupabaseLogger/SupabaseLogLevel.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// SupabaseLogLevel.swift -// -// -// Created by Guilherme Souza on 15/01/24. -// - -import Foundation - -public enum SupabaseLogLevel: Int, Codable, CustomStringConvertible, Sendable { - case debug - case warning - case error - - public var description: String { - switch self { - case .debug: - "debug" - case .warning: - "warning" - case .error: - "error" - } - } -} diff --git a/Sources/_Helpers/SupabaseLogger/SupabaseLogger.swift b/Sources/_Helpers/SupabaseLogger/SupabaseLogger.swift deleted file mode 100644 index dd0ac20a..00000000 --- a/Sources/_Helpers/SupabaseLogger/SupabaseLogger.swift +++ /dev/null @@ -1,90 +0,0 @@ -import Foundation - -public struct SupabaseLoggingConfiguration: Sendable { - public let disabled: Bool - public let minLevel: SupabaseLogLevel - public let logFile: URL - - public init( - disabled: Bool = true, - minLevel: SupabaseLogLevel = .debug, - logFile: URL = Self.defaultLogFileLocationURL - ) { - self.disabled = disabled - self.minLevel = minLevel - self.logFile = logFile - } - - public static let defaultLogFileLocationURL = try! FileManager.default.url( - for: .applicationSupportDirectory, - in: .userDomainMask, - appropriateFor: nil, - create: true - ).appendingPathComponent("supabase-swift.log") -} - -@_spi(Internal) -public struct SupabaseLogger: Sendable { - let system: String - let configuration: SupabaseLoggingConfiguration - let handler: SupabaseLogHandler - - public init(system: String, configuration: SupabaseLoggingConfiguration) { - self.system = system - handler = DefaultSupabaseLogHandler.instance(for: configuration.logFile) - self.configuration = configuration - } - - public func log( - _ level: SupabaseLogLevel, - message: @autoclosure () -> String, - fileID: StaticString = #fileID, - function: StaticString = #function, - line: UInt = #line - ) { - guard shouldLog(level) else { return } - - let entry = Entry( - system: system, - level: level, - message: message(), - fileID: "\(fileID)", - function: "\(function)", - line: line, - timestamp: Date().timeIntervalSince1970 - ) - - handler.didLog(entry) - } - - private func shouldLog(_ level: SupabaseLogLevel) -> Bool { - !configuration.disabled && level.rawValue >= configuration.minLevel.rawValue - } - - public func debug( - _ message: @autoclosure () -> String, - fileID: StaticString = #fileID, - function: StaticString = #function, - line: UInt = #line - ) { - log(.debug, message: message(), fileID: fileID, function: function, line: line) - } - - public func warning( - _ message: @autoclosure () -> String, - fileID: StaticString = #fileID, - function: StaticString = #function, - line: UInt = #line - ) { - log(.warning, message: message(), fileID: fileID, function: function, line: line) - } - - public func error( - _ message: @autoclosure () -> String, - fileID: StaticString = #fileID, - function: StaticString = #function, - line: UInt = #line - ) { - log(.error, message: message(), fileID: fileID, function: function, line: line) - } -} diff --git a/Tests/AuthTests/GoTrueClientTests.swift b/Tests/AuthTests/GoTrueClientTests.swift index 516119db..e0640a45 100644 --- a/Tests/AuthTests/GoTrueClientTests.swift +++ b/Tests/AuthTests/GoTrueClientTests.swift @@ -167,13 +167,7 @@ final class AuthClientTests: XCTestCase { api: .mock, eventEmitter: .mock, sessionStorage: .mock, - logger: SupabaseLogger( - system: "AuthClientTests", - configuration: SupabaseLoggingConfiguration( - logFile: URL(fileURLWithPath: NSTemporaryDirectory()) - .appendingPathComponent("supabase-swift.log") - ) - ) + logger: nil ) addTeardownBlock { [weak sut] in diff --git a/Tests/AuthTests/Mocks/Mocks.swift b/Tests/AuthTests/Mocks/Mocks.swift index 59bfed90..d163fbba 100644 --- a/Tests/AuthTests/Mocks/Mocks.swift +++ b/Tests/AuthTests/Mocks/Mocks.swift @@ -115,13 +115,7 @@ extension Dependencies { sessionStorage: .mock, sessionRefresher: .mock, codeVerifierStorage: .mock, - logger: SupabaseLogger( - system: "AuthClientTests", - configuration: SupabaseLoggingConfiguration( - logFile: URL(fileURLWithPath: NSTemporaryDirectory()) - .appendingPathComponent("supabase-swift.log") - ) - ) + logger: nil ) } diff --git a/Tests/AuthTests/RequestsTests.swift b/Tests/AuthTests/RequestsTests.swift index 8b2a0ec0..f93bcc70 100644 --- a/Tests/AuthTests/RequestsTests.swift +++ b/Tests/AuthTests/RequestsTests.swift @@ -431,13 +431,7 @@ final class RequestsTests: XCTestCase { api: api, eventEmitter: .mock, sessionStorage: .mock, - logger: SupabaseLogger( - system: "AuthClientTests", - configuration: SupabaseLoggingConfiguration( - logFile: URL(fileURLWithPath: NSTemporaryDirectory()) - .appendingPathComponent("supabase-swift.log") - ) - ) + logger: nil ) } }