feat(logging): emit sanitized structured app logs
This commit is contained in:
@@ -2,7 +2,6 @@ import winston from 'winston'
|
||||
|
||||
// Get the mocked winston from jest setup
|
||||
const mockedWinston = winston as jest.Mocked<typeof winston>
|
||||
const mockedLokiTransport = require('winston-loki') as jest.MockedFunction<any>
|
||||
|
||||
describe('Logger', () => {
|
||||
beforeEach(() => {
|
||||
@@ -10,10 +9,7 @@ describe('Logger', () => {
|
||||
// Reset process.env
|
||||
process.env = {
|
||||
...process.env,
|
||||
NODE_ENV: 'test',
|
||||
LOKI_HOST: undefined,
|
||||
LOKI_USERNAME: undefined,
|
||||
LOKI_PASSWORD: undefined
|
||||
NODE_ENV: 'test'
|
||||
}
|
||||
})
|
||||
|
||||
@@ -34,6 +30,7 @@ describe('Logger', () => {
|
||||
level: 'debug',
|
||||
format: 'combined-format',
|
||||
defaultMeta: expect.objectContaining({
|
||||
component: 'application',
|
||||
service: 'mozdit-web',
|
||||
environment: 'development'
|
||||
}),
|
||||
@@ -44,10 +41,73 @@ describe('Logger', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it.skip('should include Loki transport when LOKI_HOST is provided', () => {
|
||||
// This test is complex to implement due to module loading order with mocks
|
||||
// The Loki transport functionality is tested in integration tests
|
||||
// Skipping for now as core logger functionality is verified by other tests
|
||||
it('should use structured console logging in production', () => {
|
||||
;(process.env as unknown as Record<string, string>).NODE_ENV = 'production'
|
||||
|
||||
require('./logger')
|
||||
const activeWinston = require('winston') as jest.Mocked<typeof winston>
|
||||
|
||||
expect(activeWinston.createLogger).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: 'info',
|
||||
defaultMeta: expect.objectContaining({
|
||||
service: 'mozdit-web',
|
||||
environment: 'production'
|
||||
}),
|
||||
transports: [expect.objectContaining({ name: 'console' })]
|
||||
})
|
||||
)
|
||||
expect(activeWinston.format.json).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should keep development console output readable', () => {
|
||||
;(process.env as unknown as Record<string, string>).NODE_ENV = 'development'
|
||||
|
||||
require('./logger')
|
||||
const activeWinston = require('winston') as jest.Mocked<typeof winston>
|
||||
|
||||
expect(activeWinston.transports.Console).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: 'debug',
|
||||
format: 'combined-format',
|
||||
handleExceptions: true,
|
||||
handleRejections: true
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('should omit error messages and stacks from safe error details', () => {
|
||||
const { getSafeErrorDetails } = require('./logger')
|
||||
const sensitiveError = new Error('failed for alice@example.com with password=private')
|
||||
sensitiveError.stack = `${sensitiveError.stack}\nrequest body: private contact message`
|
||||
|
||||
const details = getSafeErrorDetails(sensitiveError)
|
||||
|
||||
expect(details).toEqual({ errorName: 'Error' })
|
||||
expect(JSON.stringify(details)).not.toContain('alice@example.com')
|
||||
expect(JSON.stringify(details)).not.toContain('private')
|
||||
})
|
||||
|
||||
it('should omit sensitive fields from timing metadata', async () => {
|
||||
const { withTiming, logger } = require('./logger')
|
||||
const operation = jest.fn().mockResolvedValue('success')
|
||||
|
||||
await withTiming('contact-persist', operation, {
|
||||
requestId: 'request-123',
|
||||
email: 'alice@example.com',
|
||||
message: 'private contact message'
|
||||
})
|
||||
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.stringContaining('Started contact-persist'),
|
||||
{ requestId: 'request-123' }
|
||||
)
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.stringContaining('Completed contact-persist'),
|
||||
expect.objectContaining({ requestId: 'request-123', duration: expect.any(Number) })
|
||||
)
|
||||
})
|
||||
|
||||
it('should create component loggers with correct metadata', () => {
|
||||
@@ -78,19 +138,19 @@ describe('Logger', () => {
|
||||
const { withTiming, logger } = require('./logger')
|
||||
const mockOperation = jest.fn().mockResolvedValue('success')
|
||||
|
||||
const result = await withTiming('test-operation', mockOperation, { test: 'metadata' })
|
||||
const result = await withTiming('test-operation', mockOperation, { requestId: '1234567890-abcdef12' })
|
||||
|
||||
expect(result).toBe('success')
|
||||
expect(logger.debug).toHaveBeenCalledTimes(2) // Start and complete
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(1,
|
||||
expect.stringContaining('Started test-operation'),
|
||||
{ test: 'metadata' }
|
||||
{ requestId: '1234567890-abcdef12' }
|
||||
)
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(2,
|
||||
expect.stringContaining('Completed test-operation'),
|
||||
expect.objectContaining({
|
||||
duration: expect.any(Number),
|
||||
test: 'metadata'
|
||||
requestId: '1234567890-abcdef12'
|
||||
})
|
||||
)
|
||||
})
|
||||
@@ -109,8 +169,23 @@ describe('Logger', () => {
|
||||
expect.stringContaining('Failed test-operation'),
|
||||
expect.objectContaining({
|
||||
duration: expect.any(Number),
|
||||
error: expect.any(Error)
|
||||
errorName: 'Error'
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('should allow only safe diagnostic metadata fields', () => {
|
||||
const { sanitizeLogMetadata } = require('./logger')
|
||||
|
||||
expect(sanitizeLogMetadata({
|
||||
requestId: '1234567890-abcdef12',
|
||||
duration: 42,
|
||||
email: 'alice@example.com',
|
||||
message: 'private contact message',
|
||||
custom: 'user supplied'
|
||||
})).toEqual({
|
||||
requestId: '1234567890-abcdef12',
|
||||
duration: 42
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+62
-27
@@ -1,5 +1,4 @@
|
||||
import winston from 'winston'
|
||||
import LokiTransport from 'winston-loki'
|
||||
import { randomUUID } from 'crypto'
|
||||
|
||||
const isDevelopment = process.env.NODE_ENV === 'development'
|
||||
@@ -28,29 +27,8 @@ const consoleFormat = winston.format.combine(
|
||||
})
|
||||
)
|
||||
|
||||
// Transports configuration
|
||||
// Application logs stay on stdout/stderr; a host-level collector owns forwarding.
|
||||
const transports: winston.transport[] = [
|
||||
// Loki transport for centralized logging
|
||||
...(process.env.LOKI_HOST
|
||||
? [
|
||||
new LokiTransport({
|
||||
host: process.env.LOKI_HOST,
|
||||
labels: {
|
||||
app: 'mozdit-web',
|
||||
environment: process.env.NODE_ENV || 'development',
|
||||
service: 'frontend'
|
||||
},
|
||||
basicAuth: process.env.LOKI_USERNAME && process.env.LOKI_PASSWORD
|
||||
? `${process.env.LOKI_USERNAME}:${process.env.LOKI_PASSWORD}`
|
||||
: undefined,
|
||||
json: true,
|
||||
format: winston.format.json(),
|
||||
onConnectionError: (err: Error) => console.error('Loki connection error:', err)
|
||||
})
|
||||
]
|
||||
: []),
|
||||
|
||||
// Console for development logging
|
||||
new winston.transports.Console({
|
||||
level: isDevelopment ? 'debug' : 'info',
|
||||
format: isDevelopment ? consoleFormat : structuredFormat,
|
||||
@@ -64,6 +42,7 @@ export const logger = winston.createLogger({
|
||||
level: isDevelopment ? 'debug' : 'info',
|
||||
format: structuredFormat,
|
||||
defaultMeta: {
|
||||
component: 'application',
|
||||
service: 'mozdit-web',
|
||||
version: process.env.DEPLOY_VERSION || process.env.npm_package_version || '1.0.0',
|
||||
environment: process.env.NODE_ENV || 'development'
|
||||
@@ -84,6 +63,56 @@ export const dbLogger = logger.child({ component: 'database' })
|
||||
export const authLogger = logger.child({ component: 'auth' })
|
||||
export const errorLogger = logger.child({ component: 'error' })
|
||||
|
||||
const SAFE_ERROR_IDENTIFIER = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/
|
||||
const SAFE_ERROR_CODE = /^[A-Za-z0-9_-]{1,64}$/
|
||||
const SAFE_LOG_LABEL = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/
|
||||
const SAFE_LOG_FIELDS = new Set([
|
||||
'component',
|
||||
'duration',
|
||||
'environment',
|
||||
'errorCode',
|
||||
'errorName',
|
||||
'operation',
|
||||
'requestId',
|
||||
'service',
|
||||
'version'
|
||||
])
|
||||
|
||||
export function getSafeErrorDetails(error: unknown): Record<string, string | number> {
|
||||
const details: Record<string, string | number> = {
|
||||
errorName: error instanceof Error && SAFE_ERROR_IDENTIFIER.test(error.name)
|
||||
? error.name
|
||||
: 'Error'
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && 'code' in error) {
|
||||
const code = error.code
|
||||
if (typeof code === 'number' && Number.isFinite(code)) details.errorCode = code
|
||||
if (typeof code === 'string' && SAFE_ERROR_CODE.test(code)) details.errorCode = code
|
||||
}
|
||||
|
||||
return details
|
||||
}
|
||||
|
||||
export function sanitizeLogMetadata(metadata: Record<string, unknown>): Record<string, unknown> {
|
||||
const safeMetadata: Record<string, unknown> = {}
|
||||
|
||||
for (const [key, value] of Object.entries(metadata)) {
|
||||
if (!SAFE_LOG_FIELDS.has(key)) continue
|
||||
if (key === 'duration' && typeof value === 'number' && Number.isFinite(value)) {
|
||||
safeMetadata[key] = value
|
||||
continue
|
||||
}
|
||||
if (key === 'errorCode' && typeof value === 'number' && Number.isFinite(value)) {
|
||||
safeMetadata[key] = value
|
||||
continue
|
||||
}
|
||||
if (typeof value === 'string' && SAFE_LOG_LABEL.test(value)) safeMetadata[key] = value
|
||||
}
|
||||
|
||||
return safeMetadata
|
||||
}
|
||||
|
||||
// Request ID generator for correlation
|
||||
export const generateRequestId = (): string =>
|
||||
`${Date.now()}-${randomUUID().slice(0, 8)}`
|
||||
@@ -95,16 +124,22 @@ export const withTiming = async <T>(
|
||||
metadata: Record<string, unknown> = {}
|
||||
): Promise<T> => {
|
||||
const startTime = Date.now()
|
||||
logger.debug(`Started ${operation}`, metadata)
|
||||
const safeOperation = SAFE_LOG_LABEL.test(operation) ? operation : 'operation'
|
||||
const safeMetadata = sanitizeLogMetadata(metadata)
|
||||
logger.debug(`Started ${safeOperation}`, safeMetadata)
|
||||
|
||||
try {
|
||||
const result = await fn()
|
||||
const duration = Date.now() - startTime
|
||||
logger.debug(`Completed ${operation} in ${duration}ms`, { ...metadata, duration })
|
||||
logger.debug(`Completed ${safeOperation} in ${duration}ms`, { ...safeMetadata, duration })
|
||||
return result
|
||||
} catch (error) {
|
||||
const duration = Date.now() - startTime
|
||||
logger.error(`Failed ${operation} in ${duration}ms`, { ...metadata, duration, error })
|
||||
logger.error(`Failed ${safeOperation} in ${duration}ms`, {
|
||||
...safeMetadata,
|
||||
...getSafeErrorDetails(error),
|
||||
duration
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -118,4 +153,4 @@ const gracefulShutdown = () => {
|
||||
process.on('SIGTERM', gracefulShutdown)
|
||||
process.on('SIGINT', gracefulShutdown)
|
||||
|
||||
export default logger
|
||||
export default logger
|
||||
|
||||
@@ -17,6 +17,15 @@ const mockClient = {
|
||||
db: jest.fn().mockReturnValue(mockDb)
|
||||
}
|
||||
|
||||
const mockMongoLoggerError = jest.fn()
|
||||
|
||||
jest.mock('./logger', () => ({
|
||||
dbLogger: { error: mockMongoLoggerError },
|
||||
getSafeErrorDetails: (error: unknown) => ({
|
||||
errorName: error instanceof Error ? error.name : 'Error'
|
||||
})
|
||||
}))
|
||||
|
||||
// The connect method should resolve to the client itself
|
||||
mockClient.connect.mockResolvedValue(mockClient)
|
||||
|
||||
@@ -39,6 +48,7 @@ describe('MongoDB Connection (Unit Tests)', () => {
|
||||
MONGODB_DB: 'test'
|
||||
}
|
||||
jest.clearAllMocks()
|
||||
mockMongoLoggerError.mockReset()
|
||||
|
||||
// Reset the mock implementation
|
||||
MockedMongoClient.mockImplementation(() => mockClient as any)
|
||||
@@ -116,6 +126,7 @@ describe('MongoDB Connection (Unit Tests)', () => {
|
||||
|
||||
const result = await checkMongoConnection()
|
||||
expect(result).toBe(false)
|
||||
expect(mockMongoLoggerError).toHaveBeenCalledWith('MongoDB connection check failed', { errorName: 'Error' })
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MongoClient, Db } from 'mongodb'
|
||||
import { dbLogger, getSafeErrorDetails } from './logger'
|
||||
|
||||
// WHY this file only exposes getDb/checkMongoConnection now: it used to also
|
||||
// export getCollection(), used by src/app/api/contact/route.ts for a raw,
|
||||
@@ -63,7 +64,7 @@ export async function checkMongoConnection(): Promise<boolean> {
|
||||
await db.admin().ping()
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('MongoDB connection check failed:', error)
|
||||
dbLogger.error('MongoDB connection check failed', getSafeErrorDetails(error))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user