This repository was archived by the owner on May 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathlogging.ts
More file actions
287 lines (240 loc) · 8.07 KB
/
Copy pathlogging.ts
File metadata and controls
287 lines (240 loc) · 8.07 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import type { Logger as WinstonLogger } from 'winston'
import fs from 'node:fs'
import path from 'node:path'
import { createLogger, format, transports } from 'winston'
const { combine, timestamp, label, printf, colorize, splat } = format
export type LogLevel = 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly'
interface LoggerOptions {
level?: LogLevel
console?: boolean
file?: string
format?: 'minimal' | 'detailed' | 'emoji'
}
const DEFAULT_LOGGER_NAME = 'mcp-use'
// Environment detection function (similar to telemetry)
function isNodeJSEnvironment(): boolean {
try {
// Check for Cloudflare Workers specifically
if (typeof navigator !== 'undefined' && navigator.userAgent?.includes('Cloudflare-Workers')) {
return false
}
// Check for other edge runtime indicators
if (typeof (globalThis as any).EdgeRuntime !== 'undefined' || typeof (globalThis as any).Deno !== 'undefined') {
return false
}
// Check for Node.js specific globals that are not available in edge environments
const hasNodeGlobals = (
typeof process !== 'undefined'
&& typeof process.platform !== 'undefined'
&& typeof __dirname !== 'undefined'
)
// Check for Node.js modules
const hasNodeModules = (
typeof fs !== 'undefined'
&& typeof createLogger === 'function'
)
return hasNodeGlobals && hasNodeModules
}
catch {
return false
}
}
// Simple console logger for non-Node.js environments
class SimpleConsoleLogger {
private _level: LogLevel
private name: string
constructor(name: string = DEFAULT_LOGGER_NAME, level: LogLevel = 'info') {
this.name = name
this._level = level
}
private shouldLog(level: LogLevel): boolean {
const levels = ['error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly']
const currentIndex = levels.indexOf(this._level)
const messageIndex = levels.indexOf(level)
return messageIndex <= currentIndex
}
private formatMessage(level: LogLevel, message: string): string {
const timestamp = new Date().toLocaleTimeString('en-US', { hour12: false })
return `${timestamp} [${this.name}] ${level}: ${message}`
}
error(message: string): void {
if (this.shouldLog('error')) {
console.error(this.formatMessage('error', message))
}
}
warn(message: string): void {
if (this.shouldLog('warn')) {
console.warn(this.formatMessage('warn', message))
}
}
info(message: string): void {
if (this.shouldLog('info')) {
console.info(this.formatMessage('info', message)) // eslint-disable-line no-console
}
}
debug(message: string): void {
if (this.shouldLog('debug')) {
console.debug(this.formatMessage('debug', message)) // eslint-disable-line no-console
}
}
http(message: string): void {
if (this.shouldLog('http')) {
console.log(this.formatMessage('http', message)) // eslint-disable-line no-console
}
}
verbose(message: string): void {
if (this.shouldLog('verbose')) {
console.log(this.formatMessage('verbose', message)) // eslint-disable-line no-console
}
}
silly(message: string): void {
if (this.shouldLog('silly')) {
console.log(this.formatMessage('silly', message)) // eslint-disable-line no-console
}
}
// Make it compatible with Winston interface
get level(): LogLevel {
return this._level
}
set level(newLevel: LogLevel) {
this._level = newLevel
}
}
function resolveLevel(env: string | undefined): LogLevel {
// Safely access environment variables
const envValue = (typeof process !== 'undefined' && process.env) ? env : undefined
switch (envValue?.trim()) {
case '2':
return 'debug'
case '1':
return 'info'
default:
return 'info'
}
}
const minimalFormatter = printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`
})
const detailedFormatter = printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`
})
const emojiFormatter = printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`
})
export class Logger {
private static instances: Record<string, WinstonLogger | SimpleConsoleLogger> = {}
private static simpleInstances: Record<string, SimpleConsoleLogger> = {}
private static currentFormat: 'minimal' | 'detailed' | 'emoji' = 'minimal'
public static get(name: string = DEFAULT_LOGGER_NAME): WinstonLogger | SimpleConsoleLogger {
// Use simple console logger in non-Node.js environments
if (!isNodeJSEnvironment()) {
if (!this.simpleInstances[name]) {
const debugEnv = (typeof process !== 'undefined' && process.env?.DEBUG) || undefined
this.simpleInstances[name] = new SimpleConsoleLogger(name, resolveLevel(debugEnv))
}
return this.simpleInstances[name]
}
// Use Winston logger in Node.js environments
if (!this.instances[name]) {
this.instances[name] = createLogger({
level: resolveLevel(process.env.DEBUG),
format: combine(
colorize(),
splat(),
label({ label: name }),
timestamp({ format: 'HH:mm:ss' }),
this.getFormatter(),
),
transports: [],
})
}
return this.instances[name]
}
private static getFormatter() {
switch (this.currentFormat) {
case 'minimal':
return minimalFormatter
case 'detailed':
return detailedFormatter
case 'emoji':
return emojiFormatter
default:
return minimalFormatter
}
}
public static configure(options: LoggerOptions = {}): void {
const { level, console = true, file, format = 'minimal' } = options
const debugEnv = (typeof process !== 'undefined' && process.env?.DEBUG) || undefined
const resolvedLevel = level ?? resolveLevel(debugEnv)
this.currentFormat = format
const root = this.get()
root.level = resolvedLevel
// For non-Node.js environments, just update the level
if (!isNodeJSEnvironment()) {
Object.values(this.simpleInstances).forEach((logger) => {
logger.level = resolvedLevel
})
return
}
// Winston-specific configuration for Node.js environments
const winstonRoot = root as WinstonLogger
winstonRoot.clear()
if (console) {
winstonRoot.add(new transports.Console())
}
if (file) {
const dir = path.dirname(path.resolve(file))
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
winstonRoot.add(new transports.File({ filename: file }))
}
// Update all existing Winston loggers with new format
Object.values(this.instances).forEach((logger) => {
if (logger && 'format' in logger) {
logger.level = resolvedLevel
;(logger as WinstonLogger).format = combine(
colorize(),
splat(),
label({ label: DEFAULT_LOGGER_NAME }),
timestamp({ format: 'HH:mm:ss' }),
this.getFormatter(),
)
}
})
}
public static setDebug(enabled: boolean | 0 | 1 | 2): void {
let level: LogLevel
if (enabled === 2 || enabled === true)
level = 'debug'
else if (enabled === 1)
level = 'info'
else level = 'info'
// Update both simple and Winston loggers
Object.values(this.simpleInstances).forEach((logger) => {
logger.level = level
})
Object.values(this.instances).forEach((logger) => {
if (logger) {
logger.level = level
}
})
// Safely set environment variable
if (typeof process !== 'undefined' && process.env) {
process.env.DEBUG = enabled ? (enabled === true ? '2' : String(enabled)) : '0'
}
}
public static setFormat(format: 'minimal' | 'detailed' | 'emoji'): void {
this.currentFormat = format
this.configure({ format })
}
}
// Only configure Winston features if in Node.js environment
if (isNodeJSEnvironment()) {
Logger.configure()
}
else {
// For non-Node.js environments, just initialize with defaults
Logger.configure({ console: true })
}
export const logger = Logger.get()