Skip to content

Commit 52096f4

Browse files
Add logger
1 parent 74d3688 commit 52096f4

File tree

6 files changed

+49
-35
lines changed

6 files changed

+49
-35
lines changed

Sources/PowerSync/Kotlin/KotlinPowerSyncDatabaseImpl.swift

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
import Foundation
22
import PowerSyncKotlin
33

4-
final class KotlinPowerSyncDatabaseImpl: PowerSyncDatabaseProtocol {
4+
internal final class KotlinPowerSyncDatabaseImpl: PowerSyncDatabaseProtocol {
5+
let logger: any LoggerProtocol
6+
57
private let kotlinDatabase: PowerSyncKotlin.PowerSyncDatabase
68

79
var currentStatus: SyncStatus { kotlinDatabase.currentStatus }
10+
811

912
init(
1013
schema: Schema,
1114
dbFilename: String,
12-
logger: DatabaseLogger? = nil
15+
logger: DatabaseLogger
1316
) {
1417
let factory = PowerSyncKotlin.DatabaseDriverFactory()
1518
kotlinDatabase = PowerSyncDatabase(
1619
factory: factory,
1720
schema: KotlinAdapter.Schema.toKotlin(schema),
1821
dbFilename: dbFilename,
19-
logger: logger?.kLogger
22+
logger: logger.kLogger
2023
)
21-
}
22-
23-
init(kotlinDatabase: KotlinPowerSyncDatabase) {
24-
self.kotlinDatabase = kotlinDatabase
24+
self.logger = logger
2525
}
2626

2727
func waitForFirstSync() async throws {
@@ -42,7 +42,10 @@ final class KotlinPowerSyncDatabaseImpl: PowerSyncDatabaseProtocol {
4242
retryDelayMs: Int64 = 5000,
4343
params: [String: JsonParam?] = [:]
4444
) async throws {
45-
let connectorAdapter = PowerSyncBackendConnectorAdapter(swiftBackendConnector: connector)
45+
let connectorAdapter = PowerSyncBackendConnectorAdapter(
46+
swiftBackendConnector: connector,
47+
db: self
48+
)
4649

4750
try await kotlinDatabase.connect(
4851
connector: connectorAdapter,
Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,34 @@
11
import OSLog
22

3-
class PowerSyncBackendConnectorAdapter: KotlinPowerSyncBackendConnector {
3+
internal class PowerSyncBackendConnectorAdapter: KotlinPowerSyncBackendConnector {
44
let swiftBackendConnector: PowerSyncBackendConnector
5-
5+
let db: any PowerSyncDatabaseProtocol
6+
let logTag = "PowerSyncBackendConnector"
7+
68
init(
7-
swiftBackendConnector: PowerSyncBackendConnector
9+
swiftBackendConnector: PowerSyncBackendConnector,
10+
db: any PowerSyncDatabaseProtocol
811
) {
912
self.swiftBackendConnector = swiftBackendConnector
13+
self.db = db
1014
}
1115

1216
override func __fetchCredentials() async throws -> KotlinPowerSyncCredentials? {
1317
do {
1418
let result = try await swiftBackendConnector.fetchCredentials()
1519
return result?.kotlinCredentials
1620
} catch {
17-
if #available(iOS 14.0, *) {
18-
Logger().error("🔴 Failed to fetch credentials: \(error.localizedDescription)")
19-
} else {
20-
print("🔴 Failed to fetch credentials: \(error.localizedDescription)")
21-
}
21+
db.logger.error("Error while fetching credentials", tag: logTag)
2222
return nil
2323
}
2424
}
2525

2626
override func __uploadData(database: KotlinPowerSyncDatabase) async throws {
27-
let swiftDatabase = KotlinPowerSyncDatabaseImpl(kotlinDatabase: database)
2827
do {
29-
return try await swiftBackendConnector.uploadData(database: swiftDatabase)
28+
// Pass the Swift DB protocal to the connector
29+
return try await swiftBackendConnector.uploadData(database: db)
3030
} catch {
31-
if #available(iOS 14.0, *) {
32-
Logger().error("🔴 Failed to upload data: \(error)")
33-
} else {
34-
print("🔴 Failed to upload data: \(error)")
35-
}
31+
db.logger.error("Error while uploading data: \(error)", tag: logTag)
3632
}
3733
}
3834
}

Sources/PowerSync/PowerSyncDatabaseProtocol.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ public protocol PowerSyncDatabaseProtocol: Queries {
1111
/// The current sync status.
1212
var currentStatus: SyncStatus { get }
1313

14+
/// Logger used for PowerSync operations
15+
var logger: any LoggerProtocol { get }
16+
1417
/// Wait for the first sync to occur
1518
func waitForFirstSync() async throws
1619

Sources/PowerSync/attachments/AttachmentQueue.swift

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ public struct WatchedAttachmentItem {
4646
public actor AttachmentQueue {
4747
/// Default name of the attachments table
4848
public static let DEFAULT_TABLE_NAME = "attachments"
49+
50+
let logTag = "AttachmentQueue"
4951

5052
/// PowerSync database client
5153
public let db: PowerSyncDatabaseProtocol
@@ -86,7 +88,7 @@ public actor AttachmentQueue {
8688
/**
8789
* Logging interface used for all log operations
8890
*/
89-
// public let logger: Logger
91+
public let logger: any LoggerProtocol
9092

9193
/// Attachment service for interacting with attachment records
9294
public let attachmentsService: AttachmentService
@@ -102,12 +104,13 @@ public actor AttachmentQueue {
102104
remoteStorage: self.remoteStorage,
103105
localStorage: self.localStorage,
104106
attachmentsService: self.attachmentsService,
107+
logger: self.logger,
105108
getLocalUri: { [weak self] filename in
106109
guard let self = self else { return filename }
107110
return await self.getLocalUri(filename)
108111
},
109112
errorHandler: self.errorHandler,
110-
syncThrottle: self.syncThrottleDuration
113+
syncThrottle: self.syncThrottleDuration,
111114
)
112115

113116
/// Initializes the attachment queue
@@ -125,7 +128,7 @@ public actor AttachmentQueue {
125128
syncThrottleDuration: TimeInterval = 1.0,
126129
subdirectories: [String]? = nil,
127130
downloadAttachments: Bool = true,
128-
// logger: Logger = Logger(subsystem: "com.powersync.attachments", category: "AttachmentQueue")
131+
logger: (any LoggerProtocol)? = nil
129132
) {
130133
self.db = db
131134
self.remoteStorage = remoteStorage
@@ -139,12 +142,12 @@ public actor AttachmentQueue {
139142
self.syncThrottleDuration = syncThrottleDuration
140143
self.subdirectories = subdirectories
141144
self.downloadAttachments = downloadAttachments
142-
// self.logger = logger
145+
self.logger = logger ?? db.logger
143146

144147
attachmentsService = AttachmentService(
145148
db: db,
146149
tableName: attachmentsQueueTableName,
147-
// logger: logger,
150+
logger: self.logger,
148151
maxArchivedCount: archivedCacheLimit
149152
)
150153
}
@@ -193,7 +196,7 @@ public actor AttachmentQueue {
193196
try await watchTask.value
194197
} catch {
195198
if !(error is CancellationError) {
196-
// logger.error("Error in sync job: \(error.localizedDescription)")
199+
logger.error("Error in sync job: \(error.localizedDescription)", tag: logTag)
197200
}
198201
}
199202
}

Sources/PowerSync/attachments/AttachmentsService.swift

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import PowerSyncKotlin
99
public class AttachmentService {
1010
private let db: any PowerSyncDatabaseProtocol
1111
private let tableName: String
12-
// private let logger: Logger
12+
private let logger: any LoggerProtocol
13+
private let logTag = "AttachmentService"
1314
private let maxArchivedCount: Int64
1415

1516
/**
@@ -22,12 +23,12 @@ public class AttachmentService {
2223
public init(
2324
db: PowerSyncDatabaseProtocol,
2425
tableName: String,
25-
// logger: Logger,
26+
logger: any LoggerProtocol,
2627
maxArchivedCount: Int64
2728
) {
2829
self.db = db
2930
self.tableName = tableName
30-
// self.logger = logger
31+
self.logger = logger
3132
self.maxArchivedCount = maxArchivedCount
3233
}
3334

@@ -145,7 +146,7 @@ public class AttachmentService {
145146
* Once a change is detected it will initiate a sync of the attachments
146147
*/
147148
public func watchActiveAttachments() throws -> AsyncThrowingStream<[String], Error> {
148-
// logger.i("Watching attachments...")
149+
logger.info("Watching attachments...", tag: logTag)
149150

150151
return try db.watch(
151152
sql: """

Sources/PowerSync/attachments/SyncingService.swift

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ actor SyncingService {
1717
private let syncTriggerSubject = PassthroughSubject<Void, Never>()
1818
private var periodicSyncTimer: Timer?
1919
private var syncTask: Task<Void, Never>?
20+
let logger: any LoggerProtocol
21+
22+
let logTag = "AttachmentSync"
2023

2124
/// Initializes a new instance of `SyncingService`.
2225
///
@@ -31,16 +34,18 @@ actor SyncingService {
3134
remoteStorage: RemoteStorageAdapter,
3235
localStorage: LocalStorageAdapter,
3336
attachmentsService: AttachmentService,
37+
logger: any LoggerProtocol,
3438
getLocalUri: @escaping (String) async -> String,
3539
errorHandler: SyncErrorHandler? = nil,
36-
syncThrottle: TimeInterval = 5.0
40+
syncThrottle: TimeInterval = 5.0,
3741
) {
3842
self.remoteStorage = remoteStorage
3943
self.localStorage = localStorage
4044
self.attachmentsService = attachmentsService
4145
self.getLocalUri = getLocalUri
4246
self.errorHandler = errorHandler
4347
self.syncThrottle = syncThrottle
48+
self.logger = logger
4449

4550
Task { await self.setupSyncFlow() }
4651
}
@@ -74,7 +79,7 @@ actor SyncingService {
7479
_ = try await deleteArchivedAttachments()
7580
} catch {
7681
if error is CancellationError { break }
77-
// logger.error("Sync failure: \(error)")
82+
logger.error("Sync error: \(error)", tag: logTag)
7883
}
7984
}
8085

@@ -167,6 +172,7 @@ actor SyncingService {
167172
/// - Parameter attachment: The attachment to upload.
168173
/// - Returns: The updated attachment with new sync state.
169174
private func uploadAttachment(attachment: Attachment) async throws -> Attachment {
175+
logger.info("Uploading attachment \(attachment.filename)", tag: logTag)
170176
do {
171177
guard let localUri = attachment.localUri else {
172178
throw PowerSyncError.attachmentError("No localUri for attachment \(attachment.id)")
@@ -192,6 +198,7 @@ actor SyncingService {
192198
/// - Parameter attachment: The attachment to download.
193199
/// - Returns: The updated attachment with new sync state.
194200
private func downloadAttachment(attachment: Attachment) async throws -> Attachment {
201+
logger.info("Downloading attachment \(attachment.filename)", tag: logTag)
195202
do {
196203
let attachmentPath = await getLocalUri(attachment.filename)
197204
let fileData = try await remoteStorage.downloadFile(attachment: attachment)
@@ -218,6 +225,7 @@ actor SyncingService {
218225
/// - Parameter attachment: The attachment to delete.
219226
/// - Returns: The updated attachment with archived state.
220227
private func deleteAttachment(attachment: Attachment) async throws -> Attachment {
228+
logger.info("Deleting attachment \(attachment.filename)", tag: logTag)
221229
do {
222230
try await remoteStorage.deleteFile(attachment: attachment)
223231

0 commit comments

Comments
 (0)