Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add filter logs by status code #15

Merged
merged 2 commits into from
Mar 5, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 26 additions & 25 deletions src/worker.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const axiomDataset = 'my-dataset' // Your Axiom dataset
const axiomToken = 'xapt-xxx' // Your Axiom API token
const logsHttpMinStatusCode = 400 // Filter logs and send only logs with status code above
KrustyHack marked this conversation as resolved.
Show resolved Hide resolved

const requestHeadersToCapture = ['user-agent'];
const responseHeadersToCapture = ['cf-cache-status', 'cf-ray'];
Expand All @@ -23,7 +24,7 @@ const WORKER_ID = generateId(6)

const throttle = (fn, wait, maxLen) => {
let timeoutInProgress = false
return async function actual (...args) {
return async function actual(...args) {
const context = this

if (batch.length >= maxLen) {
Expand All @@ -40,7 +41,7 @@ const throttle = (fn, wait, maxLen) => {
}
}

async function sendLogs () {
async function sendLogs() {
if (batch.length === 0) {
return
}
Expand Down Expand Up @@ -77,7 +78,7 @@ function getHeaderMap(headers, allowlist) {
}, {});
}

async function handleRequest (request, context) {
async function handleRequest(request, context) {
const start = Date.now()

const response = await fetch(request)
Expand All @@ -92,34 +93,34 @@ async function handleRequest (request, context) {
}
})
}

batch.push({
_time: Date.now(),
request: {
url: request.url,
headers: getHeaderMap(request.headers, requestHeadersToCapture),
method: request.method,
...cf
},
response: {
duration,
headers: getHeaderMap(response.headers, responseHeadersToCapture),
status: response.status
},
worker: {
version: Version,
id: WORKER_ID,
started: workerTimestamp
}
})

if (response.status >= logsHttpMinStatusCode) {
batch.push({
_time: Date.now(),
request: {
url: request.url,
headers: getHeaderMap(request.headers, requestHeadersToCapture),
method: request.method,
...cf
},
response: {
duration,
headers: getHeaderMap(response.headers, responseHeadersToCapture),
status: response.status
},
worker: {
version: Version,
id: WORKER_ID,
started: workerTimestamp
}
})
}
context.waitUntil(throttledSendLogs())

return response
}

export default {
async fetch (req, _, context) {
async fetch(req, _, context) {
context.passThroughOnException()

if (!workerTimestamp) {
Expand Down