Skip to content

Commit d3b95ca

Browse files
committed
Fix more logger usages
1 parent 7cf0973 commit d3b95ca

2 files changed

Lines changed: 50 additions & 54 deletions

File tree

packages/attachments/src/AbstractAttachmentQueue.ts

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AbstractPowerSyncDatabase, Transaction } from '@powersync/common';
1+
import { AbstractPowerSyncDatabase, LogLevels, Transaction } from '@powersync/common';
22
import { ATTACHMENT_TABLE, AttachmentRecord, AttachmentState } from './Schema.js';
33
import { EncodingType, StorageAdapter } from './StorageAdapter.js';
44

@@ -92,7 +92,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
9292
}
9393

9494
get logger() {
95-
return this.powersync.logger ?? console;
95+
return this.powersync.logger;
9696
}
9797

9898
protected get storage() {
@@ -127,7 +127,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
127127
async watchAttachmentIds() {
128128
this.onAttachmentIdsChange(async (ids) => {
129129
const _ids = `${ids.map((id) => `'${id}'`).join(',')}`;
130-
this.logger.debug(`Queuing for sync, attachment IDs: [${_ids}]`);
130+
this.logger.log(LogLevels.debug, `Queuing for sync, attachment IDs: [${_ids}]`);
131131

132132
if (this.initialSync) {
133133
this.initialSync = false;
@@ -155,11 +155,14 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
155155
id: id,
156156
state: AttachmentState.QUEUED_SYNC
157157
});
158-
this.logger.debug(`Attachment (${id}) not found in database, creating new record`);
158+
this.logger.log(LogLevels.debug, `Attachment (${id}) not found in database, creating new record`);
159159
await this.saveToQueue(newRecord);
160160
} else if (record.local_uri == null || !(await this.storage.fileExists(this.getLocalUri(record.local_uri)))) {
161161
// 2. Attachment in database but no local file, mark as queued download
162-
this.logger.debug(`Attachment (${id}) found in database but no local file, marking as queued download`);
162+
this.logger.log(
163+
LogLevels.debug,
164+
`Attachment (${id}) found in database but no local file, marking as queued download`
165+
);
163166
await this.update({
164167
...record,
165168
state: AttachmentState.QUEUED_DOWNLOAD
@@ -245,7 +248,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
245248
filename: record.filename
246249
});
247250
} catch (e) {
248-
this.logger.error(e);
251+
this.logger.log(LogLevels.error, e);
249252
}
250253
}
251254

@@ -271,7 +274,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
271274
const localFilePathUri = this.getLocalUri(record.local_uri);
272275
try {
273276
if (!(await this.storage.fileExists(localFilePathUri))) {
274-
this.logger.warn(`File for ${record.id} does not exist, skipping upload`);
277+
this.logger.log(LogLevels.warn, `File for ${record.id} does not exist, skipping upload`);
275278
await this.update({
276279
...record,
277280
state: AttachmentState.QUEUED_DOWNLOAD
@@ -289,11 +292,11 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
289292
});
290293
// Mark as uploaded
291294
await this.update({ ...record, state: AttachmentState.SYNCED });
292-
this.logger.debug(`Uploaded attachment "${record.id}" to Cloud Storage`);
295+
this.logger.log(LogLevels.debug, `Uploaded attachment "${record.id}" to Cloud Storage`);
293296
return true;
294297
} catch (e: any) {
295298
if (e.error == 'Duplicate') {
296-
this.logger.debug(`File already uploaded, marking ${record.id} as synced`);
299+
this.logger.log(LogLevels.debug, `File already uploaded, marking ${record.id} as synced`);
297300
await this.update({ ...record, state: AttachmentState.SYNCED });
298301
return false;
299302
}
@@ -304,7 +307,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
304307
return true;
305308
}
306309
}
307-
this.logger.error(`UploadAttachment error for record ${JSON.stringify(record, null, 2)}`);
310+
this.logger.log(LogLevels.error, `UploadAttachment error for record ${JSON.stringify(record, null, 2)}`);
308311
return false;
309312
}
310313
}
@@ -318,7 +321,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
318321
}
319322
const localFilePathUri = this.getLocalUri(record.local_uri);
320323
if (await this.storage.fileExists(localFilePathUri)) {
321-
this.logger.debug(`Local file already downloaded, marking "${record.id}" as synced`);
324+
this.logger.log(LogLevels.debug, `Local file already downloaded, marking "${record.id}" as synced`);
322325
await this.update({ ...record, state: AttachmentState.SYNCED });
323326
return true;
324327
}
@@ -349,7 +352,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
349352
media_type: fileBlob.type,
350353
state: AttachmentState.SYNCED
351354
});
352-
this.logger.debug(`Downloaded attachment "${record.id}"`);
355+
this.logger.log(LogLevels.debug, `Downloaded attachment "${record.id}"`);
353356
return true;
354357
} catch (e) {
355358
if (this.options.onDownloadError) {
@@ -359,7 +362,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
359362
return true;
360363
}
361364
}
362-
this.logger.error(`Download attachment error for record ${JSON.stringify(record, null, 2)}`, e);
365+
this.logger.log(LogLevels.error, `Download attachment error for record ${JSON.stringify(record, null, 2)}`, e);
363366
}
364367
return false;
365368
}
@@ -400,7 +403,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
400403
if (!record) {
401404
return;
402405
}
403-
this.logger.debug(`Uploading attachments...`);
406+
this.logger.log(LogLevels.debug, `Uploading attachments...`);
404407
while (record) {
405408
const uploaded = await this.uploadAttachment(record);
406409
if (!uploaded) {
@@ -409,9 +412,9 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
409412
}
410413
record = await this.getNextUploadRecord();
411414
}
412-
this.logger.debug('Finished uploading attachments');
415+
this.logger.log(LogLevels.debug, 'Finished uploading attachments');
413416
} catch (error) {
414-
this.logger.error('Upload failed:', error);
417+
this.logger.log(LogLevels.error, 'Upload failed:', error);
415418
} finally {
416419
this.uploading = false;
417420
}
@@ -468,7 +471,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
468471

