Skip to content

Commit

Permalink
fix: improve logging in httpclient
Browse files Browse the repository at this point in the history
  • Loading branch information
crleona committed Sep 13, 2024
1 parent ce41c10 commit baf26b0
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion Sources/Amplitude/Utilities/HttpClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Foundation
class HttpClient {
let configuration: Configuration
let session: URLSession
let logger: (any Logger)?
let diagnostics: Diagnostics
let callbackQueue: DispatchQueue

Expand All @@ -22,6 +23,7 @@ class HttpClient {
init(configuration: Configuration, diagnostics: Diagnostics, callbackQueue: DispatchQueue? = nil) {
self.configuration = configuration
self.diagnostics = diagnostics
self.logger = configuration.loggerProvider
self.callbackQueue = callbackQueue ?? .global()

let sessionConfiguration = URLSessionConfiguration.default
Expand All @@ -37,15 +39,17 @@ class HttpClient {
let request = try getRequest()
let requestData = getRequestData(events: events)

sessionTask = session.uploadTask(with: request, from: requestData) { [callbackQueue, configuration] data, response, error in
sessionTask = session.uploadTask(with: request, from: requestData) { [callbackQueue, configuration, logger] data, response, error in
callbackQueue.async {
if let error = error {
let nsError = error as NSError
if nsError.domain == NSURLErrorDomain {
switch nsError.code {
case NSURLErrorCannotConnectToHost, NSURLErrorNetworkConnectionLost, NSURLErrorCannotFindHost, NSURLErrorAppTransportSecurityRequiresSecureConnection:
logger?.error(message: "Conection failed with error: \(error.localizedDescription), marking offline")
configuration.offline = true
default:
logger?.error(message: "Request failed with error: \(error.localizedDescription)")
break
}
}
Expand All @@ -54,7 +58,10 @@ class HttpClient {
switch httpResponse.statusCode {
case 1..<300:
completion(.success(httpResponse.statusCode))
logger?.debug(message: "Successfully completed request")
default:
let response = String(data: data ?? Data(), encoding: .utf8) ?? ""
logger?.error(message: "Response failed \(httpResponse.statusCode): \(response)")
completion(.failure(Exception.httpError(code: httpResponse.statusCode, data: data)))
}
}
Expand All @@ -63,6 +70,7 @@ class HttpClient {
}
sessionTask!.resume()
} catch {
logger?.debug(message: "Failed to construct request")
completion(.failure(Exception.httpError(code: 500, data: nil)))
backgroundTaskCompletion?()
}
Expand Down

0 comments on commit baf26b0

Please sign in to comment.