Get logs received

The `/received` api route allows customers to retrieve their edge HTTP logs.

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Get logs received
8
 * The `/received` api route allows customers to retrieve their edge HTTP logs.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_identifier: string,
13
  end: string | undefined,
14
  sample: string | undefined,
15
  timestamps: "unix" | "unixnano" | "rfc3339" | undefined,
16
  count: string | undefined,
17
  fields: string | undefined,
18
  start: string | undefined
19
) {
20
  const url = new URL(
21
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/logs/received`
22
  );
23
  for (const [k, v] of [
24
    ["end", end],
25
    ["sample", sample],
26
    ["timestamps", timestamps],
27
    ["count", count],
28
    ["fields", fields],
29
    ["start", start],
30
  ]) {
31
    if (v !== undefined && v !== "") {
32
      url.searchParams.append(k, v);
33
    }
34
  }
35
  const response = await fetch(url, {
36
    method: "GET",
37
    headers: {
38
      "X-AUTH-EMAIL": auth.email,
39
      "X-AUTH-KEY": auth.key,
40
      Authorization: "Bearer " + auth.token,
41
    },
42
    body: undefined,
43
  });
44
  if (!response.ok) {
45
    const text = await response.text();
46
    throw new Error(`${response.status} ${text}`);
47
  }
48
  return await response.json();
49
}
50