469472
this.downloading = true;
470473
try {
471-
this.logger.debug(`Downloading ${this.downloadQueue.size} attachments...`);
474+
this.logger.log(LogLevels.debug, `Downloading ${this.downloadQueue.size} attachments...`);
472475
while (this.downloadQueue.size > 0) {
473476
const id = this.downloadQueue.values().next().value;
474477
this.downloadQueue.delete(id);
@@ -478,9 +481,9 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
478481
}
479482
await this.downloadRecord(record);
480483
}
481-
this.logger.debug('Finished downloading attachments');
484+
this.logger.log(LogLevels.debug, 'Finished downloading attachments');
482485
} catch (e) {
483-
this.logger.error('Downloads failed:', e);
486+
this.logger.log(LogLevels.error, 'Downloads failed:', e);
484487
} finally {
485488
this.downloading = false;
486489
}
@@ -522,7 +525,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
522525
return;
523526
}
524527

525-
this.logger.debug(`Deleting ${res.length} attachments from cache...`);
528+
this.logger.log(LogLevels.debug, `Deleting ${res.length} attachments from cache...`);
526529
await this.powersync.writeTransaction(async (tx) => {
527530
for (const record of res) {
528531
await this.delete(record, tx);
@@ -531,7 +534,7 @@ export abstract class AbstractAttachmentQueue<T extends AttachmentQueueOptions =
531534
}
532535

533536
async clearQueue(): Promise<void> {
534-
this.logger.debug(`Clearing attachment queue...`);
537+
this.logger.log(LogLevels.debug, `Clearing attachment queue...`);
535538
await this.powersync.writeTransaction(async (tx) => {
536539
await tx.execute(`DELETE FROM ${this.table}`);
537540
});
Lines changed: 26 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createBaseLogger, LogLevel, type ILogHandler } from '@powersync/web';
1+
import { createPowerSyncLogger, LogLevels, type PowerSyncLogger } from '@powersync/web';
22
import { createStorage } from 'unstorage';
33
import localStorageDriver from 'unstorage/drivers/session-storage';
44
import mitt from 'mitt';
@@ -15,7 +15,7 @@ const logsStorage = createStorage({
1515
* This composable creates a logger instance that is automatically configured for diagnostics
1616
* recording. The logger stores logs in session storage and emits events for real-time log monitoring.
1717
*
18-
* @param customHandler - Optional custom log handler to process log messages
18+
* @param additional - Optional logger that messages will also be forwarded to.
1919
*
2020
* @returns An object containing:
2121
* - `logger` - The configured ILogHandler instance
@@ -30,38 +30,31 @@ const logsStorage = createStorage({
3030
* // Use it in your PowerSync setup if needed
3131
* ```
3232
*/
33-
export const useDiagnosticsLogger = (customHandler?: ILogHandler) => {
34-
const logger = createBaseLogger();
35-
36-
// Console output: use js-logger's default handler (optional formatter for [PowerSync] prefix)
37-
const consoleHandler = logger.createDefaultHandler({
38-
formatter: (messages, context) => {
39-
messages.unshift(`[PowerSync]${context.name ? ` [${context.name}]` : ''}`);
33+
export const useDiagnosticsLogger = (additional?: PowerSyncLogger) => {
34+
const consoleLogger = createPowerSyncLogger({ minLevel: LogLevels.debug });
35+
36+
const logger: PowerSyncLogger = {
37+
async log(level, ...messages) {
38+
consoleLogger.log(level, ...messages);
39+
40+
// Storage + emitter
41+
const messageArray = Array.from(messages);
42+
const mainMessage = String(messageArray[0] ?? 'Empty log message');
43+
// Store extra args as-is so objects are shown as JSON in LogsTab
44+
const extra =
45+
messageArray.length > 1 ? (messageArray.length === 2 ? messageArray[1] : messageArray.slice(1)) : undefined;
46+
const logObject = {
47+
date: new Date(),
48+
args: [mainMessage, extra]
49+
};
50+
const key = `log:${logObject.date.toISOString()}`;
51+
await logsStorage.set(key, logObject);
52+
emitter.emit('log', { key, value: logObject });
53+
54+
// User callback
55+
additional?.log(level, ...messages);
4056
}
41-
});
42-
43-
logger.setLevel(LogLevel.DEBUG);
44-
logger.setHandler(async (messages, context) => {
45-
consoleHandler(messages, context);
46-
47-
// Storage + emitter
48-
const messageArray = Array.from(messages);
49-
const mainMessage = String(messageArray[0] ?? 'Empty log message');
50-
// Store extra args as-is so objects are shown as JSON in LogsTab
51-
const extra =
52-
messageArray.length > 1 ? (messageArray.length === 2 ? messageArray[1] : messageArray.slice(1)) : undefined;
53-
const logObject = {
54-
date: new Date(),
55-
type: context.level.name.toLowerCase(),
56-
args: [mainMessage, extra, context]
57-
};
58-
const key = `log:${logObject.date.toISOString()}`;
59-
await logsStorage.set(key, logObject);
60-
emitter.emit('log', { key, value: logObject });
61-
62-
// User callback
63-
await customHandler?.(messages, context);
64-
});
57+
};
6558

6659
return { logger, logsStorage, emitter };
6760
};

0 commit comments

Comments
 (0)