# Logging and Error Handling Documentation

This document describes the logging and error handling infrastructure implemented in the Betterlearn application.

## Overview

The application now uses:
- **Pino** for structured logging with environment-based configuration
- **Custom Error Types** for better error classification
- **React Error Boundaries** for graceful error handling in the UI
- **Sentry** (optional) for error monitoring and tracking
- **Standardized API Error Handling** for consistent error responses

---

## Logging

### Logger Configuration

The logger is configured in [`lib/utils/logger.ts`](file:///Users/ratneshkumar/Desktop/envato/Betterlearn-envato/lib/utils/logger.ts).

**Development Mode:**
- Pretty-printed, colorful logs
- Full error details and stack traces
- Sensitive data shown (for debugging)

**Production Mode:**
- JSON-formatted logs (for log aggregation)
- Sensitive data redacted
- Optimized for performance

### Using the Logger

#### Basic Logging

```typescript
import { logger } from '@/lib/utils/logger';

// Different log levels
logger.debug('Debug information');
logger.info('Informational message');
logger.warn('Warning message');
logger.error({ err: error }, 'Error occurred');
```

#### Specialized Loggers

The application provides specialized loggers for common patterns:

```typescript
import { loggers } from '@/lib/utils/logger';

// Authentication
loggers.auth.login(userId, { ip: '192.168.1.1' });
loggers.auth.logout(userId);
loggers.auth.unauthorized('/admin', userId);

// Database operations
loggers.db.connect();
loggers.db.query('findUser', 'User', 150); // operation, collection, duration
loggers.db.error('createUser', error);

// API requests
loggers.api.request('GET', '/api/users', userId);
loggers.api.response('GET', '/api/users', 200, 45);
loggers.api.error('POST', '/api/users', error, userId);

// Email
loggers.email.sending('user@example.com', 'Welcome Email');
loggers.email.sent('user@example.com', 'message-id-123');
loggers.email.failed('user@example.com', error);

// AI operations
loggers.ai.request('OpenAI', 'gpt-4', userId);
loggers.ai.response('OpenAI', 'gpt-4', 1500, 2300);
loggers.ai.error('OpenAI', error);

// User actions
loggers.user.created(userId, email);
loggers.user.updated(userId, ['name', 'email']);
loggers.user.deleted(userId);

// Study rooms
loggers.room.created(roomId, teacherId, 'Math 101');
loggers.room.joined(roomId, studentId);
loggers.room.left(roomId, studentId);
```

#### Creating Child Loggers

For adding persistent context to all logs:

```typescript
import { createLogger } from '@/lib/utils/logger';

const requestLogger = createLogger({ requestId: 'req-123', userId: 'user-456' });
requestLogger.info('Processing request'); // Will include requestId and userId
```

### Environment Variables

```bash
# .env
LOG_LEVEL=debug  # Options: debug, info, warn, error
NODE_ENV=development  # development or production
```

---

## Error Types

Custom error types are defined in [`lib/utils/error-types.ts`](file:///Users/ratneshkumar/Desktop/envato/Betterlearn-envato/lib/utils/error-types.ts).

### Available Error Types

```typescript
import {
  ValidationError,
  AuthenticationError,
  AuthorizationError,
  NotFoundError,
  ConflictError,
  DatabaseError,
  ExternalServiceError,
  RateLimitError,
  InsufficientCreditsError,
} from '@/lib/utils/error-types';

// Usage examples
throw new ValidationError('Invalid email format', { field: 'email' });
throw new AuthenticationError('Invalid credentials');
throw new AuthorizationError('Admin access required');
throw new NotFoundError('User');
throw new DatabaseError('Failed to save user');
throw new ExternalServiceError('OpenAI', 'API rate limit exceeded');
throw new RateLimitError('Too many requests', 60); // retryAfter in seconds
throw new InsufficientCreditsError(100, 50); // required, available
```

### Error Properties

All custom errors extend `AppError` and include:
- `statusCode`: HTTP status code (400, 401, 403, 404, 500, etc.)
- `isOperational`: Whether the error is expected (true) or a programming error (false)
- `context`: Additional context data
- `message`: Error message

---

## API Error Handling

### Using the Error Handler

```typescript
import { handleApiError, successResponse } from '@/lib/utils/api-error-handler';
import { NotFoundError } from '@/lib/utils/error-types';

export async function GET(req: NextRequest) {
  try {
    const data = await fetchData();
    
    if (!data) {
      throw new NotFoundError('Resource');
    }
    
    return successResponse(data, {
      message: 'Data retrieved successfully',
      statusCode: 200,
    });
  } catch (error) {
    return handleApiError(error, {
      context: { path: req.nextUrl.pathname },
    });
  }
}
```

### Error Wrapper

Automatically catch and handle errors:

```typescript
import { withErrorHandler } from '@/lib/utils/api-error-handler';

const handler = withErrorHandler(async (req: NextRequest) => {
  const data = await fetchData();
  return successResponse(data);
});

export { handler as GET };
```

### Helper Functions

```typescript
import {
  validateRequiredFields,
  safeJsonParse,
} from '@/lib/utils/api-error-handler';

// Validate required fields
const body = await req.json();
validateRequiredFields(body, ['name', 'email', 'password']);

// Safe JSON parsing
const data = await safeJsonParse<UserData>(req);
```

---

## React Error Boundaries

### Global Error Boundary

The app includes global error boundaries:
- [`app/error.tsx`](file:///Users/ratneshkumar/Desktop/envato/Betterlearn-envato/app/error.tsx) - Handles errors in app directory
- [`app/global-error.tsx`](file:///Users/ratneshkumar/Desktop/envato/Betterlearn-envato/app/global-error.tsx) - Handles errors in root layout

### Using Error Boundaries

```typescript
import { ErrorBoundary } from '@/components/error-boundary';

function MyComponent() {
  return (
    <ErrorBoundary
      fallback={<div>Something went wrong</div>}
      onError={(error, errorInfo) => {
        // Custom error handling
        console.error('Error caught:', error);
      }}
    >
      <YourComponent />
    </ErrorBoundary>
  );
}
```

### HOC Pattern

```typescript
import { withErrorBoundary } from '@/components/error-boundary';

const MyComponent = () => {
  // Component code
};

export default withErrorBoundary(MyComponent, {
  fallback: <CustomErrorUI />,
});
```

---

## Sentry Integration

### Setup

1. **Create Sentry Account:**
   - Go to https://sentry.io
   - Create a new project for Next.js
   - Copy your DSN

2. **Add Environment Variables:**

```bash
# .env
SENTRY_DSN=your-sentry-dsn-here
NEXT_PUBLIC_SENTRY_DSN=your-sentry-dsn-here

# Optional: Enable Sentry in development
SENTRY_ENABLE_DEV=true
```

3. **Configuration Files:**
   - [`sentry.client.config.ts`](file:///Users/ratneshkumar/Desktop/envato/Betterlearn-envato/sentry.client.config.ts) - Client-side configuration
   - [`sentry.server.config.ts`](file:///Users/ratneshkumar/Desktop/envato/Betterlearn-envato/sentry.server.config.ts) - Server-side configuration
   - [`sentry.edge.config.ts`](file:///Users/ratneshkumar/Desktop/envato/Betterlearn-envato/sentry.edge.config.ts) - Edge runtime configuration

### Manual Error Reporting

```typescript
import * as Sentry from '@sentry/nextjs';

try {
  // Your code
} catch (error) {
  Sentry.captureException(error, {
    tags: {
      section: 'payment',
    },
    extra: {
      userId: 'user-123',
      amount: 100,
    },
  });
}
```

### Adding User Context

```typescript
import * as Sentry from '@sentry/nextjs';

Sentry.setUser({
  id: userId,
  email: userEmail,
  username: userName,
});
```

---

## Best Practices

### 1. Use Appropriate Log Levels

- **debug**: Detailed information for debugging (not shown in production)
- **info**: General informational messages
- **warn**: Warning messages that don't prevent operation
- **error**: Error messages that require attention

### 2. Include Context

```typescript
// Bad
logger.error('Failed to save user');

// Good
logger.error(
  {
    err: error,
    userId,
    operation: 'saveUser',
  },
  'Failed to save user'
);
```

### 3. Use Custom Error Types

```typescript
// Bad
throw new Error('User not found');

// Good
throw new NotFoundError('User', { userId });
```

### 4. Don't Log Sensitive Data

The logger automatically redacts sensitive fields, but be cautious:

```typescript
// Automatically redacted
logger.info({ password: '123456' }); // password will be [Redacted]

// Be careful with custom fields
logger.info({ userPassword: '123456' }); // NOT automatically redacted
```

### 5. Handle Errors Gracefully

```typescript
// API Routes
try {
  // Your code
} catch (error) {
  return handleApiError(error, {
    context: { operation: 'createUser' },
  });
}

// React Components
<ErrorBoundary>
  <YourComponent />
</ErrorBoundary>
```

---

## Migration from console.log

### Before

```typescript
console.log('User logged in:', userId);
console.error('Failed to save:', error);
```

### After

```typescript
loggers.auth.login(userId);
loggers.db.error('saveUser', error);
```

---

## Troubleshooting

### Logs Not Appearing

1. Check `LOG_LEVEL` environment variable
2. Ensure logger is imported correctly
3. In production, check JSON logs in your log aggregation tool

### Sentry Not Capturing Errors

1. Verify `SENTRY_DSN` is set
2. Check `enabled` flag in Sentry config
3. Ensure errors are not in `ignoreErrors` list
4. In development, set `SENTRY_ENABLE_DEV=true`

### Error Boundaries Not Catching Errors

1. Error boundaries only catch errors in child components
2. They don't catch errors in:
   - Event handlers (use try-catch)
   - Async code (use try-catch)
   - Server-side rendering
   - Errors in the error boundary itself

---

## Performance Considerations

- Pino is designed for high performance with minimal overhead
- Logs are automatically formatted based on environment
- In production, use log aggregation tools (e.g., Datadog, CloudWatch, Logtail)
- Sentry sampling rates are configured to balance monitoring and performance

---

## Additional Resources

- [Pino Documentation](https://getpino.io/)
- [Sentry Next.js Documentation](https://docs.sentry.io/platforms/javascript/guides/nextjs/)
- [React Error Boundaries](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
