All files / src/lib/monitoring logger.ts

86.99% Statements 214/246
80% Branches 52/65
90.9% Functions 10/11
86.99% Lines 214/246

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 2471x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 1x 1x 27x 27x 27x 27x 27x 27x 27x 9x 9x 9x 9x 9x 9x 27x 27x 27x 1x 1x 27x 27x               27x 27x 27x 27x 27x             27x 27x 27x       27x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 2x                   1x 1x 1x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x     2x 1x 1x 1x  
import crypto from 'crypto';
import { prisma } from '@/lib/prisma';
 
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
 
export type LogCategory =
  | 'API'
  | 'DATABASE'
  | 'AUTH'
  | 'CLIENT'
  | 'PAYMENT'
  | 'ORDER'
  | 'CART'
  | 'PRODUCT'
  | 'SUPPORT'
  | 'SYSTEM'
  | 'PERFORMANCE'
  | 'CRON';
 
interface LogContext {
  url?: string;
  method?: string;
  statusCode?: number;
  userId?: number;
  userEmail?: string;
  userAgent?: string;
  ip?: string;
  requestId?: string;
  duration?: number;
  [key: string]: unknown;
}
 
interface LogEntry {
  timestamp: string;
  level: LogLevel;
  category: LogCategory;
  message: string;
  error?: Error | unknown;
  context?: LogContext;
}
 
const isDev = process.env.NODE_ENV === 'development';
const isLoggingEnabled = process.env.ENABLE_LOGGING !== 'false';
const LOG_TO_FILE = process.env.LOG_TO_FILE === 'true';
const LOG_TO_DB = process.env.LOG_TO_DB !== 'false'; // Default true in production
 
// Generate fingerprint for error grouping
function generateFingerprint(category: string, message: string, stack?: string): string {
  const content = `${category}:${message}:${stack?.split('\n')[1] || ''}`;
  return crypto.createHash('md5').update(content).digest('hex');
}
 
// Format log for console/file output
function formatLog(entry: LogEntry): string {
  const { timestamp, level, category, message, context } = entry;
  const prefix = `[${timestamp}] ${level.toUpperCase()} [${category}]`;
 
  let output = `${prefix} ${message}`;
 
  if (context) {
    const extras = Object.entries(context)
      .filter(([, v]) => v !== undefined)
      .map(([k, v]) => `${k}=${typeof v === 'object' ? JSON.stringify(v) : v}`)
      .join(' ');
    if (extras) output += ` | ${extras}`;
  }
 
  return output;
}
 
// Write to file (async, non-blocking)
async function writeToFile(entry: LogEntry): Promise<void> {
  if (!LOG_TO_FILE) return;

  try {
    const fs = await import('fs/promises');
    const path = await import('path');

    const logDir = path.join(process.cwd(), 'logs');
    const date = new Date().toISOString().split('T')[0];
    const filename = `${entry.level === 'error' ? 'error' : 'app'}-${date}.log`;
    const filepath = path.join(logDir, filename);
 
    // Ensure log directory exists
    await fs.mkdir(logDir, { recursive: true });

    const logLine = JSON.stringify({
      ...entry,
      error: entry.error instanceof Error ? {
        name: entry.error.name,
        message: entry.error.message,
        stack: entry.error.stack} : entry.error}) + '\n';
 
    await fs.appendFile(filepath, logLine);
  } catch (err) {
    console.error('Failed to write to log file:', err);
  }
}
 
