Skip to content

Commit a450cbb

Browse files
committed
improve logs
1 parent 596cd72 commit a450cbb

File tree

7 files changed

+61
-28
lines changed

7 files changed

+61
-28
lines changed

Sources/SwiftAPIClient/APIClientCaller.swift

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import FoundationNetworking
77
/// A generic structure for handling network requests and their responses.
88
public struct APIClientCaller<Response, Value, Result> {
99

10+
var logRequestByItSelf = false
1011
private let _call: (
1112
UUID,
1213
HTTPRequestComponents,
@@ -216,18 +217,19 @@ public extension APIClient {
216217
let fileIDLine = configs.fileIDLine ?? FileIDLine(fileID: fileID, line: line)
217218
let configs = configs.with(\.fileIDLine, fileIDLine)
218219

219-
if configs.loggingComponents.contains(.onRequest), configs.loggingComponents != .onRequest {
220-
let message = configs.loggingComponents.requestMessage(for: request, uuid: uuid, fileIDLine: fileIDLine)
221-
configs.logger.log(level: configs.logLevel, "\(message)")
222-
}
223220
if let mock = try configs.getMockIfNeeded(for: Value.self, serializer: serializer) {
221+
#if canImport(Metrics)
222+
configs.reportMetrics(false).logRequest(request, uuid: uuid)
223+
#else
224+
configs.logRequest(request, uuid: uuid)
225+
#endif
224226
return try caller.mockResult(for: mock)
225227
}
226-
#if canImport(Metrics)
227-
if configs.reportMetrics {
228-
updateTotalRequestsMetrics(for: request)
228+
229+
try configs.requestValidator.validate(request, configs.with(\.requestValidator, .alwaysSuccess))
230+
if !caller.logRequestByItSelf {
231+
configs.logRequest(request, uuid: uuid)
229232
}
230-
#endif
231233

232234
return try caller.call(uuid: uuid, request: request, configs: configs) { response, validate in
233235
do {

Sources/SwiftAPIClient/Clients/HTTPClient.swift

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,16 @@ extension APIClientCaller where Result == AsyncThrowingValue<(Value, HTTPRespons
112112
validate: @escaping (T, HTTPResponse, APIClient.Configs) throws -> Void,
113113
data: @escaping (T) -> Data?
114114
) -> APIClientCaller where Response == (T, HTTPResponse) {
115-
APIClientCaller { uuid, request, configs, serialize in
115+
var result = APIClientCaller { uuid, request, configs, serialize in
116116
{
117117
let value: T
118118
let response: HTTPResponse
119119
let start = Date()
120120
do {
121-
(value, response) = try await configs.httpClientMiddleware.execute(request: request, configs: configs, next: task)
121+
(value, response) = try await configs.httpClientMiddleware.execute(request: request, configs: configs) { request, configs in
122+
configs.logRequest(request, uuid: uuid)
123+
return try await task(request, configs)
124+
}
122125
} catch {
123126
let duration = Date().timeIntervalSince(start)
124127
if !configs._errorLoggingComponents.isEmpty {
@@ -191,6 +194,21 @@ extension APIClientCaller where Result == AsyncThrowingValue<(Value, HTTPRespons
191194
} mockResult: { value in
192195
asyncWithResponse(value)
193196
}
197+
result.logRequestByItSelf = true
198+
return result
199+
}
200+
}
201+
202+
private final actor SendableValue<Value> {
203+
204+
var value: Value
205+
206+
init(_ value: Value) {
207+
self.value = value
208+
}
209+
210+
func set(_ value: Value) {
211+
self.value = value
194212
}
195213
}
196214

Sources/SwiftAPIClient/Modifiers/LoggingModifier.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,18 @@ extension APIClient.Configs {
8484
var _errorLoggingComponents: LoggingComponents {
8585
errorLogginComponents ?? loggingComponents
8686
}
87+
88+
func logRequest(_ request: HTTPRequestComponents, uuid: UUID) {
89+
if loggingComponents.contains(.onRequest), loggingComponents != .onRequest {
90+
let message = loggingComponents.requestMessage(for: request, uuid: uuid, fileIDLine: fileIDLine)
91+
logger.log(level: logLevel, "\(message)")
92+
}
93+
#if canImport(Metrics)
94+
if configs.reportMetrics {
95+
updateTotalRequestsMetrics(for: request)
96+
}
97+
#endif
98+
}
8799
}
88100

89101
private let defaultLogger = Logger(label: "swift-api-client")

Sources/SwiftAPIClient/Modifiers/RateLimitModifier.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ private struct RateLimitMiddleware<ID: Hashable>: HTTPClientMiddleware {
4747
func execute<T>(
4848
request: HTTPRequestComponents,
4949
configs: APIClient.Configs,
50-
next: @escaping (HTTPRequestComponents, APIClient.Configs) async throws -> (T, HTTPResponse)
50+
next: @escaping @Sendable (HTTPRequestComponents, APIClient.Configs) async throws -> (T, HTTPResponse)
5151
) async throws -> (T, HTTPResponse) {
5252
let id = id(request)
5353
await waitForSynchronizedAccess(id: id, of: Void.self)

Sources/SwiftAPIClient/Modifiers/RequestValidator.swift

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,26 +25,27 @@ public extension RequestValidator {
2525
}
2626
}
2727

28+
public extension APIClient.Configs {
29+
30+
/// The request validator used for validating URL request instances.
31+
var requestValidator: RequestValidator {
32+
get { self[\.requestValidator] ?? .alwaysSuccess }
33+
set { self[\.requestValidator] = newValue }
34+
}
35+
}
36+
2837
public extension APIClient {
2938

3039
/// Sets a custom request validator for the network client.
3140
/// - Parameter validator: The `RequestValidator` to be used for validating URL request instances.
3241
/// - Returns: An instance of `APIClient` configured with the specified request validator.
3342
func requestValidator(_ validator: RequestValidator) -> APIClient {
34-
httpClientMiddleware(RequestValidatorMiddleware(validator: validator))
35-
}
36-
}
37-
38-
private struct RequestValidatorMiddleware: HTTPClientMiddleware {
39-
40-
let validator: RequestValidator
41-
42-
func execute<T>(
43-
request: HTTPRequestComponents,
44-
configs: APIClient.Configs,
45-
next: @escaping @Sendable (HTTPRequestComponents, APIClient.Configs) async throws -> (T, HTTPResponse)
46-
) async throws -> (T, HTTPResponse) {
47-
try validator.validate(request, configs)
48-
return try await next(request, configs)
43+
configs { configs in
44+
let validate = configs.requestValidator.validate
45+
configs.requestValidator.validate = { request, configs in
46+
try validate(request, configs)
47+
try validator.validate(request, configs)
48+
}
49+
}
4950
}
5051
}

Sources/SwiftAPIClient/Utils/AnyAsyncSequence.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public struct AnyAsyncSequence<Element>: AsyncSequence {
3232

3333
private var _next: () async throws -> Element?
3434

35-
public init(next: @escaping () async throws -> Element?) {
35+
public init(next: @escaping @Sendable () async throws -> Element?) {
3636
_next = next
3737
}
3838

Tests/SwiftAPIClientTests/TestUtils/QueryParameterMiddleware.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,4 @@ struct QueryParameterMiddleware: HTTPClientMiddleware {
3535

3636
return try await next(modifiedRequest, configs)
3737
}
38-
}
38+
}

0 commit comments

Comments
 (0)