File size: 4,884 Bytes
b91e262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import fs from 'fs'
import path from 'path'

export interface LogEntry {
  timestamp: string
  source: 'Server' | 'Browser'
  level: string
  message: string
}

// Logging server and browser logs to a file
export class FileLogger {
  private logFilePath: string = ''
  private isInitialized: boolean = false
  private logQueue: string[] = []
  private flushTimer: NodeJS.Timeout | null = null
  private mcpServerEnabled: boolean = false

  public initialize(distDir: string, mcpServerEnabled: boolean): void {
    this.logFilePath = path.join(distDir, 'logs', `next-development.log`)
    this.mcpServerEnabled = mcpServerEnabled

    if (this.isInitialized) {
      return
    }

    // Only initialize if mcpServer is enabled
    if (!this.mcpServerEnabled) {
      return
    }

    try {
      // Clean up the log file on each initialization
      // ensure the directory exists
      fs.mkdirSync(path.dirname(this.logFilePath), { recursive: true })
      fs.writeFileSync(this.logFilePath, '')
      this.isInitialized = true
    } catch (error) {
      console.error(error)
    }
  }

  private formatTimestamp(): string {
    // Use performance.now() instead of Date.now() for avoid sync IO of cache components
    const now = performance.now()
    const hours = Math.floor(now / 3600000)
      .toString()
      .padStart(2, '0')
    const minutes = Math.floor((now % 3600000) / 60000)
      .toString()
      .padStart(2, '0')
    const seconds = Math.floor((now % 60000) / 1000)
      .toString()
      .padStart(2, '0')
    const milliseconds = Math.floor(now % 1000)
      .toString()
      .padStart(3, '0')
    return `${hours}:${minutes}:${seconds}.${milliseconds}`
  }

  private formatLogEntry(entry: LogEntry): string {
    const { timestamp, source, level, message } = entry
    const levelPadded = level.toUpperCase().padEnd(7, ' ') // Pad level to 7 characters for alignment
    const sourcePadded = source === 'Browser' ? source : 'Server '
    return `[${timestamp}] ${sourcePadded} ${levelPadded} ${message}\n`
  }

  private scheduleFlush(): void {
    // Debounce the flush
    if (this.flushTimer) {
      clearTimeout(this.flushTimer)
      this.flushTimer = null
    }

    // Delay the log flush to ensure more logs can be batched together asynchronously
    this.flushTimer = setTimeout(() => {
      this.flush()
    }, 100)
  }

  public getLogQueue(): string[] {
    return this.logQueue
  }

  private flush(): void {
    if (this.logQueue.length === 0) {
      return
    }

    // Only flush to disk if mcpServer is enabled
    if (!this.mcpServerEnabled) {
      this.logQueue = [] // Clear the queue without writing
      this.flushTimer = null
      return
    }

    try {
      // Ensure the directory exists before writing
      const logDir = path.dirname(this.logFilePath)
      if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir, { recursive: true })
      }

      const logsToWrite = this.logQueue.join('')
      // Writing logs to files synchronously to ensure they're written before returning
      fs.appendFileSync(this.logFilePath, logsToWrite)
      this.logQueue = []
    } catch (error) {
      console.error('Failed to flush logs to file:', error)
    } finally {
      this.flushTimer = null
    }
  }

  private enqueueLog(formattedEntry: string): void {
    this.logQueue.push(formattedEntry)

    // Cancel existing timer and start a new one to ensure all logs are flushed together
    if (this.flushTimer) {
      clearTimeout(this.flushTimer)
      this.flushTimer = null
    }

    this.scheduleFlush()
  }

  log(source: 'Server' | 'Browser', level: string, message: string): void {
    // Don't log anything if mcpServer is disabled
    if (!this.mcpServerEnabled) {
      return
    }

    if (!this.isInitialized) {
      return
    }

    const logEntry: LogEntry = {
      timestamp: this.formatTimestamp(),
      source,
      level,
      message,
    }

    const formattedEntry = this.formatLogEntry(logEntry)
    this.enqueueLog(formattedEntry)
  }

  logServer(level: string, message: string): void {
    this.log('Server', level, message)
  }

  logBrowser(level: string, message: string): void {
    this.log('Browser', level, message)
  }

  // Force flush all queued logs immediately
  forceFlush(): void {
    if (this.flushTimer) {
      clearTimeout(this.flushTimer)
      this.flushTimer = null
    }
    this.flush()
  }

  // Cleanup method to flush logs on process exit
  destroy(): void {
    this.forceFlush()
  }
}

// Singleton instance
let fileLogger: FileLogger | null = null

export function getFileLogger(): FileLogger {
  if (!fileLogger || process.env.NODE_ENV === 'test') {
    fileLogger = new FileLogger()
  }
  return fileLogger
}

// Only used for testing
export function test__resetFileLogger(): void {
  if (fileLogger) {
    fileLogger.destroy()
  }
  fileLogger = null
}