feat(logging): emit sanitized structured app logs
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import config from '@payload-config'
|
||||
import { createComponentLogger, getSafeErrorDetails } from '@/lib/logger'
|
||||
|
||||
interface ContactFormData {
|
||||
name: string
|
||||
@@ -10,6 +11,8 @@ interface ContactFormData {
|
||||
gdprConsent: boolean
|
||||
}
|
||||
|
||||
const contactLogger = createComponentLogger('contact-api')
|
||||
|
||||
// Simple spam protection - rate limiting by IP
|
||||
const rateLimitMap = new Map<string, { count: number; timestamp: number }>()
|
||||
const RATE_LIMIT_WINDOW = 60 * 1000 // 1 minute
|
||||
@@ -138,7 +141,7 @@ export async function POST(request: NextRequest) {
|
||||
)
|
||||
|
||||
} catch (error) {
|
||||
console.error('Contact form error:', error)
|
||||
contactLogger.error('Contact form submission failed', getSafeErrorDetails(error))
|
||||
return NextResponse.json(
|
||||
{ error: 'Szerver hiba történt. Kérjük, próbálja újra később.' },
|
||||
{ status: 500 }
|
||||
|
||||
@@ -8,13 +8,22 @@ import { getPayload } from 'payload'
|
||||
const mockCreate = jest.fn()
|
||||
|
||||
// Mock the logger to avoid complex setup
|
||||
jest.mock('@/lib/logger', () => ({
|
||||
createComponentLogger: () => ({
|
||||
info: jest.fn(),
|
||||
error: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
})
|
||||
}))
|
||||
jest.mock('@/lib/logger', () => {
|
||||
const mockLoggerError = jest.fn()
|
||||
return {
|
||||
mockLoggerError,
|
||||
createComponentLogger: () => ({
|
||||
info: jest.fn(),
|
||||
error: mockLoggerError,
|
||||
warn: jest.fn(),
|
||||
}),
|
||||
getSafeErrorDetails: (error: unknown) => ({
|
||||
errorName: error instanceof Error ? error.name : 'Error'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const { mockLoggerError } = jest.requireMock('@/lib/logger')
|
||||
|
||||
// WHY mock the resolved relative path instead of the '@payload-config' alias:
|
||||
// next/jest's SWC transform rewrites the tsconfig path alias to a real
|
||||
@@ -34,6 +43,7 @@ jest.mock('payload', () => ({
|
||||
describe('/api/contact Unit Tests', () => {
|
||||
beforeEach(() => {
|
||||
mockCreate.mockReset()
|
||||
mockLoggerError.mockReset()
|
||||
;(getPayload as jest.Mock).mockClear()
|
||||
})
|
||||
|
||||
@@ -78,6 +88,12 @@ describe('/api/contact Unit Tests', () => {
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(1)
|
||||
expect(mockLoggerError).toHaveBeenCalledWith('Contact form submission failed', { errorName: 'Error' })
|
||||
const serializedLogs = JSON.stringify(mockLoggerError.mock.calls)
|
||||
expect(serializedLogs).not.toContain(validData.name)
|
||||
expect(serializedLogs).not.toContain(validData.email)
|
||||
expect(serializedLogs).not.toContain(validData.subject)
|
||||
expect(serializedLogs).not.toContain(validData.message)
|
||||
})
|
||||
|
||||
it('rejects an over-long message before persisting', async () => {
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
import { GET, HEAD } from './route'
|
||||
import { NextRequest } from 'next/server'
|
||||
|
||||
jest.mock('@/lib/logger', () => {
|
||||
const mockHealthLoggerError = jest.fn()
|
||||
return {
|
||||
mockHealthLoggerError,
|
||||
createComponentLogger: () => ({ error: mockHealthLoggerError }),
|
||||
getSafeErrorDetails: (error: unknown) => ({
|
||||
errorName: error instanceof Error ? error.name : 'Error'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const { mockHealthLoggerError } = jest.requireMock('@/lib/logger')
|
||||
|
||||
// Mock the process object for tests
|
||||
const mockProcess = {
|
||||
uptime: jest.fn().mockReturnValue(1234),
|
||||
@@ -13,6 +26,7 @@ const mockProcess = {
|
||||
const originalProcess = global.process
|
||||
beforeEach(() => {
|
||||
global.process = { ...originalProcess, ...mockProcess } as any
|
||||
mockHealthLoggerError.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -69,6 +83,7 @@ describe('/api/health', () => {
|
||||
expect(data.status).toBe('error')
|
||||
expect(data).toHaveProperty('timestamp')
|
||||
expect(data).toHaveProperty('message', 'Health check failed')
|
||||
expect(mockHealthLoggerError).toHaveBeenCalledWith('Health check failed', { errorName: 'Error' })
|
||||
|
||||
// Restore process.uptime
|
||||
global.process.uptime = originalUptime
|
||||
@@ -83,4 +98,4 @@ describe('/api/health', () => {
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-cache, no-store, must-revalidate')
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { createComponentLogger, getSafeErrorDetails } from '@/lib/logger'
|
||||
|
||||
const healthLogger = createComponentLogger('health-api')
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
@@ -23,7 +26,7 @@ export async function GET() {
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Health check error:', error);
|
||||
healthLogger.error('Health check failed', getSafeErrorDetails(error))
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'error',
|
||||
@@ -43,4 +46,4 @@ export async function HEAD() {
|
||||
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user