ClsService for async request messages & logging

This commit is contained in:
2024-09-23 11:20:00 +02:00
parent 860d30b16f
commit 974a6503ef
9 changed files with 55 additions and 65 deletions

View File

@@ -2,30 +2,29 @@ import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { drizzle } from 'drizzle-orm/node-postgres';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { ClsService } from 'nestjs-cls';
import pkg from 'pg';
import { ContextService, RequestContext } from 'src/context/context.service';
import { Logger } from 'winston';
import * as schema from './schema';
import { PG_CONNECTION } from './schema';
const { Pool } = pkg;
@Module({
providers: [
ContextService,
{
provide: PG_CONNECTION,
inject: [ConfigService, WINSTON_MODULE_PROVIDER, ContextService],
useFactory: async (configService: ConfigService, logger: Logger, contextService: ContextService) => {
inject: [ConfigService, WINSTON_MODULE_PROVIDER, ClsService],
useFactory: async (configService: ConfigService, logger: Logger, cls: ClsService) => {
const connectionString = configService.get<string>('DATABASE_URL');
const pool = new Pool({
connectionString,
// ssl: true,
// ssl: true, // Falls benötigt
});
// Definiere einen benutzerdefinierten Logger für Drizzle
const drizzleLogger = {
logQuery(query: string, params: unknown[]): void {
const context: RequestContext | undefined = contextService.getContext();
const ip = context?.ip || 'unknown';
const countryCode = context?.countryCode || 'unknown';
const ip = cls.get('ip') || 'unknown';
const countryCode = cls.get('countryCode') || 'unknown';
logger.info(`IP: ${ip} (${countryCode}) - Query: ${query} - Params: ${JSON.stringify(params)}`);
},
};