database config

This commit is contained in:
hannathkadher
2025-04-22 21:44:46 +04:00
parent fcb27155d8
commit cff947a84a
3 changed files with 40 additions and 30 deletions

View File

@ -2,48 +2,56 @@ import { Logger as WinstonLogger } from 'winston';
import { Logger as TypeOrmLogger } from 'typeorm';
import { requestContext } from '@app/common/context/request-context';
const ERROR_THRESHOLD = 2000;
export class TypeOrmWinstonLogger implements TypeOrmLogger {
constructor(
private readonly logger: WinstonLogger,
private readonly slowQueryThreshold = 500, // ms
) {}
constructor(private readonly logger: WinstonLogger) {}
private getContext() {
const context = requestContext.getStore();
return {
requestId: context?.requestId ?? 'N/A',
userId: context?.userId ?? null,
};
}
private extractTable(query: string): string {
const match =
query.match(/from\s+["`]?(\w+)["`]?/i) ||
query.match(/into\s+["`]?(\w+)["`]?/i);
return match?.[1] ?? 'unknown';
}
logQuery(query: string, parameters?: any[]) {
const context = requestContext.getStore();
const requestId = context?.requestId ?? 'N/A';
const start = Date.now();
const timeout = setTimeout(() => {
const duration = Date.now() - start;
const isSlow = duration > this.slowQueryThreshold;
this.logger[isSlow ? 'warn' : 'debug'](`[DB][QUERY] ${query}`, {
requestId,
parameters,
duration: `${duration}ms`,
isSlow,
});
}, 0);
// Just ensures the setTimeout fires after this function returns
clearTimeout(timeout);
const context = this.getContext();
this.logger.debug(`[DB][QUERY] ${query}`, {
...context,
table: this.extractTable(query),
parameters,
});
}
logQueryError(error: string | Error, query: string, parameters?: any[]) {
const requestId = requestContext.getStore()?.requestId ?? 'N/A';
const context = this.getContext();
this.logger.error(`[DB][ERROR] ${query}`, {
requestId,
...context,
table: this.extractTable(query),
parameters,
error,
});
}
logQuerySlow(time: number, query: string, parameters?: any[]) {
const requestId = requestContext.getStore()?.requestId ?? 'N/A';
this.logger.warn(`🔥 [DB][SLOW > ${time}ms] ${query}`, {
requestId,
const context = this.getContext();
const severity = time > ERROR_THRESHOLD ? 'error' : 'warn';
const label = severity === 'error' ? 'VERY SLOW' : 'SLOW';
this.logger[severity](`[DB][${label} > ${time}ms] ${query}`, {
...context,
table: this.extractTable(query),
parameters,
time,
duration: `${time}ms`,
severity,
});
}

View File

@ -2,7 +2,8 @@ import { utilities as nestWinstonModuleUtilities } from 'nest-winston';
import * as winston from 'winston';
export const winstonLoggerOptions: winston.LoggerOptions = {
level: 'debug',
level:
process.env.AZURE_POSTGRESQL_DATABASE === 'development' ? 'debug' : 'error',
transports: [
new winston.transports.Console({
format: winston.format.combine(