-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.ts
More file actions
159 lines (137 loc) · 4.03 KB
/
logger.ts
File metadata and controls
159 lines (137 loc) · 4.03 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
import { NextRequest, NextResponse } from 'next/server'
/**
* ANSI color codes for console output
*/
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
gray: '\x1b[90m',
}
/**
* Get colored status code based on HTTP status
*/
function getColoredStatus(status: number): string {
let color = colors.gray
if (status >= 200 && status < 300) color = colors.green
else if (status >= 300 && status < 400) color = colors.yellow
else if (status >= 400 && status < 500) color = colors.red
else if (status >= 500) color = colors.red + colors.bright
return `${color}${status}${colors.reset}`
}
/**
* Get colored HTTP method
*/
function getColoredMethod(method: string): string {
const methodColors: Record<string, string> = {
GET: colors.green,
POST: colors.blue,
PUT: colors.yellow,
DELETE: colors.red,
PATCH: colors.magenta,
HEAD: colors.cyan,
OPTIONS: colors.gray,
}
const color = methodColors[method] || colors.white
return `${color}${method.padEnd(7)}${colors.reset}`
}
/**
* Format duration with appropriate color
*/
function getColoredDuration(ms: number): string {
let color = colors.green
if (ms > 1000) color = colors.red
else if (ms > 500) color = colors.yellow
else if (ms > 100) color = colors.cyan
return `${color}${ms.toFixed(0)}ms${colors.reset}`
}
/**
* Get client IP address from various headers
*/
function getClientIP(request: NextRequest): string {
const xForwardedFor = request.headers.get('x-forwarded-for')
const xRealIP = request.headers.get('x-real-ip')
const cfConnectingIP = request.headers.get('cf-connecting-ip')
if (xForwardedFor) {
return xForwardedFor.split(',')[0].trim()
}
if (xRealIP) return xRealIP
if (cfConnectingIP) return cfConnectingIP
return 'unknown'
}
/**
* Log API route request and response
*/
export function logAPIRoute(
request: NextRequest,
response: NextResponse,
startTime: number,
additionalInfo?: string
): void {
const endTime = Date.now()
const duration = endTime - startTime
const status = response.status
const method = request.method
const url = request.url
const clientIP = getClientIP(request)
const timestamp = new Date().toISOString()
// Main log line
console.log(
`${colors.gray}[${timestamp}]${colors.reset} ` +
`${getColoredMethod(method)} ` +
`${colors.cyan}${url}${colors.reset} ` +
`${getColoredStatus(status)} ` +
`${getColoredDuration(duration)} ` +
`${colors.gray}from ${clientIP}${colors.reset}` +
(additionalInfo ? ` ${colors.dim}(${additionalInfo})${colors.reset}` : '')
)
}
/**
* Higher-order function to wrap API route handlers with logging
*/
export function withLogging<T extends any[]>(
handler: (request: NextRequest, ...args: T) => Promise<NextResponse>
) {
return async (request: NextRequest, ...args: T): Promise<NextResponse> => {
const startTime = Date.now()
try {
const response = await handler(request, ...args)
logAPIRoute(request, response, startTime)
return response
} catch (error) {
// Create error response
const errorResponse = NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
logAPIRoute(request, errorResponse, startTime, `Error: ${error}`)
throw error
}
}
}
/**
* Simple logger for general application logs
*/
export const logger = {
info: (message: string, ...args: any[]) => {
console.log(`${colors.blue}[INFO]${colors.reset} ${message}`, ...args)
},
warn: (message: string, ...args: any[]) => {
console.log(`${colors.yellow}[WARN]${colors.reset} ${message}`, ...args)
},
error: (message: string, ...args: any[]) => {
console.log(`${colors.red}[ERROR]${colors.reset} ${message}`, ...args)
},
success: (message: string, ...args: any[]) => {
console.log(`${colors.green}[SUCCESS]${colors.reset} ${message}`, ...args)
},
debug: (message: string, ...args: any[]) => {
if (process.env.NODE_ENV === 'development') {
console.log(`${colors.gray}[DEBUG]${colors.reset} ${message}`, ...args)
}
},
}