Skip to content

Commit 7cf0973

Browse files
committed
Remove JS logger dependency
1 parent f9cb3da commit 7cf0973

22 files changed

Lines changed: 182 additions & 159 deletions

packages/common/package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,7 @@
5959
"test:exports": "attw --pack . --exclude-entrypoints internal/sync_protocol"
6060
},
6161
"dependencies": {
62-
"event-iterator": "^2.0.0",
63-
"js-logger": "catalog:"
62+
"event-iterator": "^2.0.0"
6463
},
6564
"devDependencies": {
6665
"@rollup/plugin-commonjs": "catalog:",

packages/common/src/attachments/AttachmentContext.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { AbstractPowerSyncDatabase } from '../client/AbstractPowerSyncDatabase.js';
2-
import { ILogger } from '../utils/Logger.js';
2+
import { LogLevels, PowerSyncLogger } from '../utils/Logger.js';
33
import { Transaction } from '../db/DBAdapter.js';
44
import { AttachmentRecord, AttachmentState, attachmentFromSql } from './Schema.js';
55

@@ -19,7 +19,7 @@ export class AttachmentContext {
1919
tableName: string;
2020

2121
/** Logger instance for diagnostic information */
22-
logger: ILogger;
22+
logger: PowerSyncLogger;
2323

2424
/** Maximum number of archived attachments to keep before cleanup */
2525
archivedCacheLimit: number = 100;
@@ -34,7 +34,7 @@ export class AttachmentContext {
3434
constructor(
3535
db: AbstractPowerSyncDatabase,
3636
tableName: string = 'attachments',
37-
logger: ILogger,
37+
logger: PowerSyncLogger,
3838
archivedCacheLimit: number
3939
) {
4040
this.db = db;
@@ -233,7 +233,8 @@ export class AttachmentContext {
233233
if (archivedAttachments.length === 0) return false;
234234

235235
await callback?.(archivedAttachments);
236-
this.logger.info(
236+
this.logger.log(
237+
LogLevels.info,
237238
`Deleting ${archivedAttachments.length} archived attachments. Archived attachment exceeds cache archiveCacheLimit of ${this.archivedCacheLimit}.`
238239
);
239240

@@ -254,7 +255,7 @@ export class AttachmentContext {
254255
[JSON.stringify(ids)]
255256
);
256257

257-
this.logger.info(`Deleted ${archivedAttachments.length} archived attachments`);
258+
this.logger.log(LogLevels.info, `Deleted ${archivedAttachments.length} archived attachments`);
258259
return archivedAttachments.length < limit;
259260
}
260261

packages/common/src/attachments/AttachmentQueue.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { AbstractPowerSyncDatabase } from '../client/AbstractPowerSyncDatabase.js';
22
import { DEFAULT_WATCH_THROTTLE_MS } from '../client/watched/WatchedQuery.js';
33
import { DifferentialWatchedQuery } from '../client/watched/processors/DifferentialQueryProcessor.js';
4-
import { ILogger } from '../utils/Logger.js';
4+
import { LogLevels, PowerSyncLogger } from '../utils/Logger.js';
55
import { Transaction } from '../db/DBAdapter.js';
66
import { AttachmentData, LocalStorageAdapter } from './LocalStorageAdapter.js';
77
import { RemoteStorageAdapter } from './RemoteStorageAdapter.js';
@@ -49,7 +49,7 @@ export class AttachmentQueue {
4949
readonly tableName: string;
5050

5151
/** Logger instance for diagnostic information */
52-
readonly logger: ILogger;
52+
readonly logger: PowerSyncLogger;
5353

5454
/** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
5555
* failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
@@ -78,9 +78,9 @@ export class AttachmentQueue {
7878
/** Cleanup function for status change listener */
7979
private statusListenerDispose?: () => void;
8080

81-
private watchActiveAttachments: DifferentialWatchedQuery<AttachmentRecord>;
81+
private watchActiveAttachments!: DifferentialWatchedQuery<AttachmentRecord>;
8282

83-
private watchAttachmentsAbortController: AbortController;
83+
private watchAttachmentsAbortController!: AbortController;
8484

8585
/**
8686
* Creates a new AttachmentQueue instance.
@@ -115,7 +115,7 @@ export class AttachmentQueue {
115115
localStorage: LocalStorageAdapter;
116116
watchAttachments: (onUpdate: (attachment: WatchedAttachmentItem[]) => Promise<void>, signal: AbortSignal) => void;
117117
tableName?: string;
118-
logger?: ILogger;
118+
logger?: PowerSyncLogger;
119119
syncIntervalMs?: number;
120120
syncThrottleDuration?: number;
121121
downloadAttachments?: boolean;
@@ -190,7 +190,7 @@ export class AttachmentQueue {
190190
if (status.connected) {
191191
// Device came online, process attachments immediately
192192
this.syncStorage().catch((error) => {
193-
this.logger.error('Error syncing storage on connection:', error);
193+
this.logger.log(LogLevels.error, 'Error syncing storage on connection:', error);
194194
});
195195
}
196196
}

packages/common/src/attachments/AttachmentService.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { AbstractPowerSyncDatabase } from '../client/AbstractPowerSyncDatabase.js';
22
import { DifferentialWatchedQuery } from '../client/watched/processors/DifferentialQueryProcessor.js';
3-
import { ILogger } from '../utils/Logger.js';
3+
import { PowerSyncLogger, LogLevels } from '../utils/Logger.js';
44
import { Mutex } from '../utils/mutex.js';
55
import { AttachmentContext } from './AttachmentContext.js';
66
import { AttachmentRecord, AttachmentState } from './Schema.js';
@@ -16,7 +16,7 @@ export class AttachmentService {
1616

1717
constructor(
1818
private db: AbstractPowerSyncDatabase,
19-
private logger: ILogger,
19+
private logger: PowerSyncLogger,
2020
private tableName: string = 'attachments',
2121
archivedCacheLimit: number = 100
2222
) {
@@ -28,7 +28,7 @@ export class AttachmentService {
2828
* @returns Watch query that emits changes for queued uploads, downloads, and deletes
2929
*/
3030
watchActiveAttachments({ throttleMs }: { throttleMs?: number } = {}): DifferentialWatchedQuery<AttachmentRecord> {
31-
this.logger.info('Watching active attachments...');
31+
this.logger.log(LogLevels.info, 'Watching active attachments...');
3232
const watch = this.db
3333
.query<AttachmentRecord>({
3434
sql: /* sql */ `

packages/common/src/attachments/SyncingService.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ILogger } from '../utils/Logger.js';
1+
import { LogLevels, PowerSyncLogger } from '../utils/Logger.js';
22
import { AttachmentService } from './AttachmentService.js';
33
import { LocalStorageAdapter } from './LocalStorageAdapter.js';
44
import { RemoteStorageAdapter } from './RemoteStorageAdapter.js';
@@ -16,14 +16,14 @@ export class SyncingService {
1616
private attachmentService: AttachmentService;
1717
private localStorage: LocalStorageAdapter;
1818
private remoteStorage: RemoteStorageAdapter;
19-
private logger: ILogger;
19+
private logger: PowerSyncLogger;
2020
private errorHandler?: AttachmentErrorHandler;
2121

2222
constructor(
2323
attachmentService: AttachmentService,
2424
localStorage: LocalStorageAdapter,
2525
remoteStorage: RemoteStorageAdapter,
26-
logger: ILogger,
26+
logger: PowerSyncLogger,
2727
errorHandler?: AttachmentErrorHandler
2828
) {
2929
this.attachmentService = attachmentService;
@@ -75,7 +75,7 @@ export class SyncingService {
7575
* @throws Error if the attachment has no localUri
7676
*/
7777
async uploadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord> {
78-
this.logger.info(`Uploading attachment ${attachment.filename}`);
78+
this.logger.log(LogLevels.info, `Uploading attachment ${attachment.filename}`);
7979
try {
8080
if (attachment.localUri == null) {
8181
throw new Error(`No localUri for attachment ${attachment.id}`);
@@ -111,7 +111,7 @@ export class SyncingService {
111111
* @returns Updated attachment record with local URI and new state
112112
*/
113113
async downloadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord> {
114-
this.logger.info(`Downloading attachment ${attachment.filename}`);
114+
this.logger.log(LogLevels.info, `Downloading attachment ${attachment.filename}`);
115115
try {
116116
const fileData = await this.remoteStorage.downloadFile(attachment);
117117

@@ -183,7 +183,7 @@ export class SyncingService {
183183
try {
184184
await this.localStorage.deleteFile(attachment.localUri);
185185
} catch (error) {
186-
this.logger.error('Error deleting local file for archived attachment', error);
186+
this.logger.log(LogLevels.error, 'Error deleting local file for archived attachment', error);
187187
}
188188
}
189189
}

packages/common/src/client/AbstractPowerSyncDatabase.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { EventIterator } from 'event-iterator';
2-
import Logger, { ILogger } from 'js-logger';
32
import {
43
BatchedUpdateNotification,
54
DBAdapter,
@@ -46,6 +45,7 @@ import { DEFAULT_WATCH_THROTTLE_MS, WatchCompatibleQuery } from './watched/Watch
4645
import { OnChangeQueryProcessor } from './watched/processors/OnChangeQueryProcessor.js';
4746
import { WatchedQueryComparator } from './watched/processors/comparators.js';
4847
import { Mutex } from '../utils/mutex.js';
48+
import { createPowerSyncLogger, LogLevels, PowerSyncLogger } from '../utils/Logger.js';
4949

5050
export interface DisconnectAndClearOptions {
5151
/** When set to false, data in local-only tables is preserved. */
@@ -59,7 +59,7 @@ export interface BasePowerSyncDatabaseOptions extends AdditionalConnectionOption
5959
* @deprecated Use {@link retryDelayMs} instead as this will be removed in future releases.
6060
*/
6161
retryDelay?: number;
62-
logger?: ILogger;
62+
logger?: PowerSyncLogger;
6363
}
6464

6565
export interface PowerSyncDatabaseOptions extends BasePowerSyncDatabaseOptions {
@@ -225,7 +225,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
225225
readonly triggers: TriggerManager;
226226
protected triggersImpl: TriggerManagerImpl;
227227

228-
logger: ILogger;
228+
logger: PowerSyncLogger;
229229

230230
constructor(options: PowerSyncDatabaseOptionsWithDBAdapter);
231231
constructor(options: PowerSyncDatabaseOptionsWithOpenFactory);
@@ -250,7 +250,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
250250
throw new Error('The provided `database` option is invalid.');
251251
}
252252

253-
this.logger = options.logger ?? Logger.get(`PowerSyncDatabase[${this._database.name}]`);
253+
this.logger = options.logger ?? createPowerSyncLogger({ prefix: `PowerSyncDatabase[${this._database.name}]` });
254254

255255
this.bucketStorageAdapter = this.generateBucketStorageAdapter();
256256
this.closed = false;
@@ -495,7 +495,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
495495
try {
496496
schema.validate();
497497
} catch (ex) {
498-
this.logger.warn('Schema validation failed. Unexpected behaviour could occur', ex);
498+
this.logger.log(LogLevels.warn, 'Schema validation failed. Unexpected behaviour could occur', ex);
499499
}
500500
this._schema = schema;
501501

@@ -1079,7 +1079,7 @@ SELECT * FROM crud_entries;
10791079
* @param options Options for configuring watch behavior
10801080
*/
10811081
watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void {
1082-
const { onResult, onError = (e: Error) => this.logger.error(e) } = handler ?? {};
1082+
const { onResult, onError = (e: Error) => this.logger.log(LogLevels.error, e) } = handler ?? {};
10831083
if (!onResult) {
10841084
throw new Error('onResult is required');
10851085
}
@@ -1240,7 +1240,7 @@ SELECT * FROM crud_entries;
12401240
* @returns A dispose function to stop watching for changes
12411241
*/
12421242
onChangeWithCallback(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void {
1243-
const { onChange, onError = (e: Error) => this.logger.error(e) } = handler ?? {};
1243+
const { onChange, onError = (e: Error) => this.logger.log(LogLevels.error, e) } = handler ?? {};
12441244
if (!onChange) {
12451245
throw new Error('onChange is required');
12461246
}

packages/common/src/client/AbstractPowerSyncOpenFactory.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import Logger from 'js-logger';
1+
import { createPowerSyncLogger } from '../utils/Logger.js';
22
import { DBAdapter } from '../db/DBAdapter.js';
33
import { Schema } from '../db/schema/Schema.js';
44
import { AbstractPowerSyncDatabase, PowerSyncDatabaseOptions } from './AbstractPowerSyncDatabase.js';
@@ -11,7 +11,7 @@ export interface PowerSyncOpenFactoryOptions extends Partial<PowerSyncDatabaseOp
1111

1212
export abstract class AbstractPowerSyncDatabaseOpenFactory {
1313
constructor(protected options: PowerSyncOpenFactoryOptions) {
14-
options.logger = options.logger ?? Logger.get(`PowerSync ${this.options.dbFilename}`);
14+
options.logger = options.logger ?? createPowerSyncLogger({ prefix: `PowerSync ${this.options.dbFilename}` });
1515
}
1616

1717
/**

packages/common/src/client/ConnectionManager.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ILogger } from 'js-logger';
1+
import { LogLevels, PowerSyncLogger } from '../utils/Logger.js';
22
import { SyncStatus } from '../db/crud/SyncStatus.js';
33
import { BaseListener, BaseObserver } from '../utils/BaseObserver.js';
44
import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnector.js';
@@ -51,7 +51,7 @@ export interface ConnectionManagerOptions {
5151
options: CreateSyncImplementationOptions
5252
): Promise<ConnectionManagerSyncImplementationResult>;
5353

54-
logger: ILogger;
54+
logger: PowerSyncLogger;
5555
}
5656

5757
type StoredConnectionOptions = {
@@ -194,7 +194,10 @@ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
194194
this.syncStreamInitPromise = new Promise(async (resolve, reject) => {
195195
try {
196196
if (!this.pendingConnectionOptions) {
197-
this.logger.debug('No pending connection options found, not creating sync stream implementation');
197+
this.logger.log(
198+
LogLevels.debug,
199+
'No pending connection options found, not creating sync stream implementation'
200+
);
198201
// A disconnect could have cleared this.
199202
resolve();
200203
return;
@@ -236,7 +239,7 @@ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
236239
// and this point. Awaiting here allows the sync stream to be cleared if disconnected.
237240
await this.disconnectingPromise;
238241

239-
this.logger.debug('Attempting to connect to PowerSync instance');
242+
this.logger.log(LogLevels.debug, 'Attempting to connect to PowerSync instance');
240243
await this.syncStreamImplementation?.connect(appliedOptions!);
241244
}
242245

@@ -350,7 +353,7 @@ class ActiveSubscription {
350353
constructor(
351354
readonly name: string,
352355
readonly parameters: Record<string, any> | null,
353-
readonly logger: ILogger,
356+
readonly logger: PowerSyncLogger,
354357
readonly waitForFirstSync: (abort?: AbortSignal) => Promise<void>,
355358
private clearSubscription: () => void
356359
) {}
@@ -395,7 +398,8 @@ class SyncStreamSubscriptionHandle implements SyncStreamSubscription {
395398
const _finalizer =
396399
'FinalizationRegistry' in globalThis
397400
? new FinalizationRegistry<ActiveSubscription>((sub) => {
398-
sub.logger.warn(
401+
sub.logger.log(
402+
LogLevels.warn,
399403
`A subscription to ${sub.name} with params ${JSON.stringify(sub.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`
400404
);
401405
})

packages/common/src/client/sync/bucket/SqliteBucketStorage.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import Logger, { ILogger } from 'js-logger';
1+
import { LogLevels, PowerSyncLogger } from '../../../utils/Logger.js';
22
import { DBAdapter, extractTableUpdates, Transaction } from '../../../db/DBAdapter.js';
33
import { BaseObserver } from '../../../utils/BaseObserver.js';
44
import { MAX_OP_ID } from '../../constants.js';
@@ -18,7 +18,7 @@ export class SqliteBucketStorage extends BaseObserver<BucketStorageListener> imp
1818

1919
constructor(
2020
private db: DBAdapter,
21-
private logger: ILogger = Logger.get('SqliteBucketStorage')
21+
private logger: PowerSyncLogger
2222
) {
2323
super();
2424
this.tableNames = new Set();
@@ -84,7 +84,10 @@ export class SqliteBucketStorage extends BaseObserver<BucketStorageListener> imp
8484
const anyData = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');
8585
if (anyData.rows?.length) {
8686
// if isNotEmpty
87-
this.logger.debug(`New data uploaded since write checkpoint ${opId} - need new write checkpoint`);
87+
this.logger.log(
88+
LogLevels.debug,
89+
`New data uploaded since write checkpoint ${opId} - need new write checkpoint`
90+
);
8891
return false;
8992
}
9093

@@ -96,15 +99,16 @@ export class SqliteBucketStorage extends BaseObserver<BucketStorageListener> imp
9699

97100
const seqAfter: number = rs.rows?.item(0)['seq'];
98101
if (seqAfter != seqBefore) {
99-
this.logger.debug(
102+
this.logger.log(
103+
LogLevels.debug,
100104
`New data uploaded since write checpoint ${opId} - need new write checkpoint (sequence updated)`
101105
);
102106

103107
// New crud data may have been uploaded since we got the checkpoint. Abort.
104108
return false;
105109
}
106110

107-
this.logger.debug(`Updating target write checkpoint to ${opId}`);
111+
this.logger.log(LogLevels.debug, `Updating target write checkpoint to ${opId}`);
108112
await tx.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'", [opId]);
109113
return true;
110114
});

0 commit comments

Comments
 (0)