// Write to database (async, non-blocking)
async function writeToDatabase(entry: LogEntry): Promise<void> {
  if (!LOG_TO_DB || isDev) return;
  if (entry.level === 'debug' || entry.level === 'info') return; // Only store warn/error
  // Skip database writes during CI builds (no database available)
  if (process.env.CI === "true") return;
 
  try {
    const fingerprint = generateFingerprint(
      entry.category,
      entry.message,
      entry.error instanceof Error ? entry.error.stack : undefined
    );
    // Create error log entry
    await prisma.errorLog.create({
      data: {
        fingerprint,
        level: entry.level,
        category: entry.category,
        message: entry.message,
        stack: entry.error instanceof Error ? entry.error.stack : undefined,
        url: entry.context?.url,
        method: entry.context?.method,
        statusCode: entry.context?.statusCode,
        userId: entry.context?.userId,
        userEmail: entry.context?.userEmail,
        userAgent: entry.context?.userAgent,
        ip: entry.context?.ip,
        requestId: entry.context?.requestId,
        metadata: entry.context ? JSON.parse(JSON.stringify(entry.context)) : undefined}});
    // Update or create error statistics
    await prisma.errorStatistic.upsert({
      where: { fingerprint },
      update: {
        count: { increment: 1 },
        lastSeen: new Date()},
      create: {
        fingerprint,
        category: entry.category,
        message: entry.message.substring(0, 500),
        count: 1,
        firstSeen: new Date(),
        lastSeen: new Date()}});
  } catch (err) {
    console.error('Failed to write to database:', err);
  }
}
 
// Import alert function lazily to avoid circular dependencies
let sendErrorAlertEmail: ((data: LogEntry) => Promise<void>) | null = null;
 
async function getAlertFunction() {
  if (!sendErrorAlertEmail) {
    try {
      const alerts = await import('@/lib/monitoring/alerts');
      sendErrorAlertEmail = alerts.sendErrorAlertEmail;
    } catch {
      // Alerts module not available yet
      sendErrorAlertEmail = async () => { };
    }
  }
  return sendErrorAlertEmail;
}
 
// Main logger object
export const monitoringLogger = {
  debug(category: LogCategory, message: string, context?: LogContext) {
    if (!isDev) return;

    const entry: LogEntry = {
      timestamp: new Date().toISOString(),
      level: 'debug',
      category,
      message,
      context};

    console.debug(formatLog(entry));
  },
 
  info(category: LogCategory, message: string, context?: LogContext) {
    if (!isLoggingEnabled) return;
 
    const entry: LogEntry = {
      timestamp: new Date().toISOString(),
      level: 'info',
      category,
      message,
      context};
 
    console.log(formatLog(entry));
    writeToFile(entry).catch(() => { });
  },
 
  warn(category: LogCategory, message: string, context?: LogContext) {
    const entry: LogEntry = {
      timestamp: new Date().toISOString(),
      level: 'warn',
      category,
      message,
      context};
 
    console.warn(formatLog(entry));
    writeToFile(entry).catch(() => { });
    writeToDatabase(entry).catch(() => { });
  },
 
  async error(category: LogCategory, message: string, error?: unknown, context?: LogContext) {
    const entry: LogEntry = {
      timestamp: new Date().toISOString(),
      level: 'error',
      category,
      message,
      error,
      context: {
        ...context,
        errorMessage: error instanceof Error ? error.message : String(error)}};
 
    console.error(formatLog(entry));
    if (error instanceof Error && error.stack) {
      console.error(error.stack);
    }
 
    writeToFile(entry).catch(() => { });
    writeToDatabase(entry).catch(() => { });
 
    // Send email alert for critical errors
    if (context?.statusCode === 500 || category === 'DATABASE' || category === 'PAYMENT') {
      const alertFn = await getAlertFunction();
      alertFn(entry).catch(() => { });
    }
  },
 
  // Performance timing helper
  time(category: LogCategory, label: string): () => void {
    const start = performance.now();
 
    return () => {
      const duration = performance.now() - start;
      this.info(category, `${label} completed`, { duration: Number(duration.toFixed(2)) });
 
      if (duration > 1000) {
        this.warn(category, `Slow operation: ${label}`, { duration: Number(duration.toFixed(2)) });
      }
    };
  }};
 
export default monitoringLogger;