fix(logging): preserve component labels and ISO timestamps
CI Pipeline with Test Management / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
CI Pipeline with Test Management / 🐳 Docker Integration Tests (push) Canceled after 0s
CI Pipeline with Test Management / 🏗️ Build Docker Image (push) Canceled after 0s
CI Pipeline with Test Management / 📊 Generate Test Summary (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 📊 Analyze Test Coverage (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🔄 Sync with Linear (push) Canceled after 0s
Test Reporting & Gherkin Analysis / ⚡ Performance Monitoring (push) Canceled after 0s
CI Pipeline with Test Management / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
CI Pipeline with Test Management / 🐳 Docker Integration Tests (push) Canceled after 0s
CI Pipeline with Test Management / 🏗️ Build Docker Image (push) Canceled after 0s
CI Pipeline with Test Management / 📊 Generate Test Summary (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 📊 Analyze Test Coverage (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🔄 Sync with Linear (push) Canceled after 0s
Test Reporting & Gherkin Analysis / ⚡ Performance Monitoring (push) Canceled after 0s
This commit is contained in:
@@ -58,6 +58,7 @@ describe('Logger', () => {
|
||||
})
|
||||
)
|
||||
expect(activeWinston.format.json).toHaveBeenCalled()
|
||||
expect(activeWinston.format.timestamp).toHaveBeenCalledWith()
|
||||
})
|
||||
|
||||
it('should keep development console output readable', () => {
|
||||
@@ -101,24 +102,29 @@ describe('Logger', () => {
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.stringContaining('Started contact-persist'),
|
||||
{ requestId: 'request-123' }
|
||||
{ requestId: 'request-123', component: 'application' }
|
||||
)
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.stringContaining('Completed contact-persist'),
|
||||
expect.objectContaining({ requestId: 'request-123', duration: expect.any(Number) })
|
||||
expect.objectContaining({ requestId: 'request-123', component: 'application', duration: expect.any(Number) })
|
||||
)
|
||||
})
|
||||
|
||||
it('should create component loggers with correct metadata', () => {
|
||||
const { createComponentLogger, logger } = require('./logger')
|
||||
|
||||
// Clear the mock calls to avoid interference from logger creation
|
||||
const mockLogger = mockedWinston.createLogger()
|
||||
;(mockLogger.child as jest.Mock).mockClear()
|
||||
|
||||
|
||||
;(logger.error as jest.Mock).mockClear()
|
||||
const componentLogger = createComponentLogger('test-component')
|
||||
expect(logger.child).toHaveBeenCalledWith({ component: 'test-component' })
|
||||
componentLogger.error('safe error', {
|
||||
requestId: '1234567890-abcdef12',
|
||||
email: 'alice@example.com'
|
||||
})
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith('safe error', {
|
||||
requestId: '1234567890-abcdef12',
|
||||
component: 'test-component'
|
||||
})
|
||||
})
|
||||
|
||||
it('should generate request IDs in correct format', () => {
|
||||
@@ -144,13 +150,14 @@ describe('Logger', () => {
|
||||
expect(logger.debug).toHaveBeenCalledTimes(2) // Start and complete
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(1,
|
||||
expect.stringContaining('Started test-operation'),
|
||||
{ requestId: '1234567890-abcdef12' }
|
||||
{ requestId: '1234567890-abcdef12', component: 'application' }
|
||||
)
|
||||
expect(logger.debug).toHaveBeenNthCalledWith(2,
|
||||
expect.stringContaining('Completed test-operation'),
|
||||
expect.objectContaining({
|
||||
duration: expect.any(Number),
|
||||
requestId: '1234567890-abcdef12'
|
||||
requestId: '1234567890-abcdef12',
|
||||
component: 'application'
|
||||
})
|
||||
)
|
||||
})
|
||||
@@ -163,7 +170,7 @@ describe('Logger', () => {
|
||||
|
||||
expect(logger.debug).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Started test-operation'),
|
||||
{}
|
||||
{ component: 'application' }
|
||||
)
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Failed test-operation'),
|
||||
|
||||
+26
-16
@@ -5,7 +5,7 @@ const isDevelopment = process.env.NODE_ENV === 'development'
|
||||
|
||||
// Custom format for structured logging
|
||||
const structuredFormat = winston.format.combine(
|
||||
winston.format.timestamp({ format: 'ISO' }),
|
||||
winston.format.timestamp(),
|
||||
winston.format.errors({ stack: true }),
|
||||
winston.format.json({
|
||||
replacer: (_key, value) =>
|
||||
@@ -52,17 +52,6 @@ export const logger = winston.createLogger({
|
||||
rejectionHandlers: transports
|
||||
})
|
||||
|
||||
// Specialized loggers for different components
|
||||
export const createComponentLogger = (component: string) => {
|
||||
return logger.child({ component })
|
||||
}
|
||||
|
||||
export const requestLogger = logger.child({ component: 'request' })
|
||||
export const apiLogger = logger.child({ component: 'api' })
|
||||
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}$/
|
||||
@@ -113,6 +102,26 @@ export function sanitizeLogMetadata(metadata: Record<string, unknown>): Record<s
|
||||
return safeMetadata
|
||||
}
|
||||
|
||||
// Explicit metadata overrides root defaultMeta so component labels remain accurate.
|
||||
export const createComponentLogger = (component: string) => {
|
||||
const componentName = SAFE_LOG_LABEL.test(component) ? component : 'application'
|
||||
const write = (level: 'error' | 'warn' | 'info' | 'debug', message: string, metadata: Record<string, unknown> = {}) =>
|
||||
logger[level](message, { ...sanitizeLogMetadata(metadata), component: componentName })
|
||||
|
||||
return {
|
||||
error: (message: string, metadata?: Record<string, unknown>) => write('error', message, metadata),
|
||||
warn: (message: string, metadata?: Record<string, unknown>) => write('warn', message, metadata),
|
||||
info: (message: string, metadata?: Record<string, unknown>) => write('info', message, metadata),
|
||||
debug: (message: string, metadata?: Record<string, unknown>) => write('debug', message, metadata)
|
||||
}
|
||||
}
|
||||
|
||||
export const requestLogger = createComponentLogger('request')
|
||||
export const apiLogger = createComponentLogger('api')
|
||||
export const dbLogger = createComponentLogger('database')
|
||||
export const authLogger = createComponentLogger('auth')
|
||||
export const errorLogger = createComponentLogger('error')
|
||||
|
||||
// Request ID generator for correlation
|
||||
export const generateRequestId = (): string =>
|
||||
`${Date.now()}-${randomUUID().slice(0, 8)}`
|
||||
@@ -126,16 +135,17 @@ export const withTiming = async <T>(
|
||||
const startTime = Date.now()
|
||||
const safeOperation = SAFE_LOG_LABEL.test(operation) ? operation : 'operation'
|
||||
const safeMetadata = sanitizeLogMetadata(metadata)
|
||||
logger.debug(`Started ${safeOperation}`, safeMetadata)
|
||||
const timingLogger = createComponentLogger('application')
|
||||
timingLogger.debug(`Started ${safeOperation}`, safeMetadata)
|
||||
|
||||
try {
|
||||
const result = await fn()
|
||||
const duration = Date.now() - startTime
|
||||
logger.debug(`Completed ${safeOperation} in ${duration}ms`, { ...safeMetadata, duration })
|
||||
timingLogger.debug(`Completed ${safeOperation} in ${duration}ms`, { ...safeMetadata, duration })
|
||||
return result
|
||||
} catch (error) {
|
||||
const duration = Date.now() - startTime
|
||||
logger.error(`Failed ${safeOperation} in ${duration}ms`, {
|
||||
timingLogger.error(`Failed ${safeOperation} in ${duration}ms`, {
|
||||
...safeMetadata,
|
||||
...getSafeErrorDetails(error),
|
||||
duration
|
||||
@@ -146,7 +156,7 @@ export const withTiming = async <T>(
|
||||
|
||||
// Graceful shutdown
|
||||
const gracefulShutdown = () => {
|
||||
logger.info('Initiating graceful shutdown...')
|
||||
createComponentLogger('application').info('Initiating graceful shutdown...')
|
||||
logger.end()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user