Skip to content

Commit

Permalink
Simplify logger
Browse files Browse the repository at this point in the history
  • Loading branch information
grdsdev committed Jan 16, 2024
1 parent bc9d6ad commit 1b339f4
Show file tree
Hide file tree
Showing 20 changed files with 201 additions and 268 deletions.
26 changes: 22 additions & 4 deletions Examples/UserManagement/Supabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
}
}
}
11 changes: 10 additions & 1 deletion Package.resolved
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -47,4 +56,4 @@
}
],
"version" : 2
}
}
32 changes: 16 additions & 16 deletions Sources/Auth/AuthClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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) }
Expand All @@ -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
Expand Down Expand Up @@ -79,7 +79,7 @@ public actor AuthClient {
Dependencies.current.value!.currentDate
}

private var logger: SupabaseLogger {
private var logger: SupabaseLogger? {
Dependencies.current.value!.logger
}

Expand All @@ -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.
Expand All @@ -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) }
Expand All @@ -122,7 +122,7 @@ public actor AuthClient {
headers: headers,
flowType: flowType,
localStorage: localStorage,
loggingConfiguration: loggingConfiguration,
logger: logger,
encoder: encoder,
decoder: decoder,
fetch: fetch
Expand All @@ -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,
Expand All @@ -144,10 +147,7 @@ public actor AuthClient {
api: api,
eventEmitter: .live,
sessionStorage: .live,
logger: SupabaseLogger(
system: "AuthClient",
configuration: configuration.loggingConfiguration
)
logger: configuration.logger
)
}

Expand All @@ -159,7 +159,7 @@ public actor AuthClient {
api: APIClient,
eventEmitter: EventEmitter,
sessionStorage: SessionStorage,
logger: SupabaseLogger
logger: SupabaseLogger?
) {
mfa = AuthMFA()

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Sources/Auth/Internal/Dependencies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ struct Dependencies: Sendable {
var sessionRefresher: SessionRefresher
var codeVerifierStorage: CodeVerifierStorage
var currentDate: @Sendable () -> Date = { Date() }
var logger: SupabaseLogger
var logger: SupabaseLogger?
}
4 changes: 2 additions & 2 deletions Sources/PostgREST/PostgrestBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
}
}
Expand Down
15 changes: 7 additions & 8 deletions Sources/PostgREST/PostgrestClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,33 @@ 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.
public init(
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
) {
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)
}
}

Expand All @@ -66,15 +65,15 @@ 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.
public init(
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
Expand All @@ -84,7 +83,7 @@ public actor PostgrestClient {
url: url,
schema: schema,
headers: headers,
loggingConfiguration: loggingConfiguration,
logger: logger,
fetch: fetch,
encoder: encoder,
decoder: decoder
Expand Down
17 changes: 11 additions & 6 deletions Sources/Realtime/RealtimeClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
}

Expand All @@ -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
)
}

Expand All @@ -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
Expand All @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion Sources/Storage/StorageApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion Sources/Storage/SupabaseStorage.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import _Helpers
import Foundation

public struct StorageClientConfiguration {
Expand All @@ -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
}
}

Expand Down
Loading

0 comments on commit 1b339f4

Please sign in to comment.