File size: 1,987 Bytes
1b44660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Define the basic structure for your logs
interface LogEntry {
  level: 'debug' | 'info' | 'warn' | 'error';
  message: string;
  timestamp: string;
  context?: Record<string, unknown>;
  error?: {
    message: string;
    stack?: string;
    cause?: unknown;
  };
}

// Basic logger class
export class Logger {
  private baseContext: Record<string, unknown>;

  constructor(baseContext: Record<string, unknown> = {}) {
    // Clone the context to prevent mutation issues if the source object changes
    this.baseContext = { ...baseContext };
  }

  // Method to create a "child" logger with additional context
  child(additionalContext: Record<string, unknown>): Logger {
    return new Logger({ ...this.baseContext, ...additionalContext });
  }

  // Central logging function
  private log(level: LogEntry['level'], message: string, context?: Record<string, unknown>, error?: Error) {
    const entry: LogEntry = {
      level,
      message,
      timestamp: new Date().toISOString(),
      // Merge base context, method-specific context
      context: { ...this.baseContext, ...context },
    };

    if (error) {
      entry.error = {
        message: error.message,
        stack: error.stack,
        // Include cause if available
        ...(error.cause ? { cause: error.cause } : {}),
      };
    }

    // The core idea: output structured JSON via console.log
    // Logpush / Tail Workers will pick this up.
    console.log(JSON.stringify(entry));
  }

  // Convenience methods for different levels
  debug(message: string, context?: Record<string, unknown>) {
    this.log('debug', message, context);
  }

  info(message: string, context?: Record<string, unknown>) {
    this.log('info', message, context);
  }

  warn(message: string, context?: Record<string, unknown>, error?: Error) {
    this.log('warn', message, context, error);
  }

  error(message: string, context?: Record<string, unknown>, error?: Error) {
    this.log('error', message, context, error);
  }
}