Skip to content

Commit 0460455

Browse files
committed
Define a log prefix on child loggers.
1 parent a369964 commit 0460455

File tree

11 files changed

+187
-120
lines changed

11 files changed

+187
-120
lines changed

libs/lib-services/src/logger/Logger.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,22 @@
11
import winston from 'winston';
22

3+
const prefixFormat = winston.format((info) => {
4+
if (info.prefix) {
5+
info.message = `${info.prefix}${info.message}`;
6+
}
7+
return {
8+
...info,
9+
prefix: undefined
10+
};
11+
});
12+
313
export namespace LogFormat {
4-
export const development = winston.format.combine(winston.format.colorize({ level: true }), winston.format.simple());
5-
export const production = winston.format.combine(winston.format.timestamp(), winston.format.json());
14+
export const development = winston.format.combine(
15+
prefixFormat(),
16+
winston.format.colorize({ level: true }),
17+
winston.format.simple()
18+
);
19+
export const production = winston.format.combine(prefixFormat(), winston.format.timestamp(), winston.format.json());
620
}
721

822
export const logger = winston.createLogger();

modules/module-mongodb-storage/src/storage/implementation/MongoBucketBatch.ts

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import {
77
container,
88
ErrorCode,
99
errors,
10-
logger,
10+
Logger,
11+
logger as defaultLogger,
1112
ReplicationAssertionError,
1213
ServiceError
1314
} from '@powersync/lib-services-framework';
@@ -55,12 +56,16 @@ export interface MongoBucketBatchOptions {
5556
skipExistingRows: boolean;
5657

5758
markRecordUnavailable: BucketStorageMarkRecordUnavailable | undefined;
59+
60+
logger?: Logger;
5861
}
5962

