:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): add pagerduty to the logs alert notification picker (#112243)
Jimmy Zhu740355f3f04c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 06d01390b8cd..5315ea3499ab 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6302,6 +6302,10 @@ snapshots:hash: v1.k794b7964.3c027b2e0731f9738cdfe21d14b6a893375c0fe0a0f11b587580adafc09340f9.GfzW8vynGlDg1ZO7Mp1sS9oDhRiKra5Vxhtopyi31Goproducts-alerts-shared-components--notifications-multiple-slack-workspaces--light:hash: v1.k794b7964.63ec31eddf76c6f6544838a9b765e091bbe84325070fff837ed94d2cc1e85ba8.rPHnjzF-XA_HZd7mJ9KKN8iLGsZVXVdne4uww2vsx4w+ products-alerts-shared-components--notifications-pager-duty--dark:+ hash: v1.k794b7964.c3a3b73806e040d29cf7bfce8d565543a0e7e4b47a56556414e047f2511da17b.SGZtwKir5o45QYI1dRjvgbzHGHTrnWqW6mmktzjN3jk+ products-alerts-shared-components--notifications-pager-duty--light:+ hash: v1.k794b7964.211c55b2e573ce2620f4ff11dfe2692c56f6a7ae320af57557bd302430b40d87.KtzQY8KdtOwLt-LOiH6XneFrqpaKvdGg8Wa3oAElMSQproducts-alerts-shared-components--preview--dark:hash: v1.k794b7964.c9bdafae1ad47e45cba8bc136bc1f911fcd38d3f3adc0109c73c608fc7aff1a7.JQQcVBlkdE7zlG0B9V18hFYCe7DRINlSu1YhOXTSNFgproducts-alerts-shared-components--preview--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c15028303421..11385a6b1238 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -759,6 +759,8 @@ export const LOGS_ALERT_FIRING_EVENT_ID = '$logs_alert_firing'export const LOGS_ALERT_RESOLVED_EVENT_ID = '$logs_alert_resolved'export const LOGS_ALERT_AUTO_DISABLED_EVENT_ID = '$logs_alert_auto_disabled'export const LOGS_ALERT_ERRORED_EVENT_ID = '$logs_alert_errored'+export const LOGS_ALERT_INCIDENT_OPENED_EVENT_ID = '$logs_alert_incident_opened'+export const LOGS_ALERT_INCIDENT_CLOSED_EVENT_ID = '$logs_alert_incident_closed'export const COHORT_PERSONS_QUERY_LIMIT = 10000diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsxindex 1cdaed504e06..732b7d4ccc9a 100644--- a/products/alerts/frontend/components/AlertComponents.stories.tsx+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx@@ -30,6 +30,8 @@ import {import {AlertNotificationDestinationEditor,AlertNotificationDestinationView,+ AlertPagerDutyRegion,+ AlertPagerDutySeverity,PendingAlertNotificationDestinationView,} from './AlertNotificationDestinationEditor'import { AlertPreviewCard } from './AlertPreviewCard'@@ -146,17 +148,21 @@ function AdvancedOptionsStory(): JSX.Element {)}-type StoryNotificationType = 'slack' | 'webhook'+type StoryNotificationType = 'slack' | 'webhook' | 'pagerduty'const NOTIFICATION_TYPE_OPTIONS: LemonSelectOptions<StoryNotificationType> = [{ label: 'Slack', value: 'slack' },+ { label: 'PagerDuty', value: 'pagerduty' },{ label: 'Webhook', value: 'webhook' },]-function NotificationsStory(): JSX.Element {- const [selectedType, setSelectedType] = useState<StoryNotificationType>('webhook')+function NotificationsStory({ initialType = 'webhook' }: { initialType?: StoryNotificationType }): JSX.Element {+ const [selectedType, setSelectedType] = useState<StoryNotificationType>(initialType)const [urlValue, setUrlValue] = useState('https://example.com/alerts')const [slackChannelValue, setSlackChannelValue] = useState<string | null>(null)+ const [routingKey, setRoutingKey] = useState('')+ const [severity, setSeverity] = useState<AlertPagerDutySeverity>('critical')+ const [region, setRegion] = useState<AlertPagerDutyRegion>('us')const [existingDestinations, setExistingDestinations] = useState<AlertNotificationDestinationView[]>([{key: 'existing-slack',@@ -197,6 +203,8 @@ function NotificationsStory(): JSX.Element {let addDisabledReason: string | undefinedif (selectedType === 'slack') {addDisabledReason = 'Connect Slack first'+ } else if (selectedType === 'pagerduty') {+ addDisabledReason = routingKey ? undefined : 'Enter the PagerDuty integration key'} else if (!urlValue) {addDisabledReason = 'Enter a webhook URL'}@@ -234,6 +242,18 @@ function NotificationsStory(): JSX.Element {}: undefined}+ pagerduty={+ selectedType === 'pagerduty'+ ? {+ routingKey,+ onRoutingKeyChange: setRoutingKey,+ severity,+ onSeverityChange: setSeverity,+ region,+ onRegionChange: setRegion,+ }+ : undefined+ }add={{ onClick: addDestination, disabledReason: addDisabledReason }}/></div>@@ -509,6 +529,7 @@ export const EditorLoading: Story = {export const Definition: Story = { render: () => <DefinitionStory /> }export const AdvancedOptions: Story = { render: () => <AdvancedOptionsStory /> }export const Notifications: Story = { render: () => <NotificationsStory /> }+export const NotificationsPagerDuty: Story = { render: () => <NotificationsStory initialType="pagerduty" /> }export const NotificationsMultipleSlackWorkspaces: Story = { render: () => <MultipleSlackWorkspacesStory /> }export const QuietHours: Story = { render: () => <QuietHoursStory /> }export const EvaluationHistory: Story = { render: () => <EvaluationHistoryStory /> }diff --git a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsxindex 6aaae6d82dbb..d658b0210828 100644--- a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx+++ b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx@@ -1,4 +1,4 @@-import { ReactNode } from 'react'+import { KeyboardEvent, ReactNode } from 'react'import { IconExternal, IconTrash } from '@posthog/icons'import {@@ -6,6 +6,7 @@ import {LemonBanner,LemonInput,LemonSelect,+ LemonSelectOptionLeaf,LemonSelectOptions,LemonSkeleton,LemonTag,@@ -55,6 +56,30 @@ export interface AlertNotificationUrlInput {helpText?: ReactNode}+export type AlertPagerDutySeverity = 'critical' | 'error' | 'warning' | 'info'+export type AlertPagerDutyRegion = 'us' | 'eu'++export const ALERT_PAGERDUTY_SEVERITY_OPTIONS: LemonSelectOptionLeaf<AlertPagerDutySeverity>[] = [+ { value: 'critical', label: 'Critical' },+ { value: 'error', label: 'Error' },+ { value: 'warning', label: 'Warning' },+ { value: 'info', label: 'Info' },+]++export const ALERT_PAGERDUTY_REGION_OPTIONS: LemonSelectOptionLeaf<AlertPagerDutyRegion>[] = [+ { value: 'us', label: 'US' },+ { value: 'eu', label: 'EU' },+]++export interface AlertNotificationPagerDutyInput {+ routingKey: string+ onRoutingKeyChange: (value: string) => void+ severity: AlertPagerDutySeverity+ onSeverityChange: (value: AlertPagerDutySeverity) => void+ region: AlertPagerDutyRegion+ onRegionChange: (value: AlertPagerDutyRegion) => void+}+interface AlertNotificationDestinationEditorProps<NotificationType extends string> {description?: ReactNodedestinations: {@@ -86,6 +111,7 @@ interface AlertNotificationDestinationEditorProps<NotificationType extends strinvalue: stringonChange: (value: string) => void}+ pagerduty?: AlertNotificationPagerDutyInputadd: {onClick: () => voiddisabledReason?: string@@ -227,6 +253,7 @@ export function AlertNotificationDestinationEditor<NotificationType extends strinotificationType,slack,url,+ pagerduty,add,}: AlertNotificationDestinationEditorProps<NotificationType>): JSX.Element {const addDestinationButton = (@@ -240,7 +267,19 @@ export function AlertNotificationDestinationEditor<NotificationType extends striAdd</LemonButton>)- const addDestinationButtonIsInline = notificationType.value === slack.notificationType || Boolean(url)+ const addDestinationButtonIsInline =+ notificationType.value === slack.notificationType || Boolean(url) || Boolean(pagerduty)+ const addOnEnter = (event: KeyboardEvent<HTMLInputElement>): void => {+ if (event.nativeEvent.isComposing) {+ event.stopPropagation()+ return+ }+ event.preventDefault()+ event.stopPropagation()+ if (!add.disabledReason) {+ add.onClick()+ }+ }let slackDestinationInput: JSX.Element | null = nullif (notificationType.value === slack.notificationType) {@@ -336,17 +375,7 @@ export function AlertNotificationDestinationEditor<NotificationType extends striplaceholder={url.input.placeholder}value={url.value}onChange={url.onChange}- onPressEnter={(event) => {- if (event.nativeEvent.isComposing) {- event.stopPropagation()- return- }- event.preventDefault()- event.stopPropagation()- if (!add.disabledReason) {- add.onClick()- }- }}+ onPressEnter={addOnEnter}fullWidth/>{addDestinationButton}@@ -355,6 +384,56 @@ export function AlertNotificationDestinationEditor<NotificationType extends stri</div>) : null}+ {pagerduty ? (+ <div className="space-y-3">+ <fieldset className="space-y-1">+ <legend className="text-sm font-medium">Integration key</legend>+ <div className="flex flex-col sm:flex-row items-start gap-2">+ {/* Autocapture records copied text, which the password type does not stop. */}+ <LemonInput+ type="password"+ autoComplete="off"+ className="ph-no-capture"+ placeholder="32-character Events API v2 integration key"+ value={pagerduty.routingKey}+ onChange={pagerduty.onRoutingKeyChange}+ onPressEnter={addOnEnter}+ fullWidth+ data-attr="alert-pagerduty-routing-key"+ />+ {addDestinationButton}+ </div>+ <p className="text-xs text-muted-alt m-0">+ In PagerDuty, add an "Events API v2" integration to the service you want to page and+ paste its integration key here. An incident opens when the alert starts firing and+ resolves when it stops.+ </p>+ </fieldset>+ <div className="flex flex-col sm:flex-row gap-3">+ <fieldset className="space-y-1 flex-1 min-w-0">+ <legend className="text-sm font-medium">Severity</legend>+ <LemonSelect+ fullWidth+ options={ALERT_PAGERDUTY_SEVERITY_OPTIONS}+ value={pagerduty.severity}+ onChange={pagerduty.onSeverityChange}+ data-attr="alert-pagerduty-severity"+ />+ </fieldset>+ <fieldset className="space-y-1 flex-1 min-w-0">+ <legend className="text-sm font-medium">Service region</legend>+ <LemonSelect+ fullWidth+ options={ALERT_PAGERDUTY_REGION_OPTIONS}+ value={pagerduty.region}+ onChange={pagerduty.onRegionChange}+ data-attr="alert-pagerduty-region"+ />+ </fieldset>+ </div>+ </div>+ ) : null}+{!addDestinationButtonIsInline ? addDestinationButton : null}</div></div>diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsxindex 284dd4c32f5a..43d7dee0af9b 100644--- a/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx@@ -5,6 +5,8 @@ import { slackIntegrationLogic } from 'lib/integrations/slackIntegrationLogic'import { urls } from 'scenes/urls'import {+ ALERT_PAGERDUTY_REGION_OPTIONS,+ ALERT_PAGERDUTY_SEVERITY_OPTIONS,AlertNotificationDestinationEditor,AlertNotificationDestinationView,PendingAlertNotificationDestinationView,@@ -13,6 +15,8 @@ import {import { LOGS_ALERT_NOTIFICATION_TYPE_OPTIONS, logsAlertNotificationLogic } from './logsAlertNotificationLogic'import {getHogFunctionEventKind,+ logsAlertEventKindsFor,+ LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY,LOGS_ALERT_NOTIFICATION_TYPE_SLACK,LOGS_ALERT_NOTIFICATION_TYPE_TEAMS,PendingLogsAlertNotification,@@ -28,6 +32,14 @@ function getPendingNotificationDestination(if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_TEAMS) {return { title: 'Microsoft Teams', detail: notification.webhookUrl }}+ if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY) {+ const severity = ALERT_PAGERDUTY_SEVERITY_OPTIONS.find((option) => option.value === notification.severity)+ const region = ALERT_PAGERDUTY_REGION_OPTIONS.find((option) => option.value === notification.region)+ return {+ title: 'PagerDuty',+ detail: `••••${notification.routingKey.slice(-4)} · ${severity?.label ?? notification.severity} · ${region?.label ?? notification.region}`,+ }+ }return { title: 'Webhook', detail: notification.webhookUrl }}@@ -44,6 +56,9 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.EslackChannelValue,webhookUrl,urlInput,+ pagerDutyRoutingKey,+ pagerDutySeverity,+ pagerDutyRegion,addDisabledReason,} = useValues(logsAlertNotificationLogic)const {@@ -53,6 +68,9 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.EsetSelectedType,setSlackChannelValue,setWebhookUrl,+ setPagerDutyRoutingKey,+ setPagerDutySeverity,+ setPagerDutyRegion,loadIntegrations,} = useActions(logsAlertNotificationLogic)@@ -68,8 +86,9 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.Econst existingDestinations: AlertNotificationDestinationView[] = destinationGroups.map((group) => {const detailHogFunctionId =- group.hogFunctions.find((hogFunction) => getHogFunctionEventKind(hogFunction) === 'firing')?.id ??- group.hogFunctions[0]?.id+ group.hogFunctions.find(+ (hogFunction) => getHogFunctionEventKind(hogFunction) === logsAlertEventKindsFor(group.type)[0]+ )?.id ?? group.hogFunctions[0]?.idconst detailUrl =alertId && detailHogFunctionId ? urls.logsAlertNotificationDetail(alertId, detailHogFunctionId) : undefined@@ -98,7 +117,7 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.Ereturn (<AlertNotificationDestinationEditor- description="Each destination delivers notifications for all alert events: firing, resolved, and broken."+ description="Each destination gets a notification when the alert fires, resolves, or breaks. PagerDuty gets an incident that opens when the alert fires and resolves when it resolves."destinations={{showExisting: true,existingLoading: existingHogFunctionsLoading,@@ -121,6 +140,18 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.EonChannelValueChange: setSlackChannelValue,}}url={urlInput ? { input: urlInput, value: webhookUrl, onChange: setWebhookUrl } : undefined}+ pagerduty={+ selectedType === LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY+ ? {+ routingKey: pagerDutyRoutingKey,+ onRoutingKeyChange: setPagerDutyRoutingKey,+ severity: pagerDutySeverity,+ onSeverityChange: setPagerDutySeverity,+ region: pagerDutyRegion,+ onRegionChange: setPagerDutyRegion,+ }+ : undefined+ }add={{ onClick: addSelectedNotification, disabledReason: addDisabledReason }}/>)diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertNotificationLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertNotificationLogic.test.tsindex 45cf54a8ca38..deb76f99ff62 100644--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertNotificationLogic.test.ts+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertNotificationLogic.test.ts@@ -75,6 +75,35 @@ describe('logsAlertNotificationLogic', () => {logic.unmount()})+ it('adds a pagerduty notification only once the integration key looks valid', () => {+ const logic = logsAlertNotificationLogic({ alertId: undefined })+ logic.mount()++ logic.actions.setSelectedType('pagerduty')+ logic.actions.setPagerDutySeverity('warning')+ logic.actions.setPagerDutyRoutingKey('not-a-key')+ expect(logic.values.addDisabledReason).toEqual('The integration key is 32 letters and digits')++ logic.actions.addSelectedNotification()+ expect(logic.values.pendingNotifications).toHaveLength(0)++ logic.actions.setPagerDutyRoutingKey(' 0123456789abcdef0123456789abcdef ')+ expect(logic.values.addDisabledReason).toBeUndefined()++ logic.actions.addSelectedNotification()+ expect(logic.values.pendingNotifications).toEqual([+ {+ type: 'pagerduty',+ routingKey: '0123456789abcdef0123456789abcdef',+ severity: 'warning',+ region: 'us',+ },+ ])+ expect(logic.values.pagerDutyRoutingKey).toEqual('')++ logic.unmount()+ })+it('removes a pending notification by index', () => {const logic = logsAlertNotificationLogic({ alertId: undefined })logic.mount()@@ -175,12 +204,18 @@ describe('logsAlertNotificationLogic', () => {slackChannelId: 'C456',slackChannelName: 'alerts',})+ logic.actions.addPendingNotification({+ type: 'pagerduty',+ routingKey: '0123456789abcdef0123456789abcdef',+ severity: 'error',+ region: 'eu',+ })await expectLogic(logic, () => {logic.actions.createPendingHogFunctions('alert-1')}).toFinishAllListeners()- expect(mockCreate).toHaveBeenCalledTimes(2)+ expect(mockCreate).toHaveBeenCalledTimes(3)expect(mockCreate).toHaveBeenCalledWith(expect.any(String), 'alert-1', {type: 'webhook',webhook_url: 'https://a.com',@@ -191,7 +226,13 @@ describe('logsAlertNotificationLogic', () => {slack_channel_id: 'C456',slack_channel_name: 'alerts',})- expect(lemonToast.success).toHaveBeenCalledWith('2 notification destination(s) created.')+ expect(mockCreate).toHaveBeenCalledWith(expect.any(String), 'alert-1', {+ type: 'pagerduty',+ pagerduty_routing_key: '0123456789abcdef0123456789abcdef',+ pagerduty_severity: 'error',+ pagerduty_region: 'eu',+ })+ expect(lemonToast.success).toHaveBeenCalledWith('3 notification destination(s) created.')expect(logic.values.pendingNotifications).toHaveLength(0)logic.unmount()diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.tsindex 7edd38f3f6ae..f42195efb232 100644--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts@@ -3,7 +3,13 @@ import { FilterLogicalOperator, HogFunctionType, PropertyFilterType, PropertyOpeimport { LogsAlertConfigurationThresholdOperatorEnumApi } from 'products/logs/frontend/generated/api.schemas'import { LogsAlertFormType } from '../logsAlertFormLogic'-import { buildLogsAlertFilterConfig, groupLogsAlertDestinations, runPreEnableChecks } from '../logsAlertUtils'+import {+ buildLogsAlertFilterConfig,+ getHogFunctionEventKind,+ groupLogsAlertDestinations,+ logsAlertEventKindsFor,+ runPreEnableChecks,+} from '../logsAlertUtils'const baseForm = (overrides: Partial<LogsAlertFormType> = {}): LogsAlertFormType => ({name: 'A',@@ -69,6 +75,16 @@ describe('logsAlertUtils', () => {filters: {},}) as unknown as HogFunctionType+ const pagerDutyHf = (id: string, name: string, eventId: string, enabled = true): HogFunctionType =>+ ({+ id,+ name,+ enabled,+ template: { id: 'template-pagerduty' },+ inputs: { routing_key: { secret: true }, severity: { value: 'critical' } },+ filters: { events: [{ id: eventId, type: 'events' }] },+ }) as unknown as HogFunctionType+const resolveSlack = (channelValue: string): string | null => `channel-for-${channelValue}`it('collapses multiple HogFunctions for the same slack channel into one group', () => {@@ -118,6 +134,40 @@ describe('logsAlertUtils', () => {expect(groups[0].hogFunctions).toHaveLength(2)})+ it('groups pagerduty HogFunctions by the key tail in their name, since the key itself is secret', () => {+ const groups = groupLogsAlertDestinations(+ [+ pagerDutyHf(+ 'hf-1',+ 'Logs alert — Errors (incident opened) → PagerDuty ••••cdef',+ '$logs_alert_incident_opened'+ ),+ pagerDutyHf(+ 'hf-2',+ 'Logs alert — Errors (incident closed) → PagerDuty ••••cdef',+ '$logs_alert_incident_closed'+ ),+ pagerDutyHf(+ 'hf-3',+ 'Logs alert — Errors (incident opened) → PagerDuty ••••0000',+ '$logs_alert_incident_opened'+ ),+ ],+ resolveSlack+ )++ expect(groups.map((g) => [g.key, g.label, g.type, g.hogFunctions.length])).toEqual([+ ['pagerduty:PagerDuty ••••cdef', 'PagerDuty ••••cdef', 'pagerduty', 2],+ ['pagerduty:PagerDuty ••••0000', 'PagerDuty ••••0000', 'pagerduty', 1],+ ])+ // The detail scene shows one row per kind; a kind it cannot match renders as missing.+ expect(+ logsAlertEventKindsFor(groups[0].type).map(+ (kind) => groups[0].hogFunctions.find((hf) => getHogFunctionEventKind(hf) === kind)?.id+ )+ ).toEqual(['hf-1', 'hf-2'])+ })+it('keeps distinct slack channels and webhook urls as separate groups', () => {const groups = groupLogsAlertDestinations([diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.tsindex 6333fad24fd8..8e993025cfc0 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts@@ -8,26 +8,55 @@ import { projectLogic } from 'scenes/projectLogic'import { HogFunctionType, IntegrationType } from '~/types'-import { AlertNotificationUrlInput } from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'+import {+ AlertNotificationUrlInput,+ AlertPagerDutyRegion,+ AlertPagerDutySeverity,+} from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'import { logsAlertsDestinationsCreate, logsAlertsDestinationsDeleteCreate } from 'products/logs/frontend/generated/api'+import { LogsAlertCreateDestinationApi } from 'products/logs/frontend/generated/api.schemas'import {buildLogsAlertFilterConfig,groupLogsAlertDestinations,+ LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY,LOGS_ALERT_NOTIFICATION_TYPE_SLACK,LOGS_ALERT_NOTIFICATION_TYPE_TEAMS,LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK,LogsAlertDestinationGroup,LogsAlertNotificationType,+ PAGERDUTY_ROUTING_KEY_PATTERN,PendingLogsAlertNotification,} from './logsAlertUtils'export const LOGS_ALERT_NOTIFICATION_TYPE_OPTIONS = [{ label: 'Slack', value: LOGS_ALERT_NOTIFICATION_TYPE_SLACK },{ label: 'Microsoft Teams', value: LOGS_ALERT_NOTIFICATION_TYPE_TEAMS },+ { label: 'PagerDuty', value: LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY },{ label: 'Webhook', value: LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK },]+function destinationCreateBody(notification: PendingLogsAlertNotification): LogsAlertCreateDestinationApi {+ switch (notification.type) {+ case LOGS_ALERT_NOTIFICATION_TYPE_SLACK:+ return {+ type: notification.type,+ slack_workspace_id: notification.slackWorkspaceId,+ slack_channel_id: notification.slackChannelId,+ slack_channel_name: notification.slackChannelName,+ }+ case LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY:+ return {+ type: notification.type,+ pagerduty_routing_key: notification.routingKey,+ pagerduty_severity: notification.severity,+ pagerduty_region: notification.region,+ }+ default:+ return { type: notification.type, webhook_url: notification.webhookUrl }+ }+}+export interface LogsAlertNotificationLogicProps {alertId?: string}@@ -43,6 +72,9 @@ export interface logsAlertNotificationLogicValues {existingHogFunctionsLoading: booleanfirstSlackIntegration: IntegrationType | undefinedintegrationsFailed: boolean+ pagerDutyRegion: AlertPagerDutyRegion+ pagerDutyRoutingKey: string+ pagerDutySeverity: AlertPagerDutySeveritypendingNotifications: PendingLogsAlertNotification[]selectedType: LogsAlertNotificationTypeslackChannelValue: string | null@@ -103,6 +135,15 @@ export interface logsAlertNotificationLogicActions {removePendingNotification: (index: number) => {index: number}+ setPagerDutyRegion: (pagerDutyRegion: AlertPagerDutyRegion) => {+ pagerDutyRegion: AlertPagerDutyRegion+ }+ setPagerDutyRoutingKey: (pagerDutyRoutingKey: string) => {+ pagerDutyRoutingKey: string+ }+ setPagerDutySeverity: (pagerDutySeverity: AlertPagerDutySeverity) => {+ pagerDutySeverity: AlertPagerDutySeverity+ }setPendingNotifications: (notifications: PendingLogsAlertNotification[]) => {notifications: PendingLogsAlertNotification[]}@@ -127,7 +168,8 @@ export interface logsAlertNotificationLogicMeta {selectedType: LogsAlertNotificationType,firstSlackIntegration: IntegrationType | undefined,slackChannelValue: string | null,- webhookUrl: string+ webhookUrl: string,+ pagerDutyRoutingKey: string) => string | undefineddestinationGroups: (existingHogFunctions: HogFunctionType[]) => LogsAlertDestinationGroup[]}@@ -162,6 +204,9 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([setSelectedType: (selectedType: LogsAlertNotificationType) => ({ selectedType }),setSlackChannelValue: (slackChannelValue: string | null) => ({ slackChannelValue }),setWebhookUrl: (webhookUrl: string) => ({ webhookUrl }),+ setPagerDutyRoutingKey: (pagerDutyRoutingKey: string) => ({ pagerDutyRoutingKey }),+ setPagerDutySeverity: (pagerDutySeverity: AlertPagerDutySeverity) => ({ pagerDutySeverity }),+ setPagerDutyRegion: (pagerDutyRegion: AlertPagerDutyRegion) => ({ pagerDutyRegion }),}),reducers({@@ -194,6 +239,24 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([setWebhookUrl: (_, { webhookUrl }) => webhookUrl,},],+ pagerDutyRoutingKey: [+ '' as string,+ {+ setPagerDutyRoutingKey: (_, { pagerDutyRoutingKey }) => pagerDutyRoutingKey,+ },+ ],+ pagerDutySeverity: [+ 'critical' as AlertPagerDutySeverity,+ {+ setPagerDutySeverity: (_, { pagerDutySeverity }) => pagerDutySeverity,+ },+ ],+ pagerDutyRegion: [+ 'us' as AlertPagerDutyRegion,+ {+ setPagerDutyRegion: (_, { pagerDutyRegion }) => pagerDutyRegion,+ },+ ],selectedType: [LOGS_ALERT_NOTIFICATION_TYPE_SLACK as LogsAlertNotificationType,{@@ -244,13 +307,22 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([},],addDisabledReason: [- (s) => [s.selectedType, s.firstSlackIntegration, s.slackChannelValue, s.webhookUrl],+ (s) => [s.selectedType, s.firstSlackIntegration, s.slackChannelValue, s.webhookUrl, s.pagerDutyRoutingKey],(selectedType: LogsAlertNotificationType,firstSlackIntegration: IntegrationType | undefined,slackChannelValue: string | null,- webhookUrl: string+ webhookUrl: string,+ pagerDutyRoutingKey: string): string | undefined => {+ if (selectedType === LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY) {+ if (!pagerDutyRoutingKey.trim()) {+ return 'Enter the PagerDuty integration key'+ }+ return PAGERDUTY_ROUTING_KEY_PATTERN.test(pagerDutyRoutingKey.trim())+ ? undefined+ : 'The integration key is 32 letters and digits'+ }if (selectedType !== LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {return webhookUrl ? undefined : 'Enter a webhook URL'}@@ -284,6 +356,20 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([actions.setSlackChannelValue(null)return}+ if (values.selectedType === LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY) {+ const routingKey = values.pagerDutyRoutingKey.trim()+ if (!PAGERDUTY_ROUTING_KEY_PATTERN.test(routingKey)) {+ return+ }+ actions.addPendingNotification({+ type: LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY,+ routingKey,+ severity: values.pagerDutySeverity,+ region: values.pagerDutyRegion,+ })+ actions.setPagerDutyRoutingKey('')+ return+ }if (!values.webhookUrl) {return}@@ -325,21 +411,9 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([const projectId = String(values.currentProjectId)const results = await Promise.allSettled(- pending.map((notification) => {- const payload =- notification.type === LOGS_ALERT_NOTIFICATION_TYPE_SLACK- ? {- type: LOGS_ALERT_NOTIFICATION_TYPE_SLACK,- slack_workspace_id: notification.slackWorkspaceId,- slack_channel_id: notification.slackChannelId,- slack_channel_name: notification.slackChannelName,- }- : {- type: notification.type,- webhook_url: notification.webhookUrl,- }- return logsAlertsDestinationsCreate(projectId, alertId, payload)- })+ pending.map((notification) =>+ logsAlertsDestinationsCreate(projectId, alertId, destinationCreateBody(notification))+ ))const failedNotifications = pending.filter((_, i) => results[i].status === 'rejected')diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.tsindex ea9feaba4c02..c4a441b8daeb 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts@@ -4,6 +4,8 @@ import {LOGS_ALERT_AUTO_DISABLED_EVENT_ID,LOGS_ALERT_ERRORED_EVENT_ID,LOGS_ALERT_FIRING_EVENT_ID,+ LOGS_ALERT_INCIDENT_CLOSED_EVENT_ID,+ LOGS_ALERT_INCIDENT_OPENED_EVENT_ID,LOGS_ALERT_RESOLVED_EVENT_ID,} from 'lib/constants'@@ -16,11 +18,13 @@ import {SlackChannelType,} from '~/types'+import {+ AlertPagerDutyRegion,+ AlertPagerDutySeverity,+} from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'import { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'-export type LogsAlertEventKind = 'firing' | 'resolved' | 'broken' | 'errored'--export const LOGS_ALERT_EVENT_KIND_ORDER: LogsAlertEventKind[] = ['firing', 'resolved', 'broken', 'errored']+export type LogsAlertEventKind = 'firing' | 'resolved' | 'broken' | 'errored' | 'incident_opened' | 'incident_closed'export const LOGS_ALERT_EVENT_KIND_META: Record<LogsAlertEventKind, { label: string; description: string }> = {firing: {@@ -39,6 +43,14 @@ export const LOGS_ALERT_EVENT_KIND_META: Record<LogsAlertEventKind, { label: strlabel: 'Errored',description: "Sent when an alert check can't evaluate.",},+ incident_opened: {+ label: 'Trigger incident',+ description: 'Opens an incident when the alert starts firing.',+ },+ incident_closed: {+ label: 'Resolve incident',+ description: 'Resolves the incident when the alert stops firing or is auto-disabled.',+ },}export function getHogFunctionEventKind(hf: HogFunctionType): LogsAlertEventKind | null {@@ -52,6 +64,10 @@ export function getHogFunctionEventKind(hf: HogFunctionType): LogsAlertEventKindreturn 'broken'case LOGS_ALERT_ERRORED_EVENT_ID:return 'errored'+ case LOGS_ALERT_INCIDENT_OPENED_EVENT_ID:+ return 'incident_opened'+ case LOGS_ALERT_INCIDENT_CLOSED_EVENT_ID:+ return 'incident_closed'default:return null}@@ -100,10 +116,22 @@ export const SNOOZE_DURATIONS = [export const LOGS_ALERT_NOTIFICATION_TYPE_SLACK = 'slack' as constexport const LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK = 'webhook' as constexport const LOGS_ALERT_NOTIFICATION_TYPE_TEAMS = 'teams' as const+export const LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY = 'pagerduty' as const+export function logsAlertEventKindsFor(type: LogsAlertNotificationType): LogsAlertEventKind[] {+ return type === LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY+ ? ['incident_opened', 'incident_closed']+ : ['firing', 'resolved', 'broken', 'errored']+}+export type LogsAlertNotificationType =| typeof LOGS_ALERT_NOTIFICATION_TYPE_SLACK| typeof LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK| typeof LOGS_ALERT_NOTIFICATION_TYPE_TEAMS+ | typeof LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY++// Mirrors the backend check, so a mistyped key is caught before the alert is saved instead+// of failing in the background after it.+export const PAGERDUTY_ROUTING_KEY_PATTERN = /^[A-Za-z0-9]{32}$/export type PendingLogsAlertNotification =| {@@ -120,6 +148,12 @@ export type PendingLogsAlertNotification =type: typeof LOGS_ALERT_NOTIFICATION_TYPE_TEAMSwebhookUrl: string}+ | {+ type: typeof LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY+ routingKey: string+ severity: AlertPagerDutySeverity+ region: AlertPagerDutyRegion+ }// Filter used to list every HogFunction tied to a given alert, regardless of which// event kind it handles. Deliberately omits the `events` array: the backend@@ -221,6 +255,14 @@ export function groupLogsAlertDestinations(type = LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOKkey = `webhook:${webhookUrl ?? hf.id}`label = webhookUrl ? `Webhook ${webhookUrl}` : 'Webhook'+ } else if (templateId === 'template-pagerduty') {+ // The integration key is a secret input, so the API never returns it. The name's+ // destination segment carries the key's tail and is what tells two PagerDuty+ // destinations apart.+ const destinationSegment = hf.name?.split(' → ').pop()+ type = LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY+ key = `pagerduty:${destinationSegment ?? hf.id}`+ label = destinationSegment ?? 'PagerDuty'} else {type = LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOKkey = `unknown:${hf.id}`diff --git a/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsx b/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsxindex 0d3d69fb66ec..f8efbccd7d9a 100644--- a/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsx+++ b/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsx@@ -15,7 +15,7 @@ import { HogFunctionType } from '~/types'import {getHogFunctionEventKind,LOGS_ALERT_EVENT_KIND_META,- LOGS_ALERT_EVENT_KIND_ORDER,+ logsAlertEventKindsFor,LogsAlertEventKind,resolveGroupLabel,} from 'products/logs/frontend/components/LogsAlerting/logsAlertUtils'@@ -166,7 +166,7 @@ export function LogsAlertNotificationDetailScene(): JSX.Element {<LemonSkeleton className="h-16" repeat={4} />) : (<div className="flex flex-col gap-2">- {LOGS_ALERT_EVENT_KIND_ORDER.map((kind) => {+ {logsAlertEventKindsFor(destinationGroup?.type ?? 'webhook').map((kind) => {const fn = kindToFn.get(kind)const meta = LOGS_ALERT_EVENT_KIND_META[kind]const isToggling = !!fn && togglingHogFunctionIds.includes(fn.id)