ilia 08914dc469 Implements a comprehensive structured logging system to replace verbose console.* calls throughout the codebase, addressing all cleanup tasks from CLEANUP.md. (#4)
# Structured Logging System Implementation

## Summary
Implements a comprehensive structured logging system to replace verbose console.* calls throughout the codebase, addressing all cleanup tasks from CLEANUP.md.

## What Changed

### Core Features
-  **Structured Logging System** - New `lib/logger.ts` with DEBUG, INFO, WARN, ERROR levels
-  **Environment-Based Control** - `LOG_LEVEL` env var controls verbosity (DEBUG/INFO/WARN/ERROR/NONE)
-  **JSON Logging Option** - `LOG_FORMAT=json` for structured JSON output
-  **Shared Constants** - Extracted session cookie name to `lib/constants.ts`

### Code Refactoring
-  Replaced all `console.*` calls in API routes with structured logger
-  Refactored `activity-log.ts` to use new logger system
-  Reduced verbose logging in auth, photos page, and upload routes
-  Updated proxy.ts to use structured logging
-  Removed unused legacy `/api/photos` route (replaced by `/api/photos/upload`)

### Security Improvements
-  Protected `/api/debug/session` endpoint with admin-only access
-  Added proper error logging with structured context

### Documentation
-  Documented multiple upload routes usage
-  Enhanced watch-activity.sh script documentation
-  Updated README.md with upload endpoint information
-  Added configuration documentation to next.config.ts

### Testing
-  Added 23 tests for logger system
-  Added 8 tests for refactored activity-log
-  All 43 tests passing

## Benefits

1. **Production-Ready Logging** - Environment-based control, defaults to INFO in production
2. **Reduced Verbosity** - DEBUG logs only show in development or when explicitly enabled
3. **Structured Output** - JSON format option for log aggregation tools
4. **Better Organization** - Shared constants, consistent logging patterns
5. **Improved Security** - Debug endpoint now requires admin access

## Testing

### Manual Testing
-  Server builds successfully
-  All tests pass (43/43)
-  Type checking passes
-  Linting passes
-  Production server runs with logs visible
-  Log levels work correctly (DEBUG shows all, INFO shows activity, etc.)

### Test Coverage
- Logger system: 100% coverage
- Activity log: 100% coverage
- All existing tests still pass

## Configuration

### Environment Variables
```bash
# Control log verbosity (DEBUG, INFO, WARN, ERROR, NONE)
LOG_LEVEL=INFO

# Use structured JSON logging
LOG_FORMAT=json
```

### Defaults
- Development: `LOG_LEVEL=DEBUG` (shows all logs)
- Production: `LOG_LEVEL=INFO` (shows activity and above)

## Migration Notes

- No breaking changes (legacy route was unused)
- All existing functionality preserved
- Logs are now structured and filterable
- Debug endpoint now requires admin authentication
- Legacy `/api/photos` endpoint removed (use `/api/photos/upload` instead)

## Checklist

- [x] All console.* calls replaced in API routes
- [x] Logger system implemented with tests
- [x] Activity logging refactored
- [x] Debug endpoint protected
- [x] Documentation updated
- [x] All tests passing
- [x] Type checking passes
- [x] Linting passes
- [x] Build succeeds
- [x] Manual testing completed

## Related Issues
Addresses cleanup tasks from CLEANUP.md:
- Task 1: Verbose logging in production 
- Task 2: Activity logging optimization 
- Task 3: Upload verification logging 
- Task 4: Middleware debug logging 
- Task 5: Legacy upload route documentation 
- Task 6: Multiple upload routes documentation 
- Task 7: Cookie name constant extraction 
- Task 8: Next.js config documentation 
- Task 9: ARCHITECTURE.md (already correct) 
- Task 10: Watch activity script documentation 

Reviewed-on: #4
2026-01-04 19:42:49 -05:00

92 lines
3.3 KiB
TypeScript

import { auth } from "@/lib/auth"
import { redirect } from "next/navigation"
import { prisma } from "@/lib/prisma"
import Link from "next/link"
import PhotoThumbnail from "@/components/PhotoThumbnail"
import DeletePhotoButton from "@/components/DeletePhotoButton"
import { logger } from "@/lib/logger"
// Enable caching for this page
export const revalidate = 60 // Revalidate every 60 seconds
export default async function PhotosPage() {
// DEBUG level: only logs in development or when LOG_LEVEL=DEBUG
logger.debug("PhotosPage: Starting, calling auth()")
const session = await auth()
if (!session) {
logger.debug("PhotosPage: No session, redirecting to login")
redirect("/login")
}
if (!session.user) {
// WARN level: session exists but no user is a warning condition
logger.warn("PhotosPage: Session exists but no user, redirecting to login", {
hasSession: !!session,
sessionKeys: session ? Object.keys(session) : [],
})
redirect("/login")
}
logger.debug("PhotosPage: Session valid, rendering page", {
userId: session.user.id,
userEmail: session.user.email,
})
// Limit to 50 photos per page for performance
const photos = await prisma.photo.findMany({
take: 50,
orderBy: { createdAt: "desc" },
include: {
uploader: {
select: {
name: true,
},
},
},
})
return (
<div className="max-w-7xl mx-auto px-4 py-8">
<h1 className="text-3xl font-bold text-gray-900 mb-6">All Photos</h1>
{photos.length === 0 ? (
<div className="bg-white rounded-lg shadow-md p-8 text-center">
<p className="text-gray-500">No photos yet. Be the first to upload one!</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{photos.map((photo: { id: string; url: string; answerName: string; points: number; createdAt: Date; uploader: { name: string } }) => (
<div
key={photo.id}
className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition relative group"
>
<Link href={`/photos/${photo.id}`}>
<div className="aspect-square bg-gray-200 relative">
<PhotoThumbnail src={photo.url} alt="Photo" />
</div>
<div className="p-4">
<div className="flex items-center justify-between mb-1">
<p className="text-sm text-gray-500">Uploaded by {photo.uploader.name}</p>
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800">
{photo.points} {photo.points === 1 ? "pt" : "pts"}
</span>
</div>
<p className="text-xs text-gray-400 mt-1">
{new Date(photo.createdAt).toLocaleDateString()}
</p>
</div>
</Link>
{session.user.role === "ADMIN" && (
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<DeletePhotoButton photoId={photo.id} />
</div>
)}
</div>
))}
</div>
)}
</div>
)
}