Skip to content

Commit fe39880

Browse files
authored
chore: more logging (#2661)
Signed-off-by: Jason C. Leach <jason.leach@fullboar.ca>
1 parent 2c44f6b commit fe39880

File tree

5 files changed

+126
-47
lines changed

5 files changed

+126
-47
lines changed

app/src/bcsc-theme/api/client.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ class BCSCService {
190190
}
191191

192192
private async handleRequest(config: InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig> {
193+
this.logger.info(`Handling request for URL: ${String(config.url)}`)
193194
// skip processing if skipBearerAuth is set in the config
194195
if (config.skipBearerAuth) {
195196
return config
@@ -203,7 +204,8 @@ class BCSCService {
203204
config.headers.set('Authorization', `Bearer ${this.tokens.access_token}`)
204205
}
205206

206-
this.logger.debug(`${String(config.method)}: ${String(config.url)}`, {})
207+
this.logger.debug(`Sending request to ${String(config.url)} with method ${String(config.method)}`, config as any)
208+
207209
return config
208210
}
209211

app/src/bcsc-theme/hooks/useInitializeBcscApi.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,14 @@ const useInitializeBcscApi = () => {
2222
const asyncEffect = async () => {
2323
try {
2424
await client.fetchEndpointsAndConfig(client.baseURL)
25+
logger.debug('Fetched BCSC endpoints and configuration', {
26+
baseURL: client.baseURL,
27+
})
2528
} catch (error) {
2629
logger.error('Failed to fetch BCSC endpoints', {
2730
message: error instanceof Error ? error.message : String(error),
2831
})
32+
2933
dispatch({
3034
type: DispatchAction.BANNER_MESSAGES,
3135
payload: [
@@ -42,8 +46,9 @@ const useInitializeBcscApi = () => {
4246

4347
try {
4448
await registration.register()
49+
logger.debug('BCSC registration successful')
4550
} catch (error) {
46-
logger.error(`Error during registration: ${error}`)
51+
logger.error(`Error during registration.`, error as Error)
4752
}
4853

4954
try {
@@ -69,7 +74,7 @@ const useInitializeBcscApi = () => {
6974
dispatch({ type: BCDispatchAction.UPDATE_VERIFIED, payload: [true] })
7075
}
7176
} catch (error) {
72-
logger.error(`Error setting API client tokens: ${error}`)
77+
logger.error(`Error setting API client tokens.`, error as Error)
7378
} finally {
7479
setLoading(false)
7580
}

packages/bcsc-core/ios/BcscCore.swift

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import CryptoKit
22
import Foundation
33
import React
44

5+
56
enum AccountSecurityMethod: String {
67
case pinNoDeviceAuth = "app_pin_no_device_authn"
78
case pinWithDeviceAuth = "app_pin_has_device_authn"
@@ -33,6 +34,7 @@ enum DeviceInfoKeys {
3334
@objcMembers
3435
@objc(BcscCore)
3536
class BcscCore: NSObject {
37+
let logger = AppLogger(subsystem: Bundle.main.bundleIdentifier ?? "ca.bc.gov.id.servicescard", category: "BcscCore")
3638
static let generalizedOsName = "iOS"
3739
static let provider = "https://idsit.gov.bc.ca/device/"
3840
static let clientName = "BC Services Wallet"
@@ -144,7 +146,7 @@ class BcscCore: NSObject {
144146
SecItemDelete(query as CFDictionary)
145147
}
146148

147-
print("BcscCore: Keychain cleared for this app.")
149+
logger.log("Keychain cleared for this app.")
148150
}
149151

150152
// MARK: - Public Methods
@@ -229,60 +231,60 @@ class BcscCore: NSObject {
229231
let baseId = components.joined(separator: "/") // Reconstruct the base part of the ID
230232
let newKeyId = "\(baseId)/\(numericSuffix)"
231233

232-
print(
233-
"BcscCore: generateKeyPair (private) - Latest key found: \(existingTag). Attempting to generate new incremented key with ID: \(newKeyId)"
234+
logger.log(
235+
"generateKeyPair - Latest key found: \(existingTag). Attempting to generate new incremented key with ID: \(newKeyId)"
234236
)
235237
do {
236238
// Assuming default keyType and keySize are handled by KeyPairManager.generateKeyPair or are acceptable.
237239
_ = try keyPairManager.generateKeyPair(withLabel: newKeyId)
238-
print(
239-
"BcscCore: generateKeyPair (private) - Successfully generated new incremented key with ID: \(newKeyId)"
240+
logger.log(
241+
"generateKeyPair - Successfully generated new incremented key with ID: \(newKeyId)"
240242
)
241243
return newKeyId
242244
} catch {
243-
print(
244-
"BcscCore: generateKeyPair (private) - Failed to generate new incremented key with ID \(newKeyId): \(error.localizedDescription)."
245+
logger.error(
246+
"generateKeyPair - Failed to generate new incremented key with ID \(newKeyId): \(error.localizedDescription)."
245247
)
246248
return nil // Failed to generate the specifically requested incremented key.
247249
}
248250
} else {
249251
// Parsing the existing tag failed (e.g., not in expected format or last part not a number).
250252
// Fallback: generate a completely new key using a fresh initial ID pattern.
251-
print(
252-
"BcscCore: generateKeyPair (private) - Could not parse or increment existing key tag: \(existingTag). Attempting to generate a new key with a fresh initial ID pattern."
253+
logger.warning(
254+
"generateKeyPair - Could not parse or increment existing key tag: \(existingTag). Attempting to generate a new key with a fresh initial ID pattern."
253255
)
254256
// Use the same pattern for the new key ID as in the 'no keys found' case for consistency, but with a new UUID.
255257
let freshGeneratedKeyId = "\(BcscCore.provider)/\(UUID().uuidString)/1"
256-
print(
257-
"BcscCore: generateKeyPair (private) - Attempting to generate a new key with ID: \(freshGeneratedKeyId) due to parsing failure of existing key."
258+
logger.log(
259+
"generateKeyPair - Attempting to generate a new key with ID: \(freshGeneratedKeyId) due to parsing failure of existing key."
258260
)
259261
do {
260262
_ = try keyPairManager.generateKeyPair(withLabel: freshGeneratedKeyId)
261-
print(
262-
"BcscCore: generateKeyPair (private) - Successfully generated new key with ID: \(freshGeneratedKeyId) after parsing failure."
263+
logger.log(
264+
"generateKeyPair - Successfully generated new key with ID: \(freshGeneratedKeyId) after parsing failure."
263265
)
264266
return freshGeneratedKeyId
265267
} catch {
266-
print(
267-
"BcscCore: generateKeyPair (private) - Failed to generate new key with ID \(freshGeneratedKeyId) after parsing failure: \(error.localizedDescription)"
268+
logger.error(
269+
"generateKeyPair - Failed to generate new key with ID \(freshGeneratedKeyId) after parsing failure: \(error.localizedDescription)"
268270
)
269271
return nil
270272
}
271273
}
272274
} else {
273275
// No keys found, attempt to generate a new one
274-
print(
275-
"BcscCore: generateKeyPair (private) - No keys found. Attempting to generate a new key with ID: \(initialKeyId)"
276+
logger.log(
277+
"generateKeyPair - No keys found. Attempting to generate a new key with ID: \(initialKeyId)"
276278
)
277279
do {
278280
_ = try keyPairManager.generateKeyPair(withLabel: initialKeyId) // Assuming default keyType and keySize are handled by this method or are acceptable.
279-
print(
280-
"BcscCore: generateKeyPair (private) - Successfully generated new key with ID: \(initialKeyId)"
281+
logger.log(
282+
"generateKeyPair - Successfully generated new key with ID: \(initialKeyId)"
281283
)
282284
return initialKeyId
283285
} catch {
284-
print(
285-
"BcscCore: generateKeyPair (private) - Failed to generate new key with ID \(initialKeyId): \(error.localizedDescription)"
286+
logger.error(
287+
"generateKeyPair - Failed to generate new key with ID \(initialKeyId): \(error.localizedDescription)"
286288
)
287289
return nil
288290
}
@@ -375,7 +377,7 @@ class BcscCore: NSObject {
375377

376378
// Add any additional claims
377379
for (key, value) in claims {
378-
print(key, value)
380+
logger.log("\(key), \(value)")
379381
builder.claim(name: key as! String, value: value)
380382
}
381383

@@ -393,7 +395,7 @@ class BcscCore: NSObject {
393395
_ account: NSDictionary, resolve: @escaping RCTPromiseResolveBlock,
394396
reject: @escaping RCTPromiseRejectBlock
395397
) {
396-
print("BcscCore: setAccount called with account: \(account)")
398+
logger.log("setAccount called with account: \(account)")
397399
let accountID = UUID().uuidString
398400
let storage = StorageService()
399401

@@ -444,7 +446,7 @@ class BcscCore: NSObject {
444446
)
445447

446448
if success {
447-
print("BcscCore: setAccount - Account successfully stored")
449+
logger.log("setAccount - Account successfully stored")
448450
resolve(nil)
449451
} else {
450452
reject("E_ACCOUNT_STORAGE_FAILED", "Failed to store account data", nil)
@@ -659,7 +661,7 @@ class BcscCore: NSObject {
659661
]
660662

661663
do {
662-
// print("BcscCore: getDynamicClientRegistrationBody - Client Registration Data: \(clientRegistrationData)")
664+
// logger.log("BcscCore: getDynamicClientRegistrationBody - Client Registration Data: \(clientRegistrationData)")
663665
let jsonData = try JSONSerialization.data(withJSONObject: clientRegistrationData, options: [])
664666
let jsonString = String(data: jsonData, encoding: .utf8) ?? "{}"
665667

@@ -810,7 +812,7 @@ class BcscCore: NSObject {
810812
return // Error already handled in makeSignedJWT
811813
}
812814

813-
print("signedJWT: \(signedJWT)")
815+
logger.log("signedJWT: \(signedJWT)")
814816

815817
// Encrypt the signed JWT with the provided public key
816818
do {
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import Foundation
2+
import os
3+
4+
struct AppLogger {
5+
private let subsystem: String
6+
private let category: String
7+
8+
@available(iOS 14.0, *)
9+
private var osLogger: os.Logger {
10+
os.Logger(subsystem: subsystem, category: category)
11+
}
12+
13+
private var legacyLogger: OSLog {
14+
OSLog(subsystem: subsystem, category: category)
15+
}
16+
17+
init(subsystem: String, category: String) {
18+
self.subsystem = subsystem
19+
self.category = category
20+
}
21+
22+
func log(_ message: String) {
23+
if #available(iOS 14.0, *) {
24+
osLogger.log("\(message, privacy: .public)")
25+
} else {
26+
os_log("%{public}s", log: legacyLogger, type: .default, message)
27+
}
28+
}
29+
30+
func info(_ message: String) {
31+
if #available(iOS 14.0, *) {
32+
osLogger.info("\(message, privacy: .public)")
33+
} else {
34+
os_log("%{public}s", log: legacyLogger, type: .info, message)
35+
}
36+
}
37+
38+
func debug(_ message: String) {
39+
if #available(iOS 14.0, *) {
40+
osLogger.debug("\(message, privacy: .public)")
41+
} else {
42+
os_log("%{public}s", log: legacyLogger, type: .debug, message)
43+
}
44+
}
45+
46+
func error(_ message: String) {
47+
if #available(iOS 14.0, *) {
48+
osLogger.error("\(message, privacy: .public)")
49+
} else {
50+
os_log("%{public}s", log: legacyLogger, type: .error, message)
51+
}
52+
}
53+
54+
func warning(_ message: String) {
55+
if #available(iOS 14.0, *) {
56+
osLogger.warning("\(message, privacy: .public)")
57+
} else {
58+
os_log("%{public}s", log: legacyLogger, type: .error, message) // .warning is not available, fallback to .error
59+
}
60+
}
61+
62+
func fault(_ message: String) {
63+
if #available(iOS 14.0, *) {
64+
osLogger.fault("\(message, privacy: .public)")
65+
} else {
66+
os_log("%{public}s", log: legacyLogger, type: .fault, message)
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)