capture total time of fetching a page

This commit is contained in:
Hongbo Wu
2024-05-13 17:01:52 +08:00
parent 28a5af54e0
commit 7634ed667f
2 changed files with 30 additions and 35 deletions

View File

@ -1,13 +1,12 @@
import { PostHog } from 'posthog-node'
interface AnalyticEvent {
distinctId: string
event: string
result: 'success' | 'failure'
properties?: Record<string | number, any>
}
interface AnalyticClient {
capture: (event: AnalyticEvent) => void
capture: (userIds: string[], event: AnalyticEvent) => void
shutdownAsync?: () => Promise<void>
}
@ -18,17 +17,23 @@ class PostHogClient implements AnalyticClient {
this.client = new PostHog(apiKey)
}
capture({ distinctId, event, properties }: AnalyticEvent) {
// get client from request context
capture(userIds: string[], { properties, result }: AnalyticEvent) {
if (process.env.SEND_ANALYTICS) {
userIds.forEach((userId) => {
this.client.capture({
distinctId: userId,
event: `content_fetch_${result}`,
properties: {
...properties,
env: process.env.API_ENV,
},
})
})
this.client.capture({
distinctId,
event,
properties: {
...properties,
env: process.env.API_ENV || 'demo',
},
})
return
}
console.log('analytics', { userIds, result, properties })
}
async shutdownAsync() {

View File

@ -148,33 +148,23 @@ export const contentFetchRequestHandler: RequestHandler = async (req, res) => {
logRecord.error = 'unknown error'
}
// capture error event
users.forEach((user) => {
analytics.capture({
distinctId: user.id,
event: 'content_fetch_failure',
properties: {
url,
},
})
})
return res.sendStatus(500)
} finally {
logRecord.totalTime = Date.now() - functionStartTime
console.log(`parse-page result`, logRecord)
}
// capture success event
users.forEach((user) => {
analytics.capture({
distinctId: user.id,
event: 'content_fetch_success',
properties: {
url,
},
})
})
// capture events
analytics.capture(
users.map((user) => user.id),
{
result: logRecord.error ? 'failure' : 'success',
properties: {
url,
totalTime: logRecord.totalTime,
},
}
)
}
res.sendStatus(200)
}