JEISA-WEBAPP/LOGGING_IMPLEMENTATION.md

170 lines
6 KiB
Markdown
Raw Normal View History

2025-09-24 22:15:35 +00:00
# Logging System Implementation
## Overview
This document outlines the simple logging system that has been implemented for your JEI Stock App using PocketBase as the backend.
## Features
- **Multiple log levels**: `info`, `warn`, `error`, `debug`
- **Module-based logging**: Organize logs by application modules (stock, customers, book-out, etc.)
- **User tracking**: Associate logs with specific users
- **Metadata support**: Store additional context with logs
- **Web UI**: View and filter logs through a dedicated page
- **Automatic cleanup**: Remove old logs to manage storage
- **Development console**: Logs also appear in browser console during development
## Files Created/Modified
### 1. PocketBase Migration (`pocketbase/pb_migrations/1757376600_created_logs.js`)
Creates the `logs` collection in PocketBase with the following fields:
- `action`: Description of what happened
- `level`: Log level (info, warn, error, debug)
- `details`: Additional information
- `user`: User who performed the action
- `module`: Application module (stock, customers, etc.)
- `metadata`: JSON data for extra context
- `created`/`updated`: Timestamps
### 2. Logger Service (`src/lib/logger.ts`)
Main logging utility with methods:
- `info()`, `warn()`, `error()`, `debug()`: Basic logging methods
- `logStockOperation()`: Convenience method for stock operations
- `logCustomerOperation()`: Convenience method for customer operations
- `logBookOutOperation()`: Convenience method for book-out operations
- `logError()`: Specialized error logging
- `getLogs()`: Retrieve logs with filtering
- `clearOldLogs()`: Remove old logs
### 3. TypeScript Types (`src/types/pocketbase.d.ts`)
Updated with proper types for all PocketBase collections including the new `LogRecord` type.
### 4. Logs Viewing Component (`src/components/LogsView.tsx`)
React component that provides:
- Table view of all logs
- Filtering by level, module, and user
- Pagination
- Log cleanup functionality
### 5. Logs Page (`src/pages/Logs.tsx`)
Dedicated page for viewing logs, accessible via `/logs` route.
### 6. Navigation Updates
- Added logs page to sidebar navigation (`src/components/SidebarNav.tsx`)
- Added route to main app router (`src/App.tsx`)
### 7. Integration in Forms
Added logging to:
- Stock item creation (`src/components/stock/AddItemForm.tsx`)
- Book-out operations (`src/components/book-out/BookOutForm.tsx`)
## Usage Examples
### Basic Logging
```typescript
import logger from '@/lib/logger';
// Info log
await logger.info('User logged in', 'User john@example.com logged in successfully');
// Error log
await logger.error('Database connection failed', error.message, { error: error.stack });
// With user and module context
await logger.warn('Low stock warning', 'Item XYZ-123 has only 2 units left', null, {
user: 'admin',
module: 'stock'
});
```
### Convenience Methods
```typescript
// Stock operations
await logger.logStockOperation('added', 'Wireless Mouse', 50, 'admin');
// Customer operations
await logger.logCustomerOperation('created', 'ABC Company', 'admin');
// Book-out operations
await logger.logBookOutOperation('ABC Company', [itemData], 'admin');
// Error logging
await logger.logError('Failed to save customer', error, 'admin', 'customers');
```
### Retrieving Logs
```typescript
// Get all logs
const allLogs = await logger.getLogs();
// Get error logs only
const errorLogs = await logger.getLogs({ level: 'error' });
// Get logs for specific module
const stockLogs = await logger.getLogs({ module: 'stock', limit: 100 });
// Get logs for specific user
const userLogs = await logger.getLogs({ user: 'admin', page: 1 });
```
## Setup Instructions
1. **Run PocketBase Migration**: Start your PocketBase server and the migration should run automatically, creating the `logs` collection.
2. **Set User Context**: In your authentication logic, set the current user:
```typescript
logger.setUser('admin'); // or whatever user is logged in
```
3. **Access Logs**: Navigate to `/logs` in your application to view the logs interface.
## Configuration
### Environment Variables
The logger automatically detects development mode using `import.meta.env.MODE` and will output logs to the browser console in development.
### Log Retention
By default, the `clearOldLogs()` method removes logs older than 30 days. You can adjust this:
```typescript
await logger.clearOldLogs(7); // Remove logs older than 7 days
```
## Security Considerations
- The logs collection inherits PocketBase's authentication rules
- Sensitive data should not be logged in plain text
- Consider implementing log access restrictions based on user roles
- Regular cleanup of old logs is recommended to manage storage
## Future Enhancements
1. **Real-time Logging**: Use PocketBase's real-time subscriptions for live log updates
2. **Log Exporting**: Add functionality to export logs as CSV/JSON
3. **Log Analytics**: Add charts and statistics for log analysis
4. **Alert System**: Set up notifications for critical errors
5. **User Authentication**: Integrate with your user authentication system
6. **Advanced Filtering**: Add date range filtering and full-text search
## Troubleshooting
### Common Issues
1. **Migration not running**: Ensure PocketBase is running and the migration file is in the correct directory
2. **TypeScript errors**: Make sure all imports are correct and types are properly defined
3. **Logs not appearing**: Check that PocketBase connection is working and the logs collection exists
4. **Console errors**: Verify that all required UI components are available
### Testing the Logger
```typescript
// Test basic functionality
await logger.info('Test log', 'Testing the logging system');
await logger.error('Test error', 'This is a test error');
// Check if logs are being created
const testLogs = await logger.getLogs({ limit: 5 });
console.log('Recent logs:', testLogs);
```
This logging system provides a solid foundation for monitoring your application's activities and debugging issues. The integration with PocketBase makes it easy to store and query logs, while the web interface provides a user-friendly way to view and analyze log data.