Skip to content

Commit b2a0cb8

Browse files
o11y with context-aware logging and distributed tracing (#78)
* o11y with context-aware logging and distributed tracing - Introduce a new centralized logging module (`src/server/lib/logger/`) with AsyncLocalStorage-based context propagation - Add Datadog tracing integration with automatic correlation ID and span tracking across async operations - Migrate all services and API routes to use context-aware `getLogger()` pattern instead of static logger instances - Standardize log format to single-line key=value style for better log aggregation - Selective/single deploys now are instantly processed * use logger serializer for errors * fix webhook invokaction log to only log when webhook is actually invoked * use withLogContext to avoid contex overwriting * drop [bot] made issue_comment webhooks * add dd-trace service names for redis and pg * drop dd trace for bot issue_comment activity * standardize webhook and helm log messages * standardize more log messages * centralize buildUuid in log context * dont log bot events * fix service names * standardize log messages to Category: action key=value format * add missing buildUuid to log context * clean up logs * fix oversized api response * fix test * cleanup logs * logger migration * rename logger.ts to rootLogger.ts to fix import ambiguity * fix build * fix swallowed errors with proper logging * move rootLogger to logger module * V2 endpoint to fetch deployment pods by deployment name (#80) --------- Co-authored-by: Levon Tikoyan <ltikoyan@goodrx.com>
1 parent 97ecc8f commit b2a0cb8

141 files changed

Lines changed: 4259 additions & 3152 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎dd-trace.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Copyright 2025 GoodRx, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
'use strict';
18+
19+
const tracer = require('dd-trace').init({
20+
serviceMapping: {
21+
redis: 'lifecycle-redis',
22+
ioredis: 'lifecycle-redis',
23+
pg: 'lifecycle-postgres',
24+
},
25+
});
26+
27+
const blocklist = [/^\/api\/health/, /^\/api\/jobs/, /^\/_next\/static/, /^\/_next\/webpack-hmr/];
28+
29+
tracer.use('http', {
30+
server: {
31+
blocklist,
32+
},
33+
client: {
34+
blocklist,
35+
},
36+
});
37+
38+
tracer.use('next', {
39+
blocklist,
40+
});
41+
42+
tracer.use('net', false);
43+
tracer.use('dns', false);

‎helm/environments/local/lifecycle.yaml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ components:
6666
value: web
6767
- name: PORT
6868
value: '80'
69+
- name: DD_TRACE_ENABLED
70+
value: 'false'
6971
ports:
7072
- name: http
7173
containerPort: 80
@@ -122,6 +124,8 @@ components:
122124
value: '10000'
123125
- name: LIFECYCLE_UI_HOSTHAME_WITH_SCHEME
124126
value: 'http://localhost:8000'
127+
- name: DD_TRACE_ENABLED
128+
value: 'false'
125129
ports:
126130
- name: http
127131
containerPort: 80

‎next-env.d.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/// <reference types="next" />
22
/// <reference types="next/image-types/global" />
3+
/// <reference types="next/navigation-types/compat/navigation" />
34

45
// NOTE: This file should not be edited
5-
// see https://nextjs.org/docs/basic-features/typescript for more information.
6+
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.

‎package.json‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,17 @@
77
],
88
"scripts": {
99
"babel-node": "babel-node --extensions '.ts'",
10-
"dev": "LOG_LEVEL=debug ts-node -r tsconfig-paths/register --project tsconfig.server.json ws-server.ts | pino-pretty -c -t HH:MM -i pid,hostname,filename -o '{msg}'",
10+
"dev": "LOG_LEVEL=debug ts-node -r ./dd-trace.js -r tsconfig-paths/register --project tsconfig.server.json ws-server.ts | pino-pretty -c -t HH:MM -i pid,hostname,filename -o '{msg}'",
1111
"build": "next build && tsc --project tsconfig.server.json && tsc-alias -p tsconfig.server.json",
12-
"start": "NEXT_MANUAL_SIG_HANDLE=true NODE_ENV=production node .next/ws-server.js",
12+
"start": "NEXT_MANUAL_SIG_HANDLE=true NODE_ENV=production node -r ./dd-trace.js .next/ws-server.js",
1313
"run-prod": "port=5001 pnpm run start",
1414
"knex": "pnpm run knex",
1515
"test": "NODE_ENV=test jest --maxWorkers=75%",
1616
"lint": "eslint --ext .ts src",
1717
"lint:fix": "pnpm run lint --fix",
1818
"ts-check": "tsc --project tsconfig.json",
19-
"db:migrate": "NODE_OPTIONS='--loader ts-node/esm' knex migrate:latest",
20-
"db:rollback": "NODE_OPTIONS='--loader ts-node/esm' knex migrate:rollback",
19+
"db:migrate": "tsx node_modules/knex/bin/cli.js migrate:latest",
20+
"db:rollback": "tsx node_modules/knex/bin/cli.js migrate:rollback",
2121
"db:seed": "knex seed:run",
2222
"prepare": "husky install",
2323
"generate:jsonschemas": "tsx ./scripts/generateSchemas.ts generatejson",

‎src/app/api/v2/builds/[uuid]/services/[name]/build-jobs/[jobName]/route.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,12 @@
1515
*/
1616

1717
import { NextRequest } from 'next/server';
18-
import rootLogger from 'server/lib/logger';
18+
import { getLogger } from 'server/lib/logger';
1919
import { LogStreamingService } from 'server/services/logStreaming';
2020
import { HttpError } from '@kubernetes/client-node';
2121
import { createApiHandler } from 'server/lib/createApiHandler';
2222
import { errorResponse, successResponse } from 'server/lib/response';
2323

24-
const logger = rootLogger.child({
25-
filename: __filename,
26-
});
27-
2824
interface RouteParams {
2925
uuid: string;
3026
name: string;
@@ -96,7 +92,7 @@ const getHandler = async (req: NextRequest, { params }: { params: RouteParams })
9692
const { uuid, name: serviceName, jobName } = params;
9793

9894
if (!uuid || !jobName || !serviceName) {
99-
logger.warn({ uuid, serviceName, jobName }, 'Missing or invalid path parameters');
95+
getLogger().warn(`API: invalid params uuid=${uuid} serviceName=${serviceName} jobName=${jobName}`);
10096
return errorResponse('Missing or invalid parameters', { status: 400 }, req);
10197
}
10298

@@ -107,7 +103,7 @@ const getHandler = async (req: NextRequest, { params }: { params: RouteParams })
107103

108104
return successResponse(response, { status: 200 }, req);
109105
} catch (error: any) {
110-
logger.error({ err: error, uuid, serviceName, jobName }, 'Error getting log streaming info');
106+
getLogger().error({ error }, `API: log streaming info failed jobName=${jobName} service=${serviceName}`);
111107

112108
if (error.message === 'Build not found') {
113109
return errorResponse('Build not found', { status: 404 }, req);

‎src/app/api/v2/builds/[uuid]/services/[name]/build-jobs/route.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,12 @@
1515
*/
1616

1717
import { NextRequest } from 'next/server';
18-
import rootLogger from 'server/lib/logger';
18+
import { getLogger } from 'server/lib/logger';
1919
import { HttpError } from '@kubernetes/client-node';
2020
import { createApiHandler } from 'server/lib/createApiHandler';
2121
import { errorResponse, successResponse } from 'server/lib/response';
2222
import { getNativeBuildJobs } from 'server/lib/kubernetes/getNativeBuildJobs';
2323

24-
const logger = rootLogger.child({
25-
filename: __filename,
26-
});
27-
2824
/**
2925
* @openapi
3026
* /api/v2/builds/{uuid}/services/{name}/builds:
@@ -87,7 +83,7 @@ const getHandler = async (req: NextRequest, { params }: { params: { uuid: string
8783
const { uuid, name } = params;
8884

8985
if (!uuid || !name) {
90-
logger.warn({ uuid, name }, 'Missing or invalid path parameters');
86+
getLogger().warn(`API: invalid params uuid=${uuid} name=${name}`);
9187
return errorResponse('Missing or invalid uuid or name parameters', { status: 400 }, req);
9288
}
9389

@@ -99,7 +95,7 @@ const getHandler = async (req: NextRequest, { params }: { params: { uuid: string
9995

10096
return successResponse(response, { status: 200 }, req);
10197
} catch (error) {
102-
logger.error({ err: error }, `Error getting build logs for service ${name} in environment ${uuid}.`);
98+
getLogger().error({ error }, `API: build logs fetch failed service=${name}`);
10399

104100
if (error instanceof HttpError) {
105101
if (error.response?.statusCode === 404) {

‎src/app/api/v2/builds/[uuid]/services/[name]/deploy-jobs/[jobName]/route.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,12 @@
1515
*/
1616

1717
import { NextRequest } from 'next/server';
18-
import rootLogger from 'server/lib/logger';
18+
import { getLogger } from 'server/lib/logger';
1919
import { LogStreamingService } from 'server/services/logStreaming';
2020
import { HttpError } from '@kubernetes/client-node';
2121
import { createApiHandler } from 'server/lib/createApiHandler';
2222
import { errorResponse, successResponse } from 'server/lib/response';
2323

24-
const logger = rootLogger.child({
25-
filename: __filename,
26-
});
27-
2824
interface RouteParams {
2925
uuid: string;
3026
name: string;
@@ -96,7 +92,7 @@ const getHandler = async (req: NextRequest, { params }: { params: RouteParams })
9692
const { uuid, name: serviceName, jobName } = params;
9793

9894
if (!uuid || !jobName || !serviceName) {
99-
logger.warn({ uuid, serviceName, jobName }, 'Missing or invalid path parameters');
95+
getLogger().warn(`API: invalid params uuid=${uuid} serviceName=${serviceName} jobName=${jobName}`);
10096
return errorResponse('Missing or invalid parameters', { status: 400 }, req);
10197
}
10298

@@ -107,7 +103,7 @@ const getHandler = async (req: NextRequest, { params }: { params: RouteParams })
107103

108104
return successResponse(response, { status: 200 }, req);
109105
} catch (error: any) {
110-
logger.error({ err: error, uuid, serviceName, jobName }, 'Error getting log streaming info');
106+
getLogger().error({ error }, `API: log streaming info failed jobName=${jobName} service=${serviceName}`);
111107

112108
if (error.message === 'Deploy not found') {
113109
return errorResponse('Deploy not found', { status: 404 }, req);

‎src/app/api/v2/builds/[uuid]/services/[name]/deploy-jobs/route.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,12 @@
1515
*/
1616

1717
import { NextRequest } from 'next/server';
18-
import rootLogger from 'server/lib/logger';
18+
import { getLogger } from 'server/lib/logger';
1919
import { HttpError } from '@kubernetes/client-node';
2020
import { createApiHandler } from 'server/lib/createApiHandler';
2121
import { errorResponse, successResponse } from 'server/lib/response';
2222
import { getDeploymentJobs } from 'server/lib/kubernetes/getDeploymentJobs';
2323

24-
const logger = rootLogger.child({
25-
filename: __filename,
26-
});
27-
2824
/**
2925
* @openapi
3026
* /api/v2/builds/{uuid}/services/{name}/deploys:
@@ -85,7 +81,7 @@ const getHandler = async (req: NextRequest, { params }: { params: { uuid: string
8581
const { uuid, name } = params;
8682

8783
if (!uuid || !name) {
88-
logger.warn({ uuid, name }, 'Missing or invalid path parameters');
84+
getLogger().warn(`API: invalid params uuid=${uuid} name=${name}`);
8985
return errorResponse('Missing or invalid uuid or name parameters', { status: 400 }, req);
9086
}
9187

@@ -97,7 +93,7 @@ const getHandler = async (req: NextRequest, { params }: { params: { uuid: string
9793

9894
return successResponse(response, { status: 200 }, req);
9995
} catch (error) {
100-
logger.error({ err: error }, `Error getting deploy logs for service ${name} in environment ${uuid}.`);
96+
getLogger().error({ error }, `API: deploy logs fetch failed service=${name}`);
10197

10298
if (error instanceof HttpError) {
10399
if (error.response?.statusCode === 404) {
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/**
2+
* Copyright 2025 GoodRx, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { NextRequest } from 'next/server';
18+
import { getLogger } from 'server/lib/logger';
19+
import { HttpError } from '@kubernetes/client-node';
20+
import { createApiHandler } from 'server/lib/createApiHandler';
21+
import { errorResponse, successResponse } from 'server/lib/response';
22+
import { getDeploymentPods } from 'server/lib/kubernetes/getDeploymentPods';
23+
24+
/**
25+
* @openapi
26+
* /api/v2/builds/{uuid}/services/{name}/pods:
27+
* get:
28+
* summary: List pods for a service
29+
* description: |
30+
* Returns a list of all pods for a specific service within a build.
31+
* This includes pod status, age, restarts, readiness, and container information.
32+
* tags:
33+
* - Deployments
34+
* operationId: listDeploymentPods
35+
* parameters:
36+
* - in: path
37+
* name: uuid
38+
* required: true
39+
* schema:
40+
* type: string
41+
* description: The UUID of the build
42+
* - in: path
43+
* name: name
44+
* required: true
45+
* schema:
46+
* type: string
47+
* description: The name of the service
48+
* responses:
49+
* '200':
50+
* description: List of pods
51+
* content:
52+
* application/json:
53+
* schema:
54+
* $ref: '#/components/schemas/GetDeploymentPodsSuccessResponse'
55+
* '400':
56+
* description: Invalid parameters
57+
* content:
58+
* application/json:
59+
* schema:
60+
* $ref: '#/components/schemas/ApiErrorResponse'
61+
* '404':
62+
* description: Environment or service not found
63+
* content:
64+
* application/json:
65+
* schema:
66+
* $ref: '#/components/schemas/ApiErrorResponse'
67+
* '502':
68+
* description: Failed to communicate with Kubernetes
69+
* content:
70+
* application/json:
71+
* schema:
72+
* $ref: '#/components/schemas/ApiErrorResponse'
73+
* '500':
74+
* description: Internal server error
75+
* content:
76+
* application/json:
77+
* schema:
78+
* $ref: '#/components/schemas/ApiErrorResponse'
79+
*/
80+
const getHandler = async (req: NextRequest, { params }: { params: { uuid: string; name: string } }) => {
81+
const { uuid, name } = params;
82+
83+
if (!uuid || !name) {
84+
getLogger().warn(`API: invalid params uuid=${uuid} name=${name}`);
85+
return errorResponse('Missing or invalid uuid or name parameters', { status: 400 }, req);
86+
}
87+
88+
try {
89+
const pods = await getDeploymentPods(name, uuid);
90+
91+
const response = { pods };
92+
93+
return successResponse(response, { status: 200 }, req);
94+
} catch (error) {
95+
getLogger().error({ error }, `API: pods fetch failed service=${name}`);
96+
97+
if (error instanceof HttpError) {
98+
if (error.response?.statusCode === 404) {
99+
return errorResponse('Environment or service not found.', { status: 404 }, req);
100+
}
101+
return errorResponse('Failed to communicate with Kubernetes.', { status: 502 }, req);
102+
}
103+
104+
return errorResponse('Internal server error occurred.', { status: 500 }, req);
105+
}
106+
};
107+
108+
export const GET = createApiHandler(getHandler);

‎src/pages/api/health.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
import { NextApiRequest, NextApiResponse } from 'next';
1818
import { defaultDb } from 'server/lib/dependencies';
19-
import logger from 'server/lib/logger';
19+
import { getLogger } from 'server/lib/logger';
2020
import RedisClient from 'server/lib/redisClient';
2121

2222
export default async function healthHandler(req: NextApiRequest, res: NextApiResponse) {
@@ -30,7 +30,7 @@ export default async function healthHandler(req: NextApiRequest, res: NextApiRes
3030
await defaultDb.knex.raw('SELECT 1');
3131
res.status(200).json({ status: 'Healthy' });
3232
} catch (error) {
33-
logger.error(`Health check failed. Error:\n ${error}`);
33+
getLogger().error({ error }, 'Health: check failed');
3434
return res.status(500).json({ status: 'Unhealthy', error: `An error occurred while performing health check.` });
3535
}
3636
}

0 commit comments

Comments
 (0)