File size: 4,510 Bytes
d0ded63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Structured logging module for enhanced observability
 * Logs with severity levels, component tracking, and metrics
 */

type LogLevel = 'debug' | 'info' | 'warn' | 'error';

interface LogEntry {
  timestamp: string;
  level: LogLevel;
  component: string;
  message: string;
  duration?: number; // milliseconds
  error?: string;
  metadata?: Record<string, unknown>;
}

class Logger {
  private isProduction = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';

  /**
   * Log a message with timestamp and component context
   */
  private log(level: LogLevel, component: string, message: string, metadata?: Record<string, unknown>) {
    const entry: LogEntry = {
      timestamp: new Date().toISOString(),
      level,
      component,
      message,
      metadata,
    };

    const prefix = `[${component}]`;
    const formattedMessage = `${prefix} ${message}`;

    const logWithMetadata = (consoleFn: typeof console.error) => {
      if (metadata && Object.keys(metadata).length > 0) {
        consoleFn(formattedMessage, metadata);
      } else {
        consoleFn(formattedMessage);
      }
    };

    switch (level) {
      case 'error':
        logWithMetadata(console.error);
        break;
      case 'warn':
        logWithMetadata(console.warn);
        break;
      case 'info':
        if (!this.isProduction) {
          logWithMetadata(console.log);
        }
        break;
      case 'debug':
        if (!this.isProduction) {
          logWithMetadata(console.debug);
        }
        break;
    }
  }

  /**
   * Log debug message (development only)
   */
  debug(component: string, message: string, metadata?: Record<string, unknown>) {
    this.log('debug', component, message, metadata);
  }

  /**
   * Log info message
   */
  info(component: string, message: string, metadata?: Record<string, unknown>) {
    this.log('info', component, message, metadata);
  }

  /**
   * Log warning message
   */
  warn(component: string, message: string, metadata?: Record<string, unknown>) {
    this.log('warn', component, message, metadata);
  }

  /**
   * Log error with optional error object
   */
  error(component: string, message: string, error?: Error | unknown, metadata?: Record<string, unknown>) {
    const errorMetadata = {
      ...metadata,
      ...(error instanceof Error && {
        errorMessage: error.message,
        errorStack: error.stack,
      }),
    };
    this.log('error', component, message, errorMetadata);
  }

  /**
   * Measure performance of an async function and log duration
   */
  async measureAsync<T>(
    component: string,
    operationName: string,
    fn: () => Promise<T>,
  ): Promise<T> {
    const start = performance.now();
    try {
      const result = await fn();
      const duration = performance.now() - start;
      this.debug(component, `${operationName} completed`, { duration: `${duration.toFixed(2)}ms` });
      return result;
    } catch (error) {
      const duration = performance.now() - start;
      this.error(component, `${operationName} failed`, error, { duration: `${duration.toFixed(2)}ms` });
      throw error;
    }
  }

  /**
   * Measure performance of a sync function and log duration
   */
  measureSync<T>(
    component: string,
    operationName: string,
    fn: () => T,
  ): T {
    const start = performance.now();
    try {
      const result = fn();
      const duration = performance.now() - start;
      this.debug(component, `${operationName} completed`, { duration: `${duration.toFixed(2)}ms` });
      return result;
    } catch (error) {
      const duration = performance.now() - start;
      this.error(component, `${operationName} failed`, error, { duration: `${duration.toFixed(2)}ms` });
      throw error;
    }
  }
}

// Export singleton instance
export const logger = new Logger();

/**
 * Helper for tracking async operation metrics
 */
export function createAsyncMetricsTracker(component: string, operationName: string) {
  const start = performance.now();
  return {
    success: (metadata?: Record<string, unknown>) => {
      const duration = performance.now() - start;
      logger.info(component, `${operationName} succeeded`, { duration: `${duration.toFixed(2)}ms`, ...metadata });
    },
    error: (error: Error | unknown, metadata?: Record<string, unknown>) => {
      const duration = performance.now() - start;
      logger.error(component, `${operationName} failed`, error, { duration: `${duration.toFixed(2)}ms`, ...metadata });
    },
  };
}