6063
export class MongoBucketBatch
6164
extends BaseObserver<storage.BucketBatchStorageListener>
6265
implements storage.BucketStorageBatch
6366
{
67+
private logger: Logger;
68+
6469
private readonly client: mongo.MongoClient;
6570
public readonly db: PowerSyncMongo;
6671
public readonly session: mongo.ClientSession;
@@ -96,6 +101,7 @@ export class MongoBucketBatch
96101

97102
constructor(options: MongoBucketBatchOptions) {
98103
super();
104+
this.logger = options.logger ?? defaultLogger;
99105
this.client = options.db.client;
100106
this.db = options.db;
101107
this.group_id = options.groupId;
@@ -242,7 +248,9 @@ export class MongoBucketBatch
242248
current_data_lookup.set(cacheKey(doc._id.t, doc._id.k), doc);
243249
}
244250

245-
let persistedBatch: PersistedBatch | null = new PersistedBatch(this.group_id, transactionSize);
251+
let persistedBatch: PersistedBatch | null = new PersistedBatch(this.group_id, transactionSize, {
252+
logger: this.logger
253+
});
246254

247255
for (let op of b) {
248256
if (resumeBatch) {
@@ -329,7 +337,7 @@ export class MongoBucketBatch
329337
this.markRecordUnavailable(record);
330338
} else {
331339
// Log to help with debugging if there was a consistency issue
332-
logger.warn(
340+
this.logger.warn(
333341
`Cannot find previous record for update on ${record.sourceTable.qualifiedName}: ${beforeId} / ${record.before?.id}`
334342
);
335343
}
@@ -350,7 +358,7 @@ export class MongoBucketBatch
350358
existing_lookups = [];
351359
// Log to help with debugging if there was a consistency issue
352360
if (this.storeCurrentData) {
353-
logger.warn(
361+
this.logger.warn(
354362
`Cannot find previous record for delete on ${record.sourceTable.qualifiedName}: ${beforeId} / ${record.before?.id}`
355363
);
356364
}
@@ -447,7 +455,7 @@ export class MongoBucketBatch
447455
}
448456
}
449457
);
450-
logger.error(
458+
this.logger.error(
451459
`Failed to evaluate data query on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${error.error}`
452460
);
453461
}
@@ -487,7 +495,7 @@ export class MongoBucketBatch
487495
}
488496
}
489497
);
490-
logger.error(
498+
this.logger.error(
491499
`Failed to evaluate parameter query on ${record.sourceTable.qualifiedName}.${after.id}: ${error.error}`
492500
);
493501
}
@@ -541,7 +549,7 @@ export class MongoBucketBatch
541549
if (e instanceof mongo.MongoError && e.hasErrorLabel('TransientTransactionError')) {
542550
// Likely write conflict caused by concurrent write stream replicating
543551
} else {
544-
logger.warn('Transaction error', e as Error);
552+
this.logger.warn('Transaction error', e as Error);
545553
}
546554
await timers.setTimeout(Math.random() * 50);
547555
throw e;
@@ -566,7 +574,7 @@ export class MongoBucketBatch
566574
await this.withTransaction(async () => {
567575
flushTry += 1;
568576
if (flushTry % 10 == 0) {
569-
logger.info(`${this.slot_name} ${description} - try ${flushTry}`);
577+
this.logger.info(`${description} - try ${flushTry}`);
570578
}
571579
if (flushTry > 20 && Date.now() > lastTry) {
572580
throw new ServiceError(ErrorCode.PSYNC_S1402, 'Max transaction tries exceeded');
@@ -636,12 +644,12 @@ export class MongoBucketBatch
636644
if (this.last_checkpoint_lsn != null && lsn < this.last_checkpoint_lsn) {
637645
// When re-applying transactions, don't create a new checkpoint until
638646
// we are past the last transaction.
639-
logger.info(`Re-applied transaction ${lsn} - skipping checkpoint`);
647+
this.logger.info(`Re-applied transaction ${lsn} - skipping checkpoint`);
640648
return false;
641649
}
642650
if (lsn < this.no_checkpoint_before_lsn) {
643651
if (Date.now() - this.lastWaitingLogThottled > 5_000) {
644-
logger.info(
652+
this.logger.info(
645653
`Waiting until ${this.no_checkpoint_before_lsn} before creating checkpoint, currently at ${lsn}. Persisted op: ${this.persisted_op}`
646654
);
647655
this.lastWaitingLogThottled = Date.now();
@@ -713,7 +721,7 @@ export class MongoBucketBatch
713721
if (this.persisted_op != null) {
714722
// The commit may have been skipped due to "no_checkpoint_before_lsn".
715723
// Apply it now if relevant
716-
logger.info(`Commit due to keepalive at ${lsn} / ${this.persisted_op}`);
724+
this.logger.info(`Commit due to keepalive at ${lsn} / ${this.persisted_op}`);
717725
return await this.commit(lsn);
718726
}
719727

@@ -777,7 +785,7 @@ export class MongoBucketBatch
777785
return null;
778786
}
779787

780-
logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);
788+
this.logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);
781789

782790
this.batch ??= new OperationBatch();
783791
this.batch.push(new RecordOperation(record));
@@ -848,7 +856,7 @@ export class MongoBucketBatch
848856
session: session
849857
});
850858
const batch = await cursor.toArray();
851-
const persistedBatch = new PersistedBatch(this.group_id, 0);
859+
const persistedBatch = new PersistedBatch(this.group_id, 0, { logger: this.logger });
852860

853861
for (let value of batch) {
854862
persistedBatch.saveBucketData({

modules/module-mongodb-storage/src/storage/implementation/MongoSyncBucketStorage.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ export class MongoSyncBucketStorage
138138
const checkpoint_lsn = doc?.last_checkpoint_lsn ?? null;
139139

140140
await using batch = new MongoBucketBatch({
141+
logger: options.logger,
141142
db: this.db,
142143
syncRules: this.sync_rules.parsed(options).sync_rules,
143144
groupId: this.group_id,

modules/module-mongodb-storage/src/storage/implementation/PersistedBatch.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { JSONBig } from '@powersync/service-jsonbig';
33
import { EvaluatedParameters, EvaluatedRow } from '@powersync/service-sync-rules';
44
import * as bson from 'bson';
55

6-
import { logger } from '@powersync/lib-services-framework';
6+
import { Logger, logger as defaultLogger } from '@powersync/lib-services-framework';
77
import { InternalOpId, storage, utils } from '@powersync/service-core';
88
import { currentBucketKey, MAX_ROW_SIZE } from './MongoBucketBatch.js';
99
import { MongoIdSequence } from './MongoIdSequence.js';
@@ -46,6 +46,7 @@ const MAX_TRANSACTION_DOC_COUNT = 2_000;
4646
* multiple transactions.
4747
*/
4848
export class PersistedBatch {
49+
logger: Logger;
4950
bucketData: mongo.AnyBulkWriteOperation<BucketDataDocument>[] = [];
5051
bucketParameters: mongo.AnyBulkWriteOperation<BucketParameterDocument>[] = [];
5152
currentData: mongo.AnyBulkWriteOperation<CurrentDataDocument>[] = [];
@@ -63,9 +64,11 @@ export class PersistedBatch {
6364

6465
constructor(
6566
private group_id: number,
66-
writtenSize: number
67+
writtenSize: number,
68+
options?: { logger?: Logger }
6769
) {
6870
this.currentSize = writtenSize;
71+
this.logger = options?.logger ?? defaultLogger;
6972
}
7073

7174
private incrementBucket(bucket: string, op_id: InternalOpId) {
@@ -107,7 +110,7 @@ export class PersistedBatch {
107110
// the BSON size is small enough, but the JSON size is too large.
108111
// In these cases, we can't store the data, so we skip it, or generate a REMOVE operation if the row
109112
// was synced previously.
110-
logger.error(`powersync_${this.group_id} Row ${key} too large: ${recordData.length} bytes. Removing.`);
113+
this.logger.error(`Row ${key} too large: ${recordData.length} bytes. Removing.`);
111114
continue;
112115
}
113116

@@ -303,8 +306,8 @@ export class PersistedBatch {
303306
}
304307

305308
const duration = performance.now() - startAt;
306-
logger.info(
307-
`powersync_${this.group_id} Flushed ${this.bucketData.length} + ${this.bucketParameters.length} + ${
309+
this.logger.info(
310+
`Flushed ${this.bucketData.length} + ${this.bucketParameters.length} + ${
308311
this.currentData.length
309312
} updates, ${Math.round(this.currentSize / 1024)}kb in ${duration.toFixed(0)}ms. Last op_id: ${this.debugLastOpId}`
310313
);

0 commit comments

Comments
 (0)