refactor(server): reduce server logs (#11931)

close CLOUD-201
This commit is contained in:
fengmk2
2025-04-23 11:41:47 +00:00
parent ddb739fa13
commit ff133d1267
18 changed files with 70 additions and 46 deletions

View File

@@ -68,7 +68,7 @@ export class EventBus
this.cls.run(() => { this.cls.run(() => {
requestId = requestId ?? genRequestId('event'); requestId = requestId ?? genRequestId('event');
this.cls.set(CLS_ID, requestId); this.cls.set(CLS_ID, requestId);
this.logger.log(`Server Event: ${event} (Received)`); this.logger.debug(`Server Event: ${event} (Received)`);
this.emit(event, payload); this.emit(event, payload);
}); });
}); });
@@ -78,7 +78,7 @@ export class EventBus
* Emit event to trigger all listeners on current instance * Emit event to trigger all listeners on current instance
*/ */
async emitAsync<T extends EventName>(event: T, payload: Events[T]) { async emitAsync<T extends EventName>(event: T, payload: Events[T]) {
this.logger.log(`Dispatch event: ${event} (async)`); this.logger.debug(`Dispatch event: ${event} (async)`);
return await this.emitter.emitAsync(event, payload); return await this.emitter.emitAsync(event, payload);
} }
@@ -86,7 +86,7 @@ export class EventBus
* Emit event to trigger all listeners on current instance * Emit event to trigger all listeners on current instance
*/ */
emit<T extends EventName>(event: T, payload: Events[T]) { emit<T extends EventName>(event: T, payload: Events[T]) {
this.logger.log(`Dispatch event: ${event}`); this.logger.debug(`Dispatch event: ${event}`);
// NOTE(@forehalo): // NOTE(@forehalo):
// Because all event handlers are wrapped in promisified metrics and cls context, they will always run in standalone tick. // Because all event handlers are wrapped in promisified metrics and cls context, they will always run in standalone tick.
@@ -103,7 +103,7 @@ export class EventBus
* Broadcast event to trigger all listeners on all instance in cluster * Broadcast event to trigger all listeners on all instance in cluster
*/ */
broadcast<T extends EventName>(event: T, payload: Events[T]) { broadcast<T extends EventName>(event: T, payload: Events[T]) {
this.logger.log(`Server Event: ${event} (Send)`); this.logger.debug(`Server Event: ${event} (Send)`);
this.server?.serverSideEmit('broadcast', event, payload, this.cls.getId()); this.server?.serverSideEmit('broadcast', event, payload, this.cls.getId());
} }

View File

@@ -68,9 +68,9 @@ export class JobExecutor implements OnModuleDestroy {
async () => { async () => {
const signature = `[${name}] (${handler.name})`; const signature = `[${name}] (${handler.name})`;
try { try {
this.logger.log(`Job started: ${signature}`); this.logger.debug(`Job started: ${signature}`);
const ret = await handler.fn(payload); const ret = await handler.fn(payload);
this.logger.log(`Job finished: ${signature}, signal=${ret}`); this.logger.debug(`Job finished: ${signature}, signal=${ret}`);
return ret; return ret;
} catch (e) { } catch (e) {
this.logger.error(`Job failed: ${signature}`, e); this.logger.error(`Job failed: ${signature}`, e);

View File

@@ -30,7 +30,7 @@ export class JobQueue {
} as JobData<T>, } as JobData<T>,
opts opts
); );
this.logger.log(`Job [${name}] added; id=${job.id}`); this.logger.debug(`Job [${name}] added; id=${job.id}`);
return job; return job;
} }

View File

@@ -32,7 +32,7 @@ export class DocRpcController {
if (!doc) { if (!doc) {
throw new NotFound('Doc not found'); throw new NotFound('Doc not found');
} }
this.logger.log( this.logger.debug(
`get doc ${docId} from workspace ${workspaceId}, size: ${doc.bin.length}` `get doc ${docId} from workspace ${workspaceId}, size: ${doc.bin.length}`
); );
res.setHeader('x-doc-timestamp', doc.timestamp.toString()); res.setHeader('x-doc-timestamp', doc.timestamp.toString());
@@ -59,7 +59,7 @@ export class DocRpcController {
if (!diff) { if (!diff) {
throw new NotFound('Doc not found'); throw new NotFound('Doc not found');
} }
this.logger.log( this.logger.debug(
`get doc diff ${docId} from workspace ${workspaceId}, missing size: ${diff.missing.length}, old state size: ${stateVector?.length}, new state size: ${diff.state.length}` `get doc diff ${docId} from workspace ${workspaceId}, missing size: ${diff.missing.length}, old state size: ${stateVector?.length}, new state size: ${diff.state.length}`
); );
res.setHeader('x-doc-timestamp', diff.timestamp.toString()); res.setHeader('x-doc-timestamp', diff.timestamp.toString());
@@ -86,7 +86,7 @@ export class DocRpcController {
if (!content) { if (!content) {
throw new NotFound('Doc not found'); throw new NotFound('Doc not found');
} }
this.logger.log(`get doc content ${docId} from workspace ${workspaceId}`); this.logger.debug(`get doc content ${docId} from workspace ${workspaceId}`);
return content; return content;
} }
@@ -98,7 +98,7 @@ export class DocRpcController {
if (!content) { if (!content) {
throw new NotFound('Workspace not found'); throw new NotFound('Workspace not found');
} }
this.logger.log(`get workspace content ${workspaceId}`); this.logger.debug(`get workspace content ${workspaceId}`);
return content; return content;
} }
} }

View File

@@ -103,7 +103,7 @@ export class MailSender {
} }
metrics.mail.counter('accepted_total').add(1, { name }); metrics.mail.counter('accepted_total').add(1, { name });
this.logger.log(`Mail [${name}] sent successfully.`); this.logger.debug(`Mail [${name}] sent successfully.`);
if (this.usingTestAccount) { if (this.usingTestAccount) {
this.logger.debug( this.logger.debug(
` ⚙️ Mail preview url: ${getTestMessageUrl(result)}` ` ⚙️ Mail preview url: ${getTestMessageUrl(result)}`

View File

@@ -78,7 +78,7 @@ export class NotificationService {
}, },
}, },
}); });
this.logger.log(`Mention email sent to user ${receiver.id}`); this.logger.debug(`Mention email sent to user ${receiver.id}`);
} }
async createInvitation(input: InvitationNotificationCreate) { async createInvitation(input: InvitationNotificationCreate) {
@@ -123,7 +123,7 @@ export class NotificationService {
url: inviteUrl, url: inviteUrl,
}, },
}); });
this.logger.log( this.logger.debug(
`Invitation email sent to user ${receiver.id} for workspace ${input.body.workspaceId}` `Invitation email sent to user ${receiver.id} for workspace ${input.body.workspaceId}`
); );
} }
@@ -179,7 +179,7 @@ export class NotificationService {
), ),
}, },
}); });
this.logger.log( this.logger.debug(
`Invitation accepted email sent to user ${inviter.id} for workspace ${workspaceId}` `Invitation accepted email sent to user ${inviter.id} for workspace ${workspaceId}`
); );
} }
@@ -244,7 +244,7 @@ export class NotificationService {
), ),
}, },
}); });
this.logger.log( this.logger.debug(
`Invitation review request email sent to user ${reviewer.id} for workspace ${workspaceId}` `Invitation review request email sent to user ${reviewer.id} for workspace ${workspaceId}`
); );
} }
@@ -283,7 +283,7 @@ export class NotificationService {
url: this.url.link(`/workspace/${workspaceId}`), url: this.url.link(`/workspace/${workspaceId}`),
}, },
}); });
this.logger.log( this.logger.debug(
`Invitation review approved email sent to user ${receiver.id} for workspace ${workspaceId}` `Invitation review approved email sent to user ${receiver.id} for workspace ${workspaceId}`
); );
} }
@@ -321,7 +321,7 @@ export class NotificationService {
}, },
}, },
}); });
this.logger.log( this.logger.debug(
`Invitation review declined email sent to user ${receiver.id} for workspace ${workspaceId}` `Invitation review declined email sent to user ${receiver.id} for workspace ${workspaceId}`
); );
} }

View File

@@ -36,7 +36,7 @@ export class DocAccessController extends AccessController<'doc'> {
const allow = permissions[action] || false; const allow = permissions[action] || false;
if (!allow) { if (!allow) {
this.logger.log('Doc access check failed', { this.logger.debug('Doc access check failed', {
action, action,
resource, resource,
role, role,

View File

@@ -40,7 +40,7 @@ export class WorkspaceAccessController extends AccessController<'ws'> {
const allow = permissions[action] || false; const allow = permissions[action] || false;
if (!allow) { if (!allow) {
this.logger.log('Workspace access check failed', { this.logger.debug('Workspace access check failed', {
action, action,
resource, resource,
role, role,

View File

@@ -152,13 +152,15 @@ export class SpaceSyncGateway
handleConnection() { handleConnection() {
this.connectionCount++; this.connectionCount++;
this.logger.log(`New connection, total: ${this.connectionCount}`); this.logger.debug(`New connection, total: ${this.connectionCount}`);
metrics.socketio.gauge('connections').record(this.connectionCount); metrics.socketio.gauge('connections').record(this.connectionCount);
} }
handleDisconnect() { handleDisconnect() {
this.connectionCount--; this.connectionCount--;
this.logger.log(`Connection disconnected, total: ${this.connectionCount}`); this.logger.debug(
`Connection disconnected, total: ${this.connectionCount}`
);
metrics.socketio.gauge('connections').record(this.connectionCount); metrics.socketio.gauge('connections').record(this.connectionCount);
} }

View File

@@ -536,7 +536,7 @@ export class DocResolver {
@Args('input') input: UpdateDocDefaultRoleInput @Args('input') input: UpdateDocDefaultRoleInput
) { ) {
if (input.role === DocRole.Owner) { if (input.role === DocRole.Owner) {
this.logger.log( this.logger.debug(
`Doc default role can not be owner (${JSON.stringify(input)})` `Doc default role can not be owner (${JSON.stringify(input)})`
); );
throw new DocDefaultRoleCanNotBeOwner(); throw new DocDefaultRoleCanNotBeOwner();
@@ -559,7 +559,7 @@ export class DocResolver {
await this.ac.user(user.id).doc(input).assert('Doc.Users.Manage'); await this.ac.user(user.id).doc(input).assert('Doc.Users.Manage');
} catch (error) { } catch (error) {
if (error instanceof DocActionDenied) { if (error instanceof DocActionDenied) {
this.logger.log( this.logger.debug(
`User does not have permission to update page default role (${JSON.stringify( `User does not have permission to update page default role (${JSON.stringify(
{ {
...pairs, ...pairs,

View File

@@ -112,9 +112,11 @@ export class DocModel extends BaseModel {
}, },
}, },
}); });
this.logger.log( if (count > 0) {
`Deleted ${count} updates for workspace ${workspaceId} doc ${docId}` this.logger.log(
); `Deleted ${count} updates for workspace ${workspaceId} doc ${docId}`
);
}
return count; return count;
} }

View File

@@ -47,7 +47,7 @@ export class HistoryModel extends BaseModel {
expiredAt: new Date(Date.now() + maxAge), expiredAt: new Date(Date.now() + maxAge),
}, },
}); });
this.logger.log( this.logger.debug(
`Created history ${row.timestamp} for ${snapshot.docId} in ${snapshot.spaceId}` `Created history ${row.timestamp} for ${snapshot.docId} in ${snapshot.spaceId}`
); );
return { return {
@@ -163,7 +163,9 @@ export class HistoryModel extends BaseModel {
}, },
}, },
}); });
this.logger.log(`Deleted ${count} expired histories`); if (count > 0) {
this.logger.log(`Deleted ${count} expired histories`);
}
return count; return count;
} }
} }

View File

@@ -133,7 +133,7 @@ export class NotificationModel extends BaseModel {
type: NotificationType.Mention, type: NotificationType.Mention,
body: data.body, body: data.body,
}); });
this.logger.log( this.logger.debug(
`Created mention notification:${row.id} for user:${data.userId} in workspace:${data.body.workspaceId}` `Created mention notification:${row.id} for user:${data.userId} in workspace:${data.body.workspaceId}`
); );
return row as MentionNotification; return row as MentionNotification;
@@ -154,7 +154,7 @@ export class NotificationModel extends BaseModel {
type, type,
body: data.body, body: data.body,
}); });
this.logger.log( this.logger.debug(
`Created ${type} notification ${row.id} to user ${data.userId} in workspace ${data.body.workspaceId}` `Created ${type} notification ${row.id} to user ${data.userId} in workspace ${data.body.workspaceId}`
); );
return row as InvitationNotification; return row as InvitationNotification;
@@ -171,7 +171,7 @@ export class NotificationModel extends BaseModel {
type, type,
body: data.body, body: data.body,
}); });
this.logger.log( this.logger.debug(
`Created ${type} notification ${row.id} to user ${data.userId} in workspace ${data.body.workspaceId}` `Created ${type} notification ${row.id} to user ${data.userId} in workspace ${data.body.workspaceId}`
); );
return row as InvitationReviewDeclinedNotification; return row as InvitationReviewDeclinedNotification;
@@ -239,7 +239,9 @@ export class NotificationModel extends BaseModel {
// delete notifications that are older than one year // delete notifications that are older than one year
where: { createdAt: { lte: new Date(Date.now() - ONE_YEAR) } }, where: { createdAt: { lte: new Date(Date.now() - ONE_YEAR) } },
}); });
this.logger.log(`Deleted ${count} expired notifications`); if (count > 0) {
this.logger.log(`Deleted ${count} expired notifications`);
}
return count; return count;
} }

View File

@@ -37,7 +37,9 @@ export class SessionModel extends BaseModel {
id, id,
}, },
}); });
this.logger.log(`Deleted session success by id: ${id}`); if (count > 0) {
this.logger.log(`Deleted session success by id: ${id}`);
}
return count; return count;
} }
@@ -134,20 +136,24 @@ export class SessionModel extends BaseModel {
sessionId, sessionId,
}, },
}); });
this.logger.log( if (count > 0) {
`Deleted user sessions success by userId: ${userId} and sessionId: ${sessionId}` this.logger.log(
); `Deleted user sessions success by userId: ${userId} and sessionId: ${sessionId}`
);
}
return count; return count;
} }
async cleanExpiredUserSessions() { async cleanExpiredUserSessions() {
const result = await this.db.userSession.deleteMany({ const { count } = await this.db.userSession.deleteMany({
where: { where: {
expiresAt: { expiresAt: {
lte: new Date(), lte: new Date(),
}, },
}, },
}); });
this.logger.log(`Cleaned ${result.count} expired user sessions`); if (count > 0) {
this.logger.log(`Cleaned ${count} expired user sessions`);
}
} }
} }

View File

@@ -92,13 +92,15 @@ export class UserDocModel extends BaseModel {
* Delete a user doc by userId and docId. * Delete a user doc by userId and docId.
*/ */
async delete(userId: string, docId: string) { async delete(userId: string, docId: string) {
await this.db.userSnapshot.deleteMany({ const { count } = await this.db.userSnapshot.deleteMany({
where: { where: {
userId, userId,
id: docId, id: docId,
}, },
}); });
this.logger.log(`Deleted user ${userId} doc ${docId}`); if (count > 0) {
this.logger.log(`Deleted user ${userId} doc ${docId}`);
}
} }
/** /**
@@ -110,7 +112,9 @@ export class UserDocModel extends BaseModel {
userId, userId,
}, },
}); });
this.logger.log(`Deleted user ${userId} ${count} docs`); if (count > 0) {
this.logger.log(`Deleted user ${userId} ${count} docs`);
}
return count; return count;
} }
} }

View File

@@ -36,7 +36,7 @@ export class UserSettingsModel extends BaseModel {
payload, payload,
}, },
}); });
this.logger.log(`UserSettings updated for user ${userId}`); this.logger.debug(`UserSettings updated for user ${userId}`);
return payload; return payload;
} }

View File

@@ -303,7 +303,7 @@ export class UserModel extends BaseModel {
const account = await this.db.connectedAccount.create({ const account = await this.db.connectedAccount.create({
data, data,
}); });
this.logger.log( this.logger.debug(
`Connected account ${account.provider}:${account.id} created` `Connected account ${account.provider}:${account.id} created`
); );
return account; return account;

View File

@@ -122,7 +122,11 @@ export class VerificationTokenModel extends BaseModel {
type, type,
}, },
}); });
this.logger.log(`Deleted token success by type ${type} and token ${token}`); if (count > 0) {
this.logger.log(
`Deleted token success by type ${type} and token ${token}`
);
}
return count; return count;
} }
@@ -137,7 +141,9 @@ export class VerificationTokenModel extends BaseModel {
}, },
}, },
}); });
this.logger.log(`Cleaned ${count} expired tokens`); if (count > 0) {
this.logger.log(`Cleaned ${count} expired tokens`);
}
return count; return count;
} }
} }