Skip to content

Commit

Permalink
feat: log request user-agent
Browse files Browse the repository at this point in the history
  • Loading branch information
fraxken committed Apr 8, 2024
1 parent a9bd25f commit 14c966a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
23 changes: 23 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"@openally/timestore": "^1.5.1",
"fastify": "^4.26.2",
"pino-pretty": "^11.0.0",
"ua-parser-js": "^1.0.37",
"undici": "^6.10.1",
"zod": "^3.22.4"
},
Expand Down
14 changes: 13 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import https from "node:https";
// Import Third-party Dependencies
import fastify, { FastifyHttpOptions, FastifyHttpsOptions, FastifyInstance } from "fastify";
import proxy from "@fastify/http-proxy";
import UAParser from "ua-parser-js";
import { getGlobalDispatcher } from "undici";

// Import Internal Dependencies
Expand All @@ -22,8 +23,13 @@ export function buildServer(
server.log.info(`GRAFANA_URL: ${context.grafanaApi}`);

server.addHook("onRequest", async(request) => {
const userAgent = new UAParser(request.headers["user-agent"])
.getResult();

if (request.method !== "OPTIONS") {
request.log.info(`(${request.id}) receiving request "${request.method} ${request.raw.url}"`);
const uaLog = formatUserAgentLog(userAgent);

request.log.info(`(${request.id}|${uaLog}) receiving request "${request.method} ${request.raw.url}"`);
}
});

Expand Down Expand Up @@ -61,3 +67,9 @@ export function buildServer(

return server;
}

function formatUserAgentLog(parsedUserAgent: UAParser.IResult): string {
const { browser: uaBrowser, os: uaOs } = parsedUserAgent;

return (uaBrowser.name && uaOs.name) ? `${uaOs.name}/${uaBrowser.name}` : parsedUserAgent.ua;
}

0 comments on commit 14c966a

Please sign in to comment.