6 KiB
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 happenedlevel: Log level (info, warn, error, debug)details: Additional informationuser: User who performed the actionmodule: Application module (stock, customers, etc.)metadata: JSON data for extra contextcreated/updated: Timestamps
2. Logger Service (src/lib/logger.ts)
Main logging utility with methods:
info(),warn(),error(),debug(): Basic logging methodslogStockOperation(): Convenience method for stock operationslogCustomerOperation(): Convenience method for customer operationslogBookOutOperation(): Convenience method for book-out operationslogError(): Specialized error logginggetLogs(): Retrieve logs with filteringclearOldLogs(): 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
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
// 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
// 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
-
Run PocketBase Migration: Start your PocketBase server and the migration should run automatically, creating the
logscollection. -
Set User Context: In your authentication logic, set the current user:
logger.setUser('admin'); // or whatever user is logged in -
Access Logs: Navigate to
/logsin 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:
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
- Real-time Logging: Use PocketBase's real-time subscriptions for live log updates
- Log Exporting: Add functionality to export logs as CSV/JSON
- Log Analytics: Add charts and statistics for log analysis
- Alert System: Set up notifications for critical errors
- User Authentication: Integrate with your user authentication system
- Advanced Filtering: Add date range filtering and full-text search
Troubleshooting
Common Issues
- Migration not running: Ensure PocketBase is running and the migration file is in the correct directory
- TypeScript errors: Make sure all imports are correct and types are properly defined
- Logs not appearing: Check that PocketBase connection is working and the logs collection exists
- Console errors: Verify that all required UI components are available
Testing the Logger
// 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.