Skip to content
This repository was archived by the owner on Jan 16, 2025. It is now read-only.

Commit 8094576

Browse files
mcaulifnnpalm
andauthored
fix(logging): Add context to webhook logs (#1401)
* fix(logging): Add context to webhook logs * Update modules/webhook/lambdas/webhook/src/webhook/handler.ts Co-authored-by: Niek Palm <[email protected]> * Updating per recommendation * Updating per recommendation * Moving log fields to end, adjusting format Co-authored-by: Niek Palm <[email protected]>
1 parent e8166b9 commit 8094576

File tree

2 files changed

+47
-14
lines changed

2 files changed

+47
-14
lines changed

Diff for: modules/webhook/lambdas/webhook/src/webhook/handler.ts

+39-14
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ import { Webhooks } from '@octokit/webhooks';
33
import { sendActionRequest } from '../sqs';
44
import { CheckRunEvent, WorkflowJobEvent } from '@octokit/webhooks-types';
55
import { getParameterValue } from '../ssm';
6-
import { logger as rootLogger } from './logger';
6+
import { logger as rootLogger, LogFields } from './logger';
77
import { Response } from '../lambda';
88

9+
const supportedEvents = ['check_run', 'workflow_job'];
910
const logger = rootLogger.getChildLogger();
1011

1112
export async function handle(headers: IncomingHttpHeaders, body: string): Promise<Response> {
@@ -24,33 +25,53 @@ export async function handle(headers: IncomingHttpHeaders, body: string): Promis
2425
return response;
2526
}
2627
const payload = JSON.parse(body);
27-
logger.info(`Received Github event ${githubEvent} from ${payload.repository.full_name}`);
28+
LogFields.fields.event = githubEvent;
29+
LogFields.fields.repository = payload.repository.full_name;
30+
LogFields.fields.action = payload.action;
31+
32+
if (!supportedEvents.includes(githubEvent)) {
33+
logger.warn(`Unsupported event type.`, LogFields.print());
34+
return {
35+
statusCode: 202,
36+
body: `Ignoring unsupported event ${githubEvent}`,
37+
};
38+
}
39+
40+
LogFields.fields.name = payload[githubEvent].name;
41+
LogFields.fields.status = payload[githubEvent].status;
42+
LogFields.fields.started_at = payload[githubEvent]?.started_at;
43+
44+
/*
45+
The app subscribes to all `check_run` and `workflow_job` events.
46+
If the event status is `completed`, log the data for workflow metrics.
47+
*/
48+
LogFields.fields.completed_at = payload[githubEvent]?.completed_at;
49+
LogFields.fields.conclusion = payload[githubEvent]?.conclusion;
2850

2951
if (isRepoNotAllowed(payload.repository.full_name)) {
30-
console.warn(`Received event from unauthorized repository ${payload.repository.full_name}`);
52+
logger.error(`Received event from unauthorized repository ${payload.repository.full_name}`, LogFields.print());
3153
return {
3254
statusCode: 403,
3355
};
3456
}
3557

58+
logger.info(`Processing Github event`, LogFields.print());
59+
3660
if (githubEvent == 'workflow_job') {
3761
response = await handleWorkflowJob(payload as WorkflowJobEvent, githubEvent);
3862
} else if (githubEvent == 'check_run') {
3963
response = await handleCheckRun(payload as CheckRunEvent, githubEvent);
40-
} else {
41-
logger.warn(`Ignoring unsupported event ${githubEvent}`);
42-
response = {
43-
statusCode: 202,
44-
body: `Ignoring unsupported event ${githubEvent}`,
45-
};
4664
}
4765

4866
return response;
4967
}
5068

5169
async function verifySignature(githubEvent: string, signature: string, body: string): Promise<number> {
5270
if (!signature) {
53-
logger.error("Github event doesn't have signature. This webhook requires a secret to be configured.");
71+
logger.error(
72+
"Github event doesn't have signature. This webhook requires a secret to be configured.",
73+
LogFields.print(),
74+
);
5475
return 500;
5576
}
5677

@@ -60,7 +81,7 @@ async function verifySignature(githubEvent: string, signature: string, body: str
6081
secret: secret,
6182
});
6283
if (!(await webhooks.verify(body, signature))) {
63-
logger.error('Unable to verify signature!');
84+
logger.error('Unable to verify signature!', LogFields.print());
6485
return 401;
6586
}
6687
return 200;
@@ -70,7 +91,10 @@ async function handleWorkflowJob(body: WorkflowJobEvent, githubEvent: string): P
7091
const disableCheckWorkflowJobLabelsEnv = process.env.DISABLE_CHECK_WORKFLOW_JOB_LABELS || 'false';
7192
const disableCheckWorkflowJobLabels = JSON.parse(disableCheckWorkflowJobLabelsEnv) as boolean;
7293
if (!disableCheckWorkflowJobLabels && !canRunJob(body)) {
73-
logger.warn(`Received event contains runner labels '${body.workflow_job.labels}' that are not accepted.`);
94+
logger.warn(
95+
`Received event contains runner labels '${body.workflow_job.labels}' that are not accepted.`,
96+
LogFields.print(),
97+
);
7498
return {
7599
statusCode: 202,
76100
body: `Received event contains runner labels '${body.workflow_job.labels}' that are not accepted.`,
@@ -90,7 +114,7 @@ async function handleWorkflowJob(body: WorkflowJobEvent, githubEvent: string): P
90114
installationId: installationId,
91115
});
92116
}
93-
console.info(`Successfully queued job for ${body.repository.full_name}`);
117+
logger.info(`Successfully queued job for ${body.repository.full_name}`, LogFields.print());
94118
return { statusCode: 201 };
95119
}
96120

@@ -108,7 +132,7 @@ async function handleCheckRun(body: CheckRunEvent, githubEvent: string): Promise
108132
installationId: installationId,
109133
});
110134
}
111-
console.info(`Successfully queued job for ${body.repository.full_name}`);
135+
logger.info(`Successfully queued job for ${body.repository.full_name}`, LogFields.print());
112136
return { statusCode: 201 };
113137
}
114138

@@ -139,6 +163,7 @@ function canRunJob(job: WorkflowJobEvent): boolean {
139163
`Received workflow job event with labels: '${JSON.stringify(job.workflow_job.labels)}'. The event does ${
140164
runnerMatch ? '' : 'NOT '
141165
}match the configured labels: '${Array.from(runnerLabels).join(',')}'`,
166+
LogFields.print(),
142167
);
143168
return runnerMatch;
144169
}

Diff for: modules/webhook/lambdas/webhook/src/webhook/logger.ts

+8
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,11 @@ export const logger = new Logger({
88
overwriteConsole: true,
99
type: process.env.LOG_TYPE || 'pretty',
1010
});
11+
12+
export class LogFields {
13+
static fields: { [key: string]: string } = {};
14+
15+
public static print(): string {
16+
return JSON.stringify(LogFields.fields);
17+
}
18+
}

0 commit comments

Comments
 (0)