Skip to content

Commit f8af9dd

Browse files
authored
Merge pull request #2 from augard/feat/improve-logging
♻️ refactor: Replace print statements with structured os_log logging
2 parents 6bdeb15 + 5286d7e commit f8af9dd

15 files changed

Lines changed: 152 additions & 88 deletions

KiaExtension/CarListHandler.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import Foundation
1010
import Intents
1111
import UIKit
12+
import os.log
1213

1314
class CarListHandler: NSObject, INListCarsIntentHandling, Handler {
1415
private let api: Api
@@ -86,7 +87,7 @@ extension Vehicle {
8687

8788
// Get Bluetooth and iAP2 identifiers for this vehicle
8889
let headUnitIds = headUnitIdentifiers()
89-
print("CarListHandler: Vehicle '\(nickname)' - Bluetooth: \(headUnitIds.bluetooth ?? "none"), iAP2: \(headUnitIds.iap2 ?? "none")")
90+
os_log(.debug, log: Logger.extension, "CarListHandler: Vehicle '%{public}@' - Bluetooth: %{public}@, iAP2: %{public}@", nickname, headUnitIds.bluetooth ?? "none", headUnitIds.iap2 ?? "none")
9091

9192
let car: INCar = .init(
9293
carIdentifier: vehicleId.uuidString,

KiaExtension/CredentialsHandler.swift

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//
88

99
import Foundation
10+
import os.log
1011

1112
class CredentialsHandler {
1213
private let api: Api
@@ -37,7 +38,7 @@ class CredentialsHandler {
3738
}
3839

3940
do {
40-
print("CredentialsHandler: Using credentials from local server for reauthorization")
41+
os_log(.info, log: Logger.extension, "CredentialsHandler: Using credentials from local server for reauthorization")
4142
let authorization = try await api.login(
4243
username: credentials.username,
4344
password: credentials.password
@@ -55,7 +56,7 @@ class CredentialsHandler {
5556
}
5657

5758
private func updateCredentials() async {
58-
print("CredentialsHandler: Updating credentials")
59+
os_log(.info, log: Logger.extension, "CredentialsHandler: Updating credentials")
5960

6061
if let credentials = try? await credentialClient.fetchCredentials() {
6162
api.authorization = credentials.authorization
@@ -67,17 +68,17 @@ class CredentialsHandler {
6768

6869
// Store username and password if available for future use
6970
if let username = credentials.username, let password = credentials.password {
70-
print("CredentialsHandler: Successfully received username and password from local server")
71+
os_log(.info, log: Logger.extension, "CredentialsHandler: Successfully received username and password from local server")
7172
LoginCredentialManager.store(
7273
credentials: LoginCredentials(
7374
username: username,
7475
password: password
7576
)
7677
)
7778
}
78-
print("CredentialsHandler: Successfully updated authorization from local server")
79+
os_log(.info, log: Logger.extension, "CredentialsHandler: Successfully updated authorization from local server")
7980
} else {
80-
print("CredentialsHandler: Failed to fetch credentials from local server")
81+
os_log(.default, log: Logger.extension, "CredentialsHandler: Failed to fetch credentials from local server")
8182
// Fallback to locally stored in keychain
8283
api.authorization = Authorization.authorization
8384
}

KiaMaps/App/ApiExtensions.swift

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//
88

99
import Foundation
10+
import os.log
1011

1112
/// Extension to Api class that handles automatic token refresh and retry logic
1213
extension Api {
@@ -22,15 +23,15 @@ extension Api {
2223
} catch {
2324
// Check if this is an unauthorized error (401) indicating expired token
2425
if let apiError = error as? ApiError, case .unauthorized = apiError {
25-
print("ApiAutoRefresh: Detected expired token, attempting automatic login retry")
26+
os_log(.info, log: Logger.auth, "Detected expired token, attempting automatic login retry")
2627

2728
// Try to refresh the token using stored credentials
2829
if await refreshTokenIfPossible() {
29-
print("ApiAutoRefresh: Token refreshed successfully, retrying operation")
30+
os_log(.info, log: Logger.auth, "Token refreshed successfully, retrying operation")
3031
// Retry the operation with fresh token
3132
return try await operation()
3233
} else {
33-
print("ApiAutoRefresh: Token refresh failed, throwing original error")
34+
os_log(.error, log: Logger.auth, "Token refresh failed, throwing original error")
3435
// If refresh failed, throw the original unauthorized error
3536
throw error
3637
}
@@ -46,18 +47,18 @@ extension Api {
4647
private func refreshTokenIfPossible() async -> Bool {
4748
// Check if we have stored login credentials
4849
guard let storedCredentials = LoginCredentialManager.retrieveCredentials() else {
49-
print("ApiAutoRefresh: No stored credentials available for token refresh")
50+
os_log(.default, log: Logger.auth, "No stored credentials available for token refresh")
5051
return false
5152
}
5253

5354
// Check if current token is actually expired before attempting refresh
5455
if let currentAuth = authorization, !isTokenExpired(currentAuth) {
55-
print("ApiAutoRefresh: Current token is not expired, no refresh needed")
56+
os_log(.debug, log: Logger.auth, "Current token is not expired, no refresh needed")
5657
return true
5758
}
5859

5960
do {
60-
print("ApiAutoRefresh: Attempting to login with stored credentials")
61+
os_log(.info, log: Logger.auth, "Attempting to login with stored credentials")
6162
let newAuthData = try await login(
6263
username: storedCredentials.username,
6364
password: storedCredentials.password
@@ -67,15 +68,15 @@ extension Api {
6768
Authorization.store(data: newAuthData)
6869
self.authorization = newAuthData
6970

70-
print("ApiAutoRefresh: Successfully refreshed token")
71+
os_log(.info, log: Logger.auth, "Successfully refreshed token")
7172
return true
7273

7374
} catch {
74-
print("ApiAutoRefresh: Failed to refresh token with error: \(error)")
75+
os_log(.error, log: Logger.auth, "Failed to refresh token with error: %{public}@", error.localizedDescription)
7576

7677
// If login fails, clear the stored credentials as they might be invalid
7778
if error is ApiError {
78-
print("ApiAutoRefresh: Clearing invalid stored credentials")
79+
os_log(.default, log: Logger.auth, "Clearing invalid stored credentials")
7980
LoginCredentialManager.clearCredentials()
8081
}
8182

KiaMaps/App/AppDelegate.swift

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import SwiftUI
22
import UIKit
33
import BackgroundTasks
4+
import os.log
45

56
class AppDelegate: NSObject, UIApplicationDelegate {
67
var localClient: LocalCredentialClient! = nil
@@ -14,7 +15,7 @@ class AppDelegate: NSObject, UIApplicationDelegate {
1415

1516
// Start the local credential server
1617
LocalCredentialServer.shared.start { success in
17-
print("AppDelegate: Server start success: \(success)")
18+
os_log(.info, log: Logger.server, "Server start success: %{public}@", success ? "true" : "false")
1819
}
1920
return true
2021
}
@@ -23,7 +24,7 @@ class AppDelegate: NSObject, UIApplicationDelegate {
2324
// Stop the local credential server
2425
LocalCredentialServer.shared.stop()
2526
BackgroundTaskManager.shared.cleanup()
26-
print("AppDelegate: Stopped local credential server")
27+
os_log(.info, log: Logger.server, "Stopped local credential server")
2728
}
2829
}
2930

@@ -42,11 +43,11 @@ class BackgroundTaskManager: ObservableObject {
4243
BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.backgroundTaskIdentifier, using: nil) { task in
4344
self.handleBackgroundServerMaintenance(task: task as! BGAppRefreshTask)
4445
}
45-
print("BackgroundTaskManager: Registered background task: \(Self.backgroundTaskIdentifier)")
46+
os_log(.info, log: Logger.app, "Registered background task: %{public}@", Self.backgroundTaskIdentifier)
4647
}
4748

4849
func handleAppDidEnterBackground() {
49-
print("BackgroundTaskManager: App entered background, maintaining server")
50+
os_log(.info, log: Logger.app, "App entered background, maintaining server")
5051

5152
// Start background task to keep server running
5253
startBackgroundTask()
@@ -56,7 +57,7 @@ class BackgroundTaskManager: ObservableObject {
5657
}
5758

5859
func handleAppWillEnterForeground() {
59-
print("BackgroundTaskManager: App entering foreground")
60+
os_log(.info, log: Logger.app, "App entering foreground")
6061

6162
// End background task if running
6263
endBackgroundTask()
@@ -77,27 +78,27 @@ class BackgroundTaskManager: ObservableObject {
7778

7879
do {
7980
try BGTaskScheduler.shared.submit(request)
80-
print("BackgroundTaskManager: Scheduled background refresh task")
81+
os_log(.info, log: Logger.app, "Scheduled background refresh task")
8182
} catch {
82-
print("BackgroundTaskManager: Failed to schedule background refresh: \(error)")
83+
os_log(.error, log: Logger.app, "Failed to schedule background refresh: %{public}@", error.localizedDescription)
8384
}
8485
}
8586

8687
private func handleBackgroundServerMaintenance(task: BGAppRefreshTask) {
87-
print("BackgroundTaskManager: Handling background server maintenance")
88+
os_log(.info, log: Logger.app, "Handling background server maintenance")
8889

8990
// Schedule next refresh
9091
scheduleBackgroundRefresh()
9192

9293
task.expirationHandler = {
93-
print("BackgroundTaskManager: Background task expired")
94+
os_log(.info, log: Logger.app, "Background task expired")
9495
task.setTaskCompleted(success: false)
9596
}
9697

9798
// Check and restart server if needed
9899
DispatchQueue.global(qos: .default).async {
99100
if !LocalCredentialServer.shared.isRunning {
100-
print("BackgroundTaskManager: Restarting server during background refresh")
101+
os_log(.info, log: Logger.app, "Restarting server during background refresh")
101102
LocalCredentialServer.shared.start()
102103

103104
// Wait a moment for server to start
@@ -113,7 +114,7 @@ class BackgroundTaskManager: ObservableObject {
113114
private func startBackgroundTask() {
114115
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "LocalServerMaintenance") {
115116
[weak self] in
116-
print("BackgroundTaskManager: Background task expired, ending task")
117+
os_log(.info, log: Logger.app, "Background task expired, ending task")
117118
self?.endBackgroundTask()
118119
}
119120

@@ -132,21 +133,21 @@ class BackgroundTaskManager: ObservableObject {
132133
}
133134

134135
private func maintainServerInBackground() {
135-
print("BackgroundTaskManager: Maintaining server in background")
136+
os_log(.info, log: Logger.app, "Maintaining server in background")
136137

137138
// Keep the server alive for as long as possible in background
138139
while backgroundTask != .invalid && UIApplication.shared.backgroundTimeRemaining > 5.0 {
139140
// Check server status periodically
140141
if !LocalCredentialServer.shared.isRunning {
141-
print("BackgroundTaskManager: Restarting server in background")
142+
os_log(.info, log: Logger.app, "Restarting server in background")
142143
LocalCredentialServer.shared.start()
143144
}
144145

145146
// Sleep for a short interval
146147
Thread.sleep(forTimeInterval: 1.0)
147148
}
148149

149-
print("BackgroundTaskManager: Background maintenance ending, time remaining: \(UIApplication.shared.backgroundTimeRemaining)")
150+
os_log(.info, log: Logger.app, "Background maintenance ending, time remaining: %{public}f", UIApplication.shared.backgroundTimeRemaining)
150151
}
151152
}
152153

@@ -179,19 +180,19 @@ struct Application: App {
179180
private func handleScenePhaseChange(_ phase: ScenePhase) {
180181
switch phase {
181182
case .active:
182-
print("Application: Scene became active")
183+
os_log(.debug, log: Logger.app, "Scene became active")
183184
backgroundManager.handleAppWillEnterForeground()
184185

185186
case .inactive:
186-
print("Application: Scene became inactive")
187+
os_log(.debug, log: Logger.app, "Scene became inactive")
187188
// Handle brief inactive state (e.g., incoming call, control center)
188189

189190
case .background:
190-
print("Application: Scene entered background")
191+
os_log(.debug, log: Logger.app, "Scene entered background")
191192
backgroundManager.handleAppDidEnterBackground()
192193

193194
@unknown default:
194-
print("Application: Unknown scene phase: \(phase)")
195+
os_log(.default, log: Logger.app, "Unknown scene phase: %{public}@", String(describing: phase))
195196
}
196197
}
197198
}

KiaMaps/App/LoginView.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//
88

99
import SwiftUI
10+
import os.log
1011

1112
struct LoginView: View {
1213
@State private var username: String = ""
@@ -291,6 +292,6 @@ struct KiaTextFieldStyle: TextFieldStyle {
291292

292293
#Preview {
293294
LoginView(configuration: AppConfiguration.self) { authData in
294-
print("Login successful with user: \(authData)")
295+
os_log(.info, log: Logger.auth, "Login successful for user")
295296
}
296297
}

KiaMaps/App/MainView.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//
88

99
import SwiftUI
10+
import os.log
1011

1112
struct MainView: View {
1213
let configuration: AppConfiguration.Type
@@ -293,7 +294,7 @@ struct MainView: View {
293294
await loadData()
294295
if lastUpdateDate < selectedVehicleStatus.lastUpdateTime {
295296
self.lastUpdateDate = nil
296-
print("Updated")
297+
os_log(.debug, log: Logger.ui, "Vehicle status updated")
297298
}
298299
} else {
299300
_ = try await api.refreshVehicleWithAutoRefresh(selectedVehicle.vehicleId)

KiaMaps/Core/Api/Api.swift

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//
88

99
import Foundation
10+
import os.log
1011

1112
/**
1213
* Api - Main interface for Kia/Hyundai/Genesis vehicle API communication
@@ -76,15 +77,15 @@ class Api {
7677
let referer: String
7778
do {
7879
referer = try await fetchConnectorAuthorization()
79-
print("Retrieved referer: \(referer)")
80+
os_log(.info, log: Logger.api, "Retrieved referer: %{private}@", referer)
8081
} catch {
81-
print("Client connector authorization failed \(error.localizedDescription)")
82+
os_log(.error, log: Logger.api, "Client connector authorization failed: %{public}@", error.localizedDescription)
8283
throw AuthenticationError.clientConfigurationFailed
8384
}
8485

8586
// Step 1: Get client configuration
8687
let clientConfig = try await fetchClientConfiguration(referer: referer)
87-
print("Client configured for: \(clientConfig.clientName)")
88+
os_log(.info, log: Logger.api, "Client configured for: %{public}@", clientConfig.clientName)
8889

8990
// Step 2: Check if password encryption is enabled
9091
let encryptionSettings = try await fetchPasswordEncryptionSettings(referer: referer)
@@ -97,7 +98,7 @@ class Api {
9798
do {
9899
rsaKey = try await fetchRSACertificate(referer: referer)
99100
} catch {
100-
print("Fetch RSA Certificate failed \(error.localizedDescription)")
101+
os_log(.error, log: Logger.api, "Fetch RSA Certificate failed: %{public}@", error.localizedDescription)
101102
throw AuthenticationError.certificateRetrievalFailed
102103
}
103104
// Step 4: Initialize OAuth2 flow
@@ -117,7 +118,7 @@ class Api {
117118
do {
118119
tokenResponse = try await exchangeCodeForTokens(authorizationCode: authorizationCode)
119120
} catch {
120-
print("Exchange code for token failed \(error.localizedDescription)")
121+
os_log(.error, log: Logger.api, "Exchange code for token failed: %{public}@", error.localizedDescription)
121122
throw AuthenticationError.tokenExchangeFailed
122123
}
123124

@@ -145,9 +146,9 @@ class Api {
145146
func logout() async throws {
146147
do {
147148
try await provider.request(with: .post, endpoint: .logout).empty()
148-
print("Successfully logout")
149+
os_log(.info, log: Logger.auth, "Successfully logout")
149150
} catch {
150-
print("Failed to logout: " + error.localizedDescription)
151+
os_log(.error, log: Logger.auth, "Failed to logout: %{public}@", error.localizedDescription)
151152
}
152153
provider.authorization = nil
153154
cleanCookies()

0 commit comments

Comments
 (0)