mirror_match/__tests__/lib/logger.test.ts
ilia efb6519ffe
All checks were successful
CI / skip-ci-check (pull_request) Successful in 1m23s
CI / lint-and-type-check (pull_request) Successful in 1m47s
CI / test (pull_request) Successful in 1m51s
CI / build (pull_request) Successful in 1m52s
CI / secret-scanning (pull_request) Successful in 1m25s
CI / dependency-scan (pull_request) Successful in 1m28s
CI / sast-scan (pull_request) Successful in 2m32s
CI / workflow-summary (pull_request) Successful in 1m22s
# Cleanup Checklist
This document lists code and features that were added during development/debugging that might be candidates for cleanup or removal in the future.

## Debug/Development Code

### 1. Verbose Logging in Production
**Location:** Multiple files
**Status:** Consider reducing in production

- `lib/auth.ts` - Session callback logging (lines 78-103, 105-113)
  - Logs full session details on every session creation
  - Could be reduced to warnings only or removed in production

- `app/photos/page.tsx` - Page render logging (lines 12-33)
  - Logs auth() calls and session details
  - Useful for debugging but verbose for production

- `app/api/debug/session/route.ts` - Entire debug endpoint
  - Created for debugging session issues
  - Consider removing or protecting with admin-only access
  - Or move to development-only route

### 2. Activity Logging
**Location:** `lib/activity-log.ts`, `proxy.ts`, API routes
**Status:** Keep but consider optimization

- Activity logging is useful for monitoring
- Consider:
  - Moving to structured logging (JSON format)
  - Adding log rotation/retention policies
  - Option to disable in production if not needed
  - Rate limiting logs to prevent spam

### 3. Upload Verification Logging
**Location:** `app/api/photos/upload/route.ts`
**Status:** Keep but reduce verbosity

- Lines 89-91: Directory creation/existence logging
- Lines 101: File save verification logging
- Useful for debugging but could be reduced to errors only

### 4. Middleware Debug Logging
**Location:** `proxy.ts`
**Status:** Keep but consider reducing

- Lines 22-37: Activity logging for all requests
- Useful for monitoring but generates many logs
- Consider: log only important events or add log level filtering

## Unused/Redundant Code

### 5. Legacy Upload Route
**Location:** `app/api/photos/route.ts`
**Status:** Consider deprecating

- Legacy URL-based upload endpoint
- New uploads use `/api/photos/upload`
- Consider:
  - Marking as deprecated
  - Removing if not used
  - Or consolidating with upload route

### 6. Multiple Upload Routes
**Location:** `app/api/photos/upload/route.ts` and `app/api/photos/upload-multiple/route.ts`
**Status:** Keep but document usage

- Two separate upload endpoints
- Consider if both are needed or can be consolidated

### 7. Proxy.ts Cookie Name Variable
**Location:** `proxy.ts` line 15
**Status:** Minor cleanup

- `cookieName` variable defined but could use constant
- Consider moving to shared constant or env var

## Configuration Cleanup

### 8. Next.js Config
**Location:** `next.config.ts`
**Status:** Review

- Image optimization settings (line 19: `unoptimized: false`)
- Consider if all remote patterns are needed
- Review Turbopack configuration if not using

## Documentation Cleanup

### 10. ARCHITECTURE.md References
**Location:** `ARCHITECTURE.md` line 156
**Status:** Update

- Still references `middleware.ts` in some places
- Should reference `proxy.ts` instead
- Update all middleware references

## Testing/Debugging Utilities

### 11. Watch Activity Script
**Location:** `watch-activity.sh` (if created)
**Status:** Keep or document

- Useful utility for monitoring
- Consider adding to README or removing if not needed

## Recommendations

### High Priority (Consider Removing)
1. `app/api/debug/session/route.ts` - Debug endpoint (protect or remove)
2. Verbose logging in `app/photos/page.tsx` - Reduce to errors only
3. Update ARCHITECTURE.md middleware references

### Medium Priority (Optimize)
1. Activity logging - Add log levels or filtering
2. Upload logging - Reduce verbosity
3. Session callback logging - Reduce in production

### Low Priority (Keep)
1. Activity logging utility - Useful for monitoring
2. Multiple upload routes - Document usage
3. Watch activity script - Useful utility

## Notes

- **Consider** adding environment-based log levels (DEBUG, INFO, WARN, ERROR)
- **Consider** moving debug endpoints behind admin authentication
- **Consider** adding log rotation/retention for production

---

Do all these in stages. create new tests and test and docuemtn  as u go.

add DEBUG, INFO, WARN, ERROR flags and only show when asked for. create new branch.
2026-01-04 19:34:21 -05:00

211 lines
7.4 KiB
TypeScript

import { logger, LogLevel, getLogLevel, formatLog, createLogger } from '@/lib/logger';
// Mock console methods
const originalConsole = { ...console };
const mockConsole = {
log: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};
describe('Logger', () => {
const originalEnv = { ...process.env };
beforeEach(() => {
jest.clearAllMocks();
console.log = mockConsole.log;
console.warn = mockConsole.warn;
console.error = mockConsole.error;
// Reset environment variables
process.env = { ...originalEnv };
// Use type assertion to allow deletion
delete (process.env as { LOG_LEVEL?: string }).LOG_LEVEL;
delete (process.env as { LOG_FORMAT?: string }).LOG_FORMAT;
delete (process.env as { NODE_ENV?: string }).NODE_ENV;
});
afterEach(() => {
process.env = originalEnv;
});
afterEach(() => {
console.log = originalConsole.log;
console.warn = originalConsole.warn;
console.error = originalConsole.error;
});
describe('getLogLevel', () => {
it('should return DEBUG when LOG_LEVEL=DEBUG', () => {
process.env.LOG_LEVEL = 'DEBUG';
expect(getLogLevel()).toBe(LogLevel.DEBUG);
});
it('should return INFO when LOG_LEVEL=INFO', () => {
process.env.LOG_LEVEL = 'INFO';
expect(getLogLevel()).toBe(LogLevel.INFO);
});
it('should return WARN when LOG_LEVEL=WARN', () => {
process.env.LOG_LEVEL = 'WARN';
expect(getLogLevel()).toBe(LogLevel.WARN);
});
it('should return ERROR when LOG_LEVEL=ERROR', () => {
process.env.LOG_LEVEL = 'ERROR';
expect(getLogLevel()).toBe(LogLevel.ERROR);
});
it('should return NONE when LOG_LEVEL=NONE', () => {
process.env.LOG_LEVEL = 'NONE';
expect(getLogLevel()).toBe(LogLevel.NONE);
});
it('should default to DEBUG in development', () => {
(process.env as { NODE_ENV?: string }).NODE_ENV = 'development';
expect(getLogLevel()).toBe(LogLevel.DEBUG);
});
it('should default to INFO in production', () => {
(process.env as { NODE_ENV?: string }).NODE_ENV = 'production';
expect(getLogLevel()).toBe(LogLevel.INFO);
});
it('should ignore invalid LOG_LEVEL values and use defaults', () => {
(process.env as { LOG_LEVEL?: string }).LOG_LEVEL = 'INVALID';
(process.env as { NODE_ENV?: string }).NODE_ENV = 'production';
expect(getLogLevel()).toBe(LogLevel.INFO);
});
});
describe('formatLog', () => {
it('should format log in human-readable format by default', () => {
const result = formatLog(LogLevel.INFO, 'Test message', { key: 'value' });
expect(result).toContain('[INFO]');
expect(result).toContain('Test message');
expect(result).toContain('{"key":"value"}');
});
it('should format log as JSON when LOG_FORMAT=json', () => {
process.env.LOG_FORMAT = 'json';
const result = formatLog(LogLevel.INFO, 'Test message', { key: 'value' });
const parsed = JSON.parse(result);
expect(parsed.level).toBe('INFO');
expect(parsed.message).toBe('Test message');
expect(parsed.key).toBe('value');
expect(parsed.timestamp).toBeDefined();
});
it('should format Error objects correctly', () => {
const error = new Error('Test error');
const result = formatLog(LogLevel.ERROR, 'Error occurred', error);
expect(result).toContain('[ERROR]');
expect(result).toContain('Error occurred');
expect(result).toContain('Error: Error: Test error');
});
it('should format Error objects as JSON when LOG_FORMAT=json', () => {
process.env.LOG_FORMAT = 'json';
const error = new Error('Test error');
const result = formatLog(LogLevel.ERROR, 'Error occurred', error);
const parsed = JSON.parse(result);
expect(parsed.level).toBe('ERROR');
expect(parsed.message).toBe('Error occurred');
expect(parsed.error.name).toBe('Error');
expect(parsed.error.message).toBe('Test error');
expect(parsed.error.stack).toBeDefined();
});
it('should handle logs without context', () => {
const result = formatLog(LogLevel.INFO, 'Simple message');
expect(result).toContain('[INFO]');
expect(result).toContain('Simple message');
// Format always includes pipe separator, but no context data after it
expect(result).toContain('|');
expect(result.split('|').length).toBe(2); // timestamp | message (no context)
});
});
describe('Logger instance', () => {
it('should log DEBUG messages when level is DEBUG', () => {
process.env.LOG_LEVEL = 'DEBUG';
const testLogger = createLogger();
testLogger.debug('Debug message', { data: 'test' });
expect(mockConsole.log).toHaveBeenCalled();
});
it('should not log DEBUG messages when level is INFO', () => {
process.env.LOG_LEVEL = 'INFO';
const testLogger = createLogger();
testLogger.debug('Debug message');
expect(mockConsole.log).not.toHaveBeenCalled();
});
it('should log INFO messages when level is INFO', () => {
process.env.LOG_LEVEL = 'INFO';
const testLogger = createLogger();
testLogger.info('Info message');
expect(mockConsole.log).toHaveBeenCalled();
});
it('should log WARN messages when level is WARN', () => {
process.env.LOG_LEVEL = 'WARN';
const testLogger = createLogger();
testLogger.warn('Warning message');
expect(mockConsole.warn).toHaveBeenCalled();
});
it('should not log INFO messages when level is WARN', () => {
process.env.LOG_LEVEL = 'WARN';
const testLogger = createLogger();
testLogger.info('Info message');
expect(mockConsole.log).not.toHaveBeenCalled();
});
it('should log ERROR messages when level is ERROR', () => {
process.env.LOG_LEVEL = 'ERROR';
const testLogger = createLogger();
testLogger.error('Error message');
expect(mockConsole.error).toHaveBeenCalled();
});
it('should not log any messages when level is NONE', () => {
process.env.LOG_LEVEL = 'NONE';
const testLogger = createLogger();
testLogger.debug('Debug message');
testLogger.info('Info message');
testLogger.warn('Warning message');
testLogger.error('Error message');
expect(mockConsole.log).not.toHaveBeenCalled();
expect(mockConsole.warn).not.toHaveBeenCalled();
expect(mockConsole.error).not.toHaveBeenCalled();
});
it('should handle Error objects in error method', () => {
process.env.LOG_LEVEL = 'ERROR';
const testLogger = createLogger();
const error = new Error('Test error');
testLogger.error('Error occurred', error);
expect(mockConsole.error).toHaveBeenCalled();
const callArgs = mockConsole.error.mock.calls[0][0];
expect(callArgs).toContain('Error occurred');
});
it('isLevelEnabled should return correct values', () => {
process.env.LOG_LEVEL = 'WARN';
const testLogger = createLogger();
expect(testLogger.isLevelEnabled(LogLevel.DEBUG)).toBe(false);
expect(testLogger.isLevelEnabled(LogLevel.INFO)).toBe(false);
expect(testLogger.isLevelEnabled(LogLevel.WARN)).toBe(true);
expect(testLogger.isLevelEnabled(LogLevel.ERROR)).toBe(true);
});
});
describe('Default logger instance', () => {
it('should be available and functional', () => {
process.env.LOG_LEVEL = 'INFO';
logger.info('Test message');
expect(mockConsole.log).toHaveBeenCalled();
});
});
});