🔊 Logging context with user info and request_id (#354)

This commit is contained in:
Anton Shepilov
2024-02-01 12:07:45 +03:00
committed by GitHub
parent 1ade3de40d
commit 8a18a54e1f
4 changed files with 27 additions and 0 deletions
@@ -0,0 +1,11 @@
import { AsyncLocalStorage } from "async_hooks";
export interface ExecutionContext {
request_id: string;
user_id: string;
user_email: string;
company_id: string;
}
export const executionStorage = new AsyncLocalStorage<ExecutionContext>();
executionStorage.enterWith({} as ExecutionContext);
@@ -1,5 +1,6 @@
import pino from "pino";
import { Configuration } from "./configuration";
import { executionStorage } from "./execution-storage";
const config = new Configuration("logger");
@@ -9,6 +10,9 @@ export const logger = pino({
name: "TdriveApp",
level: config.get("level", "info") || "info",
prettyPrint: false,
mixin() {
return executionStorage.getStore() ? executionStorage.getStore() : {};
},
});
export const getLogger = (name?: string): TdriveLogger =>
@@ -4,6 +4,7 @@ import cookie from "@fastify/cookie";
import fp from "fastify-plugin";
import config from "../../../../config";
import { JwtType } from "../../types";
import { executionStorage } from "../../../framework/execution-storage";
const jwtPlugin: FastifyPluginCallback = (fastify, _opts, next) => {
fastify.register(cookie);
@@ -30,6 +31,10 @@ const jwtPlugin: FastifyPluginCallback = (fastify, _opts, next) => {
...{ allow_tracking: jwt.track || false },
...{ public_token_document_id: jwt.public_token_document_id || null },
};
executionStorage.getStore().user_id = request.currentUser.id;
executionStorage.getStore().user_email = request.currentUser.email;
request.log.debug(`Authenticated as user ${request.currentUser.id}`);
};
@@ -13,6 +13,8 @@ import path from "path";
import swaggerPlugin from "fastify-swagger";
import { SkipCLI } from "../../framework/decorators/skip";
import fs from "fs";
import { ExecutionContext, executionStorage } from "../../framework/execution-storage";
// import { throws } from "assert";
export default class WebServerService extends TdriveService<WebServerAPI> implements WebServerAPI {
name = "webserver";
@@ -41,6 +43,11 @@ export default class WebServerService extends TdriveService<WebServerAPI> implem
logger: false,
});
this.server.addHook("onRequest", (req, res, done) => {
const defaultStoreValues = { request_id: req.id } as ExecutionContext;
executionStorage.run(defaultStoreValues, done);
});
this.server.addHook("onResponse", (req, reply, done) => {
logger.info(`${reply.raw.statusCode} ${req.raw.method} ${req.raw.url}`);
done();