The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Attach registration, version, source and error code to app logs (#28283)
martmull78f514169d85
diff --git a/packages/twenty-server/src/database/clickhouse/migrations/015-add-monitoring-columns-to-application-log.sql b/packages/twenty-server/src/database/clickhouse/migrations/015-add-monitoring-columns-to-application-log.sqlnew file mode 100644index 00000000000..74416ba62e4--- /dev/null+++ b/packages/twenty-server/src/database/clickhouse/migrations/015-add-monitoring-columns-to-application-log.sql@@ -0,0 +1,7 @@+ALTER TABLE applicationLog ADD COLUMN IF NOT EXISTS applicationRegistrationId String DEFAULT '';++ALTER TABLE applicationLog ADD COLUMN IF NOT EXISTS applicationVersion String DEFAULT '';++ALTER TABLE applicationLog ADD COLUMN IF NOT EXISTS source LowCardinality(String) DEFAULT 'LOGIC_FUNCTION';++ALTER TABLE applicationLog ADD COLUMN IF NOT EXISTS errorCode LowCardinality(String) DEFAULT '';diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/__tests__/application-install.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/__tests__/application-install.service.spec.tsindex ca3a50d72a4..e059b05d4d3 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-install/__tests__/application-install.service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/__tests__/application-install.service.spec.ts@@ -23,6 +23,7 @@ import { type CacheLockService } from 'src/engine/core-modules/cache-lock/cache-import { type FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';import { type LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';+import { type EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.service';import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';@@ -94,6 +95,7 @@ describe('ApplicationInstallService', () => {{} as MessageQueueService,{} as WorkspaceCacheService,{ incrementCounterBy: jest.fn() } as unknown as MetricsService,+ { recordApplicationLogs: jest.fn() } as unknown as EventLogEmitterService,);const install = () =>diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.module.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.module.tsindex c4527f8ed71..c8eed98d9b0 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.module.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.module.ts@@ -16,6 +16,7 @@ import { InstallApplicationCommand } from 'src/engine/core-modules/application/aimport { ApplicationLifecycleJobService } from 'src/engine/core-modules/application/application-install/services/application-lifecycle-job.service';import { ApplicationUninstallRunnerService } from 'src/engine/core-modules/application/application-install/services/application-uninstall-runner.service';import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';+import { EventLogEmitterModule } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.module';import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';@@ -39,6 +40,7 @@ import { ApplicationRegistrationVersionModule } from 'src/engine/core-modules/apApplicationPackageModule,MarketplaceModule,CacheLockModule,+ EventLogEmitterModule,MetricsModule,PermissionsModule,WorkspaceCacheModule,diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.tsindex 83a54a41a43..9f6025ebf94 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts@@ -43,8 +43,11 @@ import {import { APPLICATION_LIFECYCLE_LOCK_OPTIONS } from 'src/engine/core-modules/application/application-install/constants/application-lifecycle-lock-options.constant';import { type ApplicationLifecycleProgressReporter } from 'src/engine/core-modules/application/application-install/types/application-lifecycle-progress-reporter.type';import { buildApplicationLifecycleLockKey } from 'src/engine/core-modules/application/application-install/utils/build-application-lifecycle-lock-key.util';+import { buildApplicationLifecycleLogEntry } from 'src/engine/core-modules/application/application-install/utils/build-application-lifecycle-log-entry.util';import { createApplicationLifecycleProgressReporter } from 'src/engine/core-modules/application/application-install/utils/create-application-lifecycle-progress-reporter.util';+import { getApplicationErrorCode } from 'src/engine/core-modules/application/application-install/utils/get-application-error-code.util';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';import { LOGIC_FUNCTION_QUEUE_RETRY_BACKOFF } from 'src/engine/core-modules/logic-function/logic-function-trigger/constants/logic-function-queue-retry-backoff.constant';@@ -89,6 +92,7 @@ export class ApplicationInstallService {private readonly lambdaManagementQueueService: MessageQueueService,private readonly workspaceCacheService: WorkspaceCacheService,private readonly metricsService: MetricsService,+ private readonly eventLogEmitterService: EventLogEmitterService,) {}async installApplication(params: {@@ -180,11 +184,20 @@ export class ApplicationInstallService {);}- const resolvedPackage =- await this.applicationPackageFetcherService.resolvePackage(- appRegistration,- { targetVersion: params.version },- );+ const existingApplication =+ await this.applicationLookupService.findByUniversalIdentifier({+ universalIdentifier: appRegistration.universalIdentifier,+ workspaceId: params.workspaceId,+ });++ const isVersionUpgrade = isDefined(existingApplication?.version);++ const resolvedPackage = await this.resolvePackageOrRecordFailure({+ appRegistration,+ params,+ existingApplication,+ isVersionUpgrade,+ });if (!resolvedPackage) {return true;@@ -193,17 +206,12 @@ export class ApplicationInstallService {await progressReporter.reportStepCompleted('RESOLVE_PACKAGE');try {- const existingApplication =- await this.applicationLookupService.findByUniversalIdentifier({- universalIdentifier: appRegistration.universalIdentifier,- workspaceId: params.workspaceId,- });-return await this.runInstallWithMetrics({appRegistration,params,resolvedPackage,existingApplication,+ isVersionUpgrade,progressReporter,});} finally {@@ -213,11 +221,45 @@ export class ApplicationInstallService {}}+ private async resolvePackageOrRecordFailure({+ appRegistration,+ params,+ existingApplication,+ isVersionUpgrade,+ }: {+ appRegistration: ApplicationRegistrationEntity;+ params: { version?: string; workspaceId: string };+ existingApplication: ApplicationEntity | null;+ isVersionUpgrade: boolean;+ }): Promise<ResolvedPackage | null> {+ try {+ return await this.applicationPackageFetcherService.resolvePackage(+ appRegistration,+ { targetVersion: params.version },+ );+ } catch (error) {+ await this.eventLogEmitterService.recordApplicationLogs([+ buildApplicationLifecycleLogEntry({+ source: isVersionUpgrade ? 'UPGRADE' : 'INSTALL',+ workspaceId: params.workspaceId,+ applicationId: existingApplication?.id ?? '',+ applicationRegistrationId: appRegistration.id,+ version: params.version ?? '',+ previousVersion: existingApplication?.version ?? undefined,+ error,+ }),+ ]);++ throw error;+ }+ }+private async runInstallWithMetrics({appRegistration,params,resolvedPackage,existingApplication,+ isVersionUpgrade,progressReporter,}: {appRegistration: ApplicationRegistrationEntity;@@ -229,10 +271,9 @@ export class ApplicationInstallService {};resolvedPackage: ResolvedPackage;existingApplication: ApplicationEntity | null;+ isVersionUpgrade: boolean;progressReporter: ApplicationLifecycleProgressReporter<ApplicationInstallStep>;}): Promise<boolean> {- const isVersionUpgrade = isDefined(existingApplication);-const attributes = {universal_identifier: appRegistration.universalIdentifier,app_name: resolvedPackage.manifest.application.displayName,@@ -240,8 +281,18 @@ export class ApplicationInstallService {version: resolvedPackage.packageJson.version ?? 'unknown',};+ const previousVersion = existingApplication?.version ?? undefined;++ const lifecycleLogContext = {+ source: isVersionUpgrade ? 'UPGRADE' : 'INSTALL',+ workspaceId: params.workspaceId,+ applicationRegistrationId: appRegistration.id,+ version: resolvedPackage.packageJson.version ?? '',+ previousVersion,+ } as const;+try {- const result = await this.runInstall({+ const application = await this.runInstall({appRegistration,params,resolvedPackage,@@ -257,8 +308,23 @@ export class ApplicationInstallService {attributes,});- return result;+ await this.eventLogEmitterService.recordApplicationLogs([+ buildApplicationLifecycleLogEntry({+ ...lifecycleLogContext,+ applicationId: application.id,+ }),+ ]);++ return true;} catch (error) {+ await this.eventLogEmitterService.recordApplicationLogs([+ buildApplicationLifecycleLogEntry({+ ...lifecycleLogContext,+ applicationId: existingApplication?.id ?? '',+ error,+ }),+ ]);+this.metricsService.incrementCounterBy({key: isVersionUpgrade? MetricsKeys.AppUpgradeFailed@@ -266,8 +332,7 @@ export class ApplicationInstallService {amount: 1,attributes: {...attributes,- error_code:- error instanceof ApplicationException ? error.code : 'UNKNOWN',+ error_code: getApplicationErrorCode(error),},});@@ -292,7 +357,7 @@ export class ApplicationInstallService {resolvedPackage: ResolvedPackage;existingApplication: ApplicationEntity | null;progressReporter: ApplicationLifecycleProgressReporter<ApplicationInstallStep>;- }): Promise<boolean> {+ }): Promise<ApplicationEntity> {const universalIdentifier = appRegistration.universalIdentifier;if (params.skipWorkspaceCompatibilityCheck !== true) {@@ -508,7 +573,7 @@ export class ApplicationInstallService {`Successfully installed app ${universalIdentifier} v${resolvedPackage.packageJson.version ?? 'unknown'}`,);- return true;+ return application;} catch (error) {this.logger.error(`Failed to install app ${appRegistration.universalIdentifier}: ${error}`,diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-uninstall-runner.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-uninstall-runner.service.tsindex d897c1d88dd..39276d6dd08 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-uninstall-runner.service.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-uninstall-runner.service.ts@@ -3,15 +3,17 @@ import { Injectable } from '@nestjs/common';import { isDefined } from 'twenty-shared/utils';import { ApplicationSyncService } from 'src/engine/core-modules/application/application-manifest/application-sync.service';-import { ApplicationException } from 'src/engine/core-modules/application/application.exception';import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';import { type ApplicationEntity } from 'src/engine/core-modules/application/application.entity';import { ApplicationService } from 'src/engine/core-modules/application/application.service';import { APPLICATION_LIFECYCLE_LOCK_OPTIONS } from 'src/engine/core-modules/application/application-install/constants/application-lifecycle-lock-options.constant';import { APPLICATION_UNINSTALL_STEPS } from 'src/engine/core-modules/application/application-install/constants/application-uninstall-steps.constant';import { buildApplicationLifecycleLockKey } from 'src/engine/core-modules/application/application-install/utils/build-application-lifecycle-lock-key.util';+import { buildApplicationLifecycleLogEntry } from 'src/engine/core-modules/application/application-install/utils/build-application-lifecycle-log-entry.util';import { createApplicationLifecycleProgressReporter } from 'src/engine/core-modules/application/application-install/utils/create-application-lifecycle-progress-reporter.util';+import { getApplicationErrorCode } from 'src/engine/core-modules/application/application-install/utils/get-application-error-code.util';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';import { type MessageQueueJobProgressContext } from 'src/engine/core-modules/message-queue/interfaces/message-queue-job.interface';import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';@@ -24,6 +26,7 @@ export class ApplicationUninstallRunnerService {private readonly applicationSyncService: ApplicationSyncService,private readonly metricsService: MetricsService,private readonly cacheLockService: CacheLockService,+ private readonly eventLogEmitterService: EventLogEmitterService,) {}async uninstallApplication({@@ -71,11 +74,12 @@ export class ApplicationUninstallRunnerService {amount: 1,attributes: {...this.buildMetricsAttributes({ universalIdentifier, application }),- error_code:- error instanceof ApplicationException ? error.code : 'UNKNOWN',+ error_code: getApplicationErrorCode(error),},});+ await this.recordUninstallLog({ application, workspaceId, error });+throw error;}@@ -87,6 +91,33 @@ export class ApplicationUninstallRunnerService {application,}),});++ await this.recordUninstallLog({ application, workspaceId });+ }++ private async recordUninstallLog({+ application,+ workspaceId,+ error,+ }: {+ application: ApplicationEntity | null;+ workspaceId: string;+ error?: unknown;+ }) {+ if (!isDefined(application)) {+ return;+ }++ await this.eventLogEmitterService.recordApplicationLogs([+ buildApplicationLifecycleLogEntry({+ source: 'UNINSTALL',+ workspaceId,+ applicationId: application.id,+ applicationRegistrationId: application.applicationRegistrationId ?? '',+ version: application.version ?? '',+ error,+ }),+ ]);}private buildMetricsAttributes({diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/utils/__tests__/build-application-lifecycle-log-entry.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/__tests__/build-application-lifecycle-log-entry.util.spec.tsnew file mode 100644index 00000000000..f8ff5189f84--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/__tests__/build-application-lifecycle-log-entry.util.spec.ts@@ -0,0 +1,98 @@+import {+ ApplicationException,+ ApplicationExceptionCode,+} from 'src/engine/core-modules/application/application.exception';+import { buildApplicationLifecycleLogEntry } from 'src/engine/core-modules/application/application-install/utils/build-application-lifecycle-log-entry.util';++const CONTEXT = {+ workspaceId: 'workspace-1',+ applicationId: 'application-1',+ applicationRegistrationId: 'registration-1',+};++describe('buildApplicationLifecycleLogEntry', () => {+ it('records a successful install as an info row', () => {+ expect(+ buildApplicationLifecycleLogEntry({+ ...CONTEXT,+ source: 'INSTALL',+ version: '1.2.3',+ }),+ ).toMatchObject({+ ...CONTEXT,+ applicationVersion: '1.2.3',+ source: 'INSTALL',+ logicFunctionId: '',+ logicFunctionName: '',+ executionId: '',+ level: 'INFO',+ message: 'Installed version 1.2.3.',+ errorCode: '',+ properties: {},+ });+ });++ it('records a failed upgrade with the application exception code', () => {+ expect(+ buildApplicationLifecycleLogEntry({+ ...CONTEXT,+ source: 'UPGRADE',+ version: '1.2.3',+ previousVersion: '1.2.2',+ error: new ApplicationException(+ 'Migration failed',+ ApplicationExceptionCode.UPGRADE_FAILED,+ ),+ }),+ ).toMatchObject({+ level: 'ERROR',+ message: 'Upgrade from 1.2.2 to 1.2.3 failed: Migration failed',+ errorCode: ApplicationExceptionCode.UPGRADE_FAILED,+ properties: { previousVersion: '1.2.2' },+ });+ });++ it('omits the target version of an upgrade whose package did not resolve', () => {+ expect(+ buildApplicationLifecycleLogEntry({+ ...CONTEXT,+ source: 'UPGRADE',+ version: '',+ previousVersion: '1.2.2',+ error: new ApplicationException(+ 'Registry returned 404 for acme-sync@latest',+ ApplicationExceptionCode.PACKAGE_RESOLUTION_FAILED,+ ),+ }),+ ).toMatchObject({+ message:+ 'Upgrade from 1.2.2 failed: Registry returned 404 for acme-sync@latest',+ errorCode: ApplicationExceptionCode.PACKAGE_RESOLUTION_FAILED,+ });+ });++ it('records an unexpected uninstall error as UNKNOWN', () => {+ expect(+ buildApplicationLifecycleLogEntry({+ ...CONTEXT,+ source: 'UNINSTALL',+ version: '1.2.3',+ error: new Error('Connection lost'),+ }),+ ).toMatchObject({+ level: 'ERROR',+ message: 'Uninstall failed: Connection lost',+ errorCode: 'UNKNOWN',+ });+ });++ it('records a successful uninstall', () => {+ expect(+ buildApplicationLifecycleLogEntry({+ ...CONTEXT,+ source: 'UNINSTALL',+ version: '1.2.3',+ }),+ ).toMatchObject({ level: 'INFO', message: 'Uninstalled.' });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/utils/__tests__/get-application-error-code.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/__tests__/get-application-error-code.util.spec.tsnew file mode 100644index 00000000000..188a9542156--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/__tests__/get-application-error-code.util.spec.ts@@ -0,0 +1,22 @@+import {+ ApplicationException,+ ApplicationExceptionCode,+} from 'src/engine/core-modules/application/application.exception';+import { getApplicationErrorCode } from 'src/engine/core-modules/application/application-install/utils/get-application-error-code.util';++describe('getApplicationErrorCode', () => {+ it('returns the code of an application exception', () => {+ expect(+ getApplicationErrorCode(+ new ApplicationException(+ 'Package not found',+ ApplicationExceptionCode.PACKAGE_RESOLUTION_FAILED,+ ),+ ),+ ).toBe(ApplicationExceptionCode.PACKAGE_RESOLUTION_FAILED);+ });++ it('returns UNKNOWN for any other error', () => {+ expect(getApplicationErrorCode(new Error('boom'))).toBe('UNKNOWN');+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/utils/build-application-lifecycle-log-entry.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/build-application-lifecycle-log-entry.util.tsnew file mode 100644index 00000000000..e5cf5f15f79--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/build-application-lifecycle-log-entry.util.ts@@ -0,0 +1,86 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type ApplicationLogSource } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { getApplicationErrorCode } from 'src/engine/core-modules/application/application-install/utils/get-application-error-code.util';+import { type ApplicationLogEntry } from 'src/engine/core-modules/event-logs/producers/application-log/application-log-entry.interface';++type ApplicationLifecycleLogSource = Extract<+ ApplicationLogSource,+ 'INSTALL' | 'UPGRADE' | 'UNINSTALL'+>;++const getErrorMessage = (error: unknown): string =>+ error instanceof Error ? error.message : String(error);++const buildMessage = ({+ source,+ version,+ previousVersion,+ errorMessage,+}: {+ source: ApplicationLifecycleLogSource;+ version: string;+ previousVersion?: string;+ errorMessage?: string;+}): string => {+ switch (source) {+ case 'INSTALL':+ return isDefined(errorMessage)+ ? `Install failed: ${errorMessage}`+ : `Installed version ${version}.`;+ case 'UPGRADE':+ if (!isDefined(errorMessage)) {+ return `Upgraded from ${previousVersion} to ${version}.`;+ }++ return isNonEmptyString(version)+ ? `Upgrade from ${previousVersion} to ${version} failed: ${errorMessage}`+ : `Upgrade from ${previousVersion} failed: ${errorMessage}`;+ case 'UNINSTALL':+ return isDefined(errorMessage)+ ? `Uninstall failed: ${errorMessage}`+ : 'Uninstalled.';+ }+};++export const buildApplicationLifecycleLogEntry = ({+ source,+ workspaceId,+ applicationId,+ applicationRegistrationId,+ version,+ previousVersion,+ error,+}: {+ source: ApplicationLifecycleLogSource;+ workspaceId: string;+ applicationId: string;+ applicationRegistrationId: string;+ version: string;+ previousVersion?: string;+ error?: unknown;+}): ApplicationLogEntry => {+ const hasFailed = isDefined(error);++ return {+ timestamp: new Date(),+ workspaceId,+ applicationId,+ applicationRegistrationId,+ applicationVersion: version,+ source,+ logicFunctionId: '',+ logicFunctionName: '',+ executionId: '',+ level: hasFailed ? 'ERROR' : 'INFO',+ message: buildMessage({+ source,+ version,+ previousVersion,+ errorMessage: hasFailed ? getErrorMessage(error) : undefined,+ }),+ errorCode: hasFailed ? getApplicationErrorCode(error) : '',+ properties: isDefined(previousVersion) ? { previousVersion } : {},+ };+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/utils/get-application-error-code.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/get-application-error-code.util.tsnew file mode 100644index 00000000000..f34e9afab11--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/utils/get-application-error-code.util.ts@@ -0,0 +1,4 @@+import { ApplicationException } from 'src/engine/core-modules/application/application.exception';++export const getApplicationErrorCode = (error: unknown): string =>+ error instanceof ApplicationException ? error.code : 'UNKNOWN';diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/emit/event-log-emitter.service.ts b/packages/twenty-server/src/engine/core-modules/event-logs/emit/event-log-emitter.service.tsindex 43d42cc6e52..7b2f5d74bed 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/emit/event-log-emitter.service.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/emit/event-log-emitter.service.ts@@ -12,6 +12,8 @@ import {type TrackEventProperties,} from 'src/engine/core-modules/event-logs/emit/events.type';import { WorkspaceEventSinkService } from 'src/engine/core-modules/event-logs/ingest/workspace-event-sink.service';+import { type ApplicationLogEntry } from 'src/engine/core-modules/event-logs/producers/application-log/application-log-entry.interface';+import { buildApplicationLogEnvelopes } from 'src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes';import {type EventContextFields,type WorkspaceEventEnvelope,@@ -37,6 +39,14 @@ export class EventLogEmitterService {await this.workspaceEventSinkService.ingest(events);}+ async recordApplicationLogs(entries: ApplicationLogEntry[]): Promise<void> {+ try {+ await this.dispatch(buildApplicationLogEnvelopes(entries));+ } catch (error) {+ this.logger.error('Failed to record application logs', error);+ }+ }+createContext(context?: EventContextFields) {const contextFields = computeEventContextFields(context);diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/ingest/clickhouse-event.sink.spec.ts b/packages/twenty-server/src/engine/core-modules/event-logs/ingest/clickhouse-event.sink.spec.tsindex f9fef9805e0..913871991a9 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/ingest/clickhouse-event.sink.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/ingest/clickhouse-event.sink.spec.ts@@ -13,11 +13,16 @@ const applicationLog: WorkspaceEventEnvelope = {timestamp: 't',workspaceId: 'w',applicationId: '',+ applicationRegistrationId: '',+ applicationVersion: '',+ source: 'LOGIC_FUNCTION',logicFunctionId: '',logicFunctionName: 'fn',executionId: 'e',level: 'INFO',message: 'm',+ errorCode: '',+ properties: {},},};diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/ingest/console-event.sink.ts b/packages/twenty-server/src/engine/core-modules/event-logs/ingest/console-event.sink.tsindex 4618bc4ff9b..9b3e595bab6 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/ingest/console-event.sink.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/ingest/console-event.sink.ts@@ -1,5 +1,7 @@import { Injectable, Logger } from '@nestjs/common';+import { isNonEmptyString } from '@sniptt/guards';+import { type EventSink } from 'src/engine/core-modules/event-logs/ingest/event-sink';import { type WorkspaceEventEnvelope } from 'src/engine/core-modules/event-logs/types/workspace-event-envelope.type';@@ -10,7 +12,9 @@ export class ConsoleEventSink implements EventSink {async write(events: WorkspaceEventEnvelope[]): Promise<void> {for (const event of events) {if (event.table === 'applicationLog') {- const context = `${event.row.logicFunctionName}:${event.row.executionId}`;+ const context = isNonEmptyString(event.row.logicFunctionName)+ ? `${event.row.logicFunctionName}:${event.row.executionId}`+ : event.row.source;switch (event.row.level) {case 'ERROR':diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/application-log-entry.interface.ts b/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/application-log-entry.interface.tsindex 7fc52e92f8e..0ac3584409c 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/application-log-entry.interface.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/application-log-entry.interface.ts@@ -1,10 +1,17 @@+import { type ApplicationLogSource } from 'twenty-shared/types';+export type ApplicationLogEntry = {timestamp: Date;workspaceId: string;applicationId: string;+ applicationRegistrationId: string;+ applicationVersion: string;+ source: ApplicationLogSource;logicFunctionId: string;logicFunctionName: string;executionId: string;level: string;message: string;+ errorCode?: string;+ properties?: Record<string, unknown>;};diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes.spec.ts b/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes.spec.tsnew file mode 100644index 00000000000..331d7f48bbe--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes.spec.ts@@ -0,0 +1,56 @@+import { buildApplicationLogEnvelopes } from 'src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes';++const ENTRY = {+ timestamp: new Date('2026-10-19T08:41:12.204Z'),+ workspaceId: 'workspace-1',+ applicationId: 'application-1',+ applicationRegistrationId: 'registration-1',+ applicationVersion: '1.2.3',+ source: 'LOGIC_FUNCTION' as const,+ logicFunctionId: 'function-1',+ logicFunctionName: 'syncContacts',+ executionId: 'execution-1',+ level: 'INFO',+ message: 'Synced 214 contacts.',+};++describe('buildApplicationLogEnvelopes', () => {+ it('maps an entry to an applicationLog row with empty error code and properties', () => {+ expect(buildApplicationLogEnvelopes([ENTRY])).toEqual([+ {+ table: 'applicationLog',+ row: {+ timestamp: '2026-10-19 08:41:12.204',+ workspaceId: 'workspace-1',+ applicationId: 'application-1',+ applicationRegistrationId: 'registration-1',+ applicationVersion: '1.2.3',+ source: 'LOGIC_FUNCTION',+ logicFunctionId: 'function-1',+ logicFunctionName: 'syncContacts',+ executionId: 'execution-1',+ level: 'INFO',+ message: 'Synced 214 contacts.',+ errorCode: '',+ properties: {},+ },+ },+ ]);+ });++ it('keeps the error code and properties of an entry', () => {+ const [envelope] = buildApplicationLogEnvelopes([+ {+ ...ENTRY,+ level: 'ERROR',+ errorCode: 'TypeError',+ properties: { stackTrace: ['TypeError: boom'] },+ },+ ]);++ expect(envelope.row).toMatchObject({+ errorCode: 'TypeError',+ properties: { stackTrace: ['TypeError: boom'] },+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes.ts b/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes.tsindex f1024aa4dbd..9ef2fae5662 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes.ts@@ -11,10 +11,15 @@ export const buildApplicationLogEnvelopes = (timestamp: formatDateTimeForClickHouse(entry.timestamp),workspaceId: entry.workspaceId,applicationId: entry.applicationId,+ applicationRegistrationId: entry.applicationRegistrationId,+ applicationVersion: entry.applicationVersion,+ source: entry.source,logicFunctionId: entry.logicFunctionId,logicFunctionName: entry.logicFunctionName,executionId: entry.executionId,level: entry.level,message: entry.message,+ errorCode: entry.errorCode ?? '',+ properties: entry.properties ?? {},},}));diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.spec.ts b/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.spec.tsindex ab500e66e47..c2992334f0b 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.spec.ts@@ -100,5 +100,27 @@ describe('event-log registry', () => {message: 'hello',});});++ it('folds the monitoring columns and stored properties of an application log row', () => {+ const record = EVENT_LOG_TYPES[EventLogTable.APPLICATION_LOG].normalize({+ logicFunctionName: 'myFn',+ timestamp,+ level: 'ERROR',+ message: 'TypeError: boom',+ applicationRegistrationId: 'registration-1',+ applicationVersion: '1.2.3',+ source: 'LOGIC_FUNCTION',+ errorCode: 'TypeError',+ properties: { stackTrace: ['TypeError: boom'] },+ });++ expect(record.properties).toMatchObject({+ applicationRegistrationId: 'registration-1',+ applicationVersion: '1.2.3',+ source: 'LOGIC_FUNCTION',+ errorCode: 'TypeError',+ stackTrace: ['TypeError: boom'],+ });+ });});});diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.ts b/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.tsindex 52cba372390..832db8888a8 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/registry/event-log-registry.ts@@ -105,11 +105,16 @@ export const EVENT_LOG_TYPES: Record<EventLogTable, EventLogTypeDefinition> = {return {event: record.logicFunctionName ?? '',properties: {+ ...record.properties,level: record.level,message: record.message,executionId: record.executionId,logicFunctionId: record.logicFunctionId,applicationId: record.applicationId,+ applicationRegistrationId: record.applicationRegistrationId,+ applicationVersion: record.applicationVersion,+ source: record.source,+ errorCode: record.errorCode,},};},diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/types/workspace-event-envelope.type.ts b/packages/twenty-server/src/engine/core-modules/event-logs/types/workspace-event-envelope.type.tsindex bf8e334cbc1..39461953d1f 100644--- a/packages/twenty-server/src/engine/core-modules/event-logs/types/workspace-event-envelope.type.ts+++ b/packages/twenty-server/src/engine/core-modules/event-logs/types/workspace-event-envelope.type.ts@@ -1,3 +1,5 @@+import { type ApplicationLogSource } from 'twenty-shared/types';+export type EventContextFields = {workspaceId?: string | null;userId?: string | null;@@ -44,11 +46,16 @@ export type ApplicationLogRow = {timestamp: string;workspaceId: string;applicationId: string;+ applicationRegistrationId: string;+ applicationVersion: string;+ source: ApplicationLogSource;logicFunctionId: string;logicFunctionName: string;executionId: string;level: string;message: string;+ errorCode: string;+ properties: Record<string, unknown>;};// The `table` literals must match the registry's clickHouseTable values (EVENT_LOG_TYPES).diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.tsindex b66cdfbe657..df3500f40b3 100644--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts@@ -37,9 +37,9 @@ import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspacimport { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';import { LOGIC_FUNCTION_EXECUTED_EVENT } from 'src/engine/core-modules/event-logs/emit/events/workspace-event/logic-function/logic-function-executed';import { EventLogLiveService } from 'src/engine/core-modules/event-logs/live/event-log-live.service';-import { buildApplicationLogEnvelopes } from 'src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes';import { parseApplicationLogLines } from 'src/engine/core-modules/event-logs/producers/application-log/parse-application-log-lines';import { LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';+import { buildLogicFunctionErrorLogLine } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-error-log-line.util';import { buildLogicFunctionExecutionUsage } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util';import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';@@ -577,23 +577,27 @@ export class LogicFunctionExecutorService {}) {const executionId = v4();- const parsedLines = parseApplicationLogLines(result.logs);- const logEntries = parsedLines.map((line) => ({- ...line,- workspaceId,- applicationId: flatApplication.id,- logicFunctionId: flatLogicFunction.id,- logicFunctionName: flatLogicFunction.name,- executionId,- }));-- if (this.eventLogEmitterService.isEnabled()) {- void this.eventLogEmitterService- .dispatch(buildApplicationLogEnvelopes(logEntries))- .catch((error) => {- this.logger.error('Failed to record application logs', error);- });- }+ const logLines = [+ ...parseApplicationLogLines(result.logs),+ ...(isDefined(result.error)+ ? [buildLogicFunctionErrorLogLine(result.error)]+ : []),+ ];++ await this.eventLogEmitterService.recordApplicationLogs(+ logLines.map((line) => ({+ ...line,+ workspaceId,+ applicationId: flatApplication.id,+ applicationRegistrationId:+ flatApplication.applicationRegistrationId ?? '',+ applicationVersion: flatApplication.version ?? '',+ source: 'LOGIC_FUNCTION',+ logicFunctionId: flatLogicFunction.id,+ logicFunctionName: flatLogicFunction.name,+ executionId,+ })),+ );void this.publishLogicFunctionLogsToCli({result,diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-error-log-line.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-error-log-line.util.spec.tsnew file mode 100644index 00000000000..cdc1f0d343f--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-error-log-line.util.spec.ts@@ -0,0 +1,51 @@+import { type LogicFunctionExecuteError } from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';+import { buildLogicFunctionErrorLogLine } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-error-log-line.util';++describe('buildLogicFunctionErrorLogLine', () => {+ it('builds an error line carrying the error type as error code', () => {+ const line = buildLogicFunctionErrorLogLine({+ errorType: 'TypeError',+ errorMessage: "Cannot read properties of undefined (reading 'phone')",+ stackTrace: ['TypeError: boom', ' at handler (index.js:3:9)'],+ });++ expect(line).toMatchObject({+ level: 'ERROR',+ message:+ "TypeError: Cannot read properties of undefined (reading 'phone')",+ errorCode: 'TypeError',+ properties: {+ stackTrace: ['TypeError: boom', ' at handler (index.js:3:9)'],+ },+ });+ expect(line.timestamp).toBeInstanceOf(Date);+ });++ it('splits a string stack trace into lines', () => {+ const line = buildLogicFunctionErrorLogLine({+ errorType: 'Error',+ errorMessage: 'boom',+ stackTrace: 'Error: boom\n at handler (index.js:1:1)',+ });++ expect(line.properties).toEqual({+ stackTrace: ['Error: boom', ' at handler (index.js:1:1)'],+ });+ });++ it('keeps an empty stack trace when the runtime error has none', () => {+ const lambdaRuntimeError: Omit<LogicFunctionExecuteError, 'stackTrace'> = {+ errorType: 'Runtime.ExitError',+ errorMessage: 'RequestId: 1 Error: Runtime exited with error',+ };++ const line = buildLogicFunctionErrorLogLine(+ lambdaRuntimeError as LogicFunctionExecuteError,+ );++ expect(line).toMatchObject({+ errorCode: 'Runtime.ExitError',+ properties: { stackTrace: [] },+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-error-log-line.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-error-log-line.util.tsnew file mode 100644index 00000000000..816fc8e483d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-error-log-line.util.ts@@ -0,0 +1,27 @@+import { isNonEmptyString } from '@sniptt/guards';++import { type ApplicationLogEntry } from 'src/engine/core-modules/event-logs/producers/application-log/application-log-entry.interface';+import { type ParsedLogLine } from 'src/engine/core-modules/event-logs/producers/application-log/parsed-log-line.type';+import { type LogicFunctionExecuteError } from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';++const getStackTraceLines = (+ stackTrace: LogicFunctionExecuteError['stackTrace'] | undefined,+): string[] => {+ if (Array.isArray(stackTrace)) {+ return stackTrace;+ }++ return isNonEmptyString(stackTrace) ? stackTrace.split('\n') : [];+};++export const buildLogicFunctionErrorLogLine = (+ error: LogicFunctionExecuteError,+): ParsedLogLine & Pick<ApplicationLogEntry, 'errorCode' | 'properties'> => ({+ timestamp: new Date(),+ level: 'ERROR',+ message: `${error.errorType}: ${error.errorMessage}`,+ errorCode: error.errorType,+ properties: {+ stackTrace: getStackTraceLines(error.stackTrace),+ },+});diff --git a/packages/twenty-server/test/integration/graphql/suites/event-logs/event-logs.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/event-logs/event-logs.integration-spec.tsindex 37e548c0747..4821cf4661e 100644--- a/packages/twenty-server/test/integration/graphql/suites/event-logs/event-logs.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/event-logs/event-logs.integration-spec.ts@@ -102,11 +102,14 @@ describe('Event Logs (integration)', () => {const applicationLogRecords = Array.from({ length: 8 }, (_, i) => ({workspaceId: testWorkspaceId,applicationId: 'app-1',+ applicationRegistrationId: 'registration-1',+ applicationVersion: '1.2.3',logicFunctionId: 'fn-1',logicFunctionName: i % 2 === 0 ? 'sendEmail' : 'syncContacts',executionId: `exec-${i}`,level: i % 2 === 0 ? 'INFO' : 'ERROR',message: `log line ${i}`,+ errorCode: i % 2 === 0 ? '' : 'TypeError',timestamp: formatDateTimeForClickHouse(new Date(now.getTime() - i * 60000),),@@ -284,6 +287,28 @@ describe('Event Logs (integration)', () => {expect(record.properties.message).toBeDefined();expect(record.properties.executionId).toBeDefined();});++ it('should expose the registration, version, source and error code of application logs', async () => {+ const response = await makeEventLogsQuery({+ table: 'APPLICATION_LOG',+ first: 10,+ });++ expect(response.status).toBe(200);+ expect(response.body.errors).toBeUndefined();++ const errorRecord = response.body.data.eventLogs.records.find(+ (record: { properties: { level: string } }) =>+ record.properties.level === 'ERROR',+ );++ expect(errorRecord.properties).toMatchObject({+ applicationRegistrationId: 'registration-1',+ applicationVersion: '1.2.3',+ source: 'LOGIC_FUNCTION',+ errorCode: 'TypeError',+ });+ });});describe('pagination', () => {diff --git a/packages/twenty-shared/src/types/ApplicationLogSource.ts b/packages/twenty-shared/src/types/ApplicationLogSource.tsnew file mode 100644index 00000000000..8a42293952f--- /dev/null+++ b/packages/twenty-shared/src/types/ApplicationLogSource.ts@@ -0,0 +1,5 @@+export type ApplicationLogSource =+ | 'LOGIC_FUNCTION'+ | 'INSTALL'+ | 'UPGRADE'+ | 'UNINSTALL';diff --git a/packages/twenty-shared/src/types/index.ts b/packages/twenty-shared/src/types/index.tsindex 66947161d5d..21b642b82e9 100644--- a/packages/twenty-shared/src/types/index.ts+++ b/packages/twenty-shared/src/types/index.ts@@ -13,6 +13,7 @@ export { AggregateOperations } from './AggregateOperations';export type { AllowedFullNameSortSubField } from './AllowedFullNameSortSubField';export { ApiPath } from './ApiPath';export { AppBasePath } from './AppBasePath';+export type { ApplicationLogSource } from './ApplicationLogSource';export { AppPath } from './AppPath';export type { Arrayable } from './Arrayable';export type { ArraySortDirection } from './ArraySortDirection';