# Quick Reference: Centralized Logging System

## 🚀 Quick Start

### In Any Page File (Admin/Vendor/Shop):

```javascript
// 1. Use pre-configured logger (RECOMMENDED)
const pageLog = window.LogConfig.loggers.yourPage;

// 2. Or create custom logger
const pageLog = window.LogConfig.createLogger('PAGE-NAME');

// 3. Use it
pageLog.info('Page loaded');
pageLog.debug('Data:', data);
pageLog.warn('Warning message');
pageLog.error('Error occurred', error);
```

---

## 📦 Pre-configured Loggers

### Admin Frontend
```javascript
window.LogConfig.loggers.vendors
window.LogConfig.loggers.vendorTheme
window.LogConfig.loggers.products
window.LogConfig.loggers.orders
window.LogConfig.loggers.users
window.LogConfig.loggers.dashboard
window.LogConfig.loggers.imports
```

### Vendor Frontend
```javascript
window.LogConfig.loggers.dashboard
window.LogConfig.loggers.products
window.LogConfig.loggers.orders
window.LogConfig.loggers.theme
window.LogConfig.loggers.analytics
```

### Shop Frontend
```javascript
window.LogConfig.loggers.catalog
window.LogConfig.loggers.cart
window.LogConfig.loggers.checkout
window.LogConfig.loggers.product
```

---

## 🎨 Basic Logging

```javascript
const log = window.LogConfig.loggers.myPage;

// Simple messages
log.info('Operation started');
log.warn('Slow connection detected');
log.error('Operation failed');
log.debug('Debug data:', { user: 'John', id: 123 });

// With multiple arguments
log.info('User logged in:', username, 'at', timestamp);
```

---

## 🔥 Advanced Features

### API Call Logging
```javascript
const url = '/api/vendors';

// Before request
window.LogConfig.logApiCall('GET', url, null, 'request');

// Make request
const data = await apiClient.get(url);

// After response
window.LogConfig.logApiCall('GET', url, data, 'response');
```

### Performance Logging
```javascript
const start = performance.now();
await expensiveOperation();
const duration = performance.now() - start;

window.LogConfig.logPerformance('Operation Name', duration);
// Output: ⚡ Operation Name took 45ms (fast)
// Output: ⏱️ Operation Name took 250ms (medium)
// Output: 🐌 Operation Name took 750ms (slow)
```

### Error Logging
```javascript
try {
    await riskyOperation();
} catch (error) {
    window.LogConfig.logError(error, 'Operation Context');
    // Automatically logs error message and stack trace
}
```

### Grouped Logging
```javascript
log.group('Loading Data');
log.info('Fetching users...');
log.info('Fetching products...');
log.info('Fetching orders...');
log.groupEnd();
```

### Table Logging
```javascript
const users = [
    { id: 1, name: 'John', status: 'active' },
    { id: 2, name: 'Jane', status: 'inactive' }
];
log.table(users);
```

### Timer Logging
```javascript
log.time('Data Processing');
// ... long operation ...
log.timeEnd('Data Processing');
// Output: ⏱️ [ADMIN:PAGE TIME] Data Processing: 1234.56ms
```

---

## 📋 Complete Page Template

```javascript
// static/admin/js/my-page.js

// 1. Setup logger
const pageLog = window.LogConfig.loggers.myPage;

// 2. Create component
function myPageComponent() {
    return {
        ...data(),
        currentPage: 'my-page',
        
        items: [],
        loading: false,
        
        async init() {
            pageLog.info('Initializing page');
            
            // Prevent double init
            if (window._myPageInitialized) return;
            window._myPageInitialized = true;
            
            const start = performance.now();
            
            try {
                pageLog.group('Loading Data');
                await this.loadData();
                pageLog.groupEnd();
                
                const duration = performance.now() - start;
                window.LogConfig.logPerformance('Page Init', duration);
                
                pageLog.info('Page initialized successfully');
            } catch (error) {
                window.LogConfig.logError(error, 'Page Init');
            }
        },
        
        async loadData() {
            const url = '/api/my-data';
            window.LogConfig.logApiCall('GET', url, null, 'request');
            
            const data = await apiClient.get(url);
            
            window.LogConfig.logApiCall('GET', url, data, 'response');
            this.items = data;
        }
    };
}

pageLog.info('Page module loaded');
```

---

## 🎯 Log Levels

```javascript
LOG_LEVELS = {
    ERROR: 1,   // Only errors
    WARN: 2,    // Errors + warnings
    INFO: 3,    // Errors + warnings + info (default)
    DEBUG: 4    // Everything
}
```

**Auto-detected:**
- `localhost` → DEBUG (4)
- Production → Varies by frontend

**Manual override:**
```javascript
const myLog = window.LogConfig.createLogger('MY-PAGE', 4); // Force DEBUG
```

---

## 🔍 Debugging Tips

### Check Current Config
```javascript
console.log(window.LogConfig.frontend);    // 'admin' | 'vendor' | 'shop'
console.log(window.LogConfig.environment); // 'development' | 'production'
console.log(window.LogConfig.logLevel);    // 1 | 2 | 3 | 4
```

### Test Logger
```javascript
const test = window.LogConfig.createLogger('TEST', 4);
test.info('This is a test');
test.debug('Debug info:', { test: true });
```

### Enable Debug Mode
```javascript
// In browser console
window.LogConfig.loggers.myPage = window.LogConfig.createLogger('MY-PAGE', 4);
// Now reload page to see debug logs
```

---

## ⚠️ Common Mistakes

### ❌ WRONG
```javascript
// Old way (don't do this!)
const LOG_LEVEL = 3;
const log = {
    info: (...args) => LOG_LEVEL >= 3 && console.log(...args)
};

// Wrong case
ApiClient.get(url)  // Should be apiClient
Logger.info()       // Should be window.LogConfig
```

### ✅ CORRECT
```javascript
// New way
const log = window.LogConfig.loggers.myPage;

// Correct case
apiClient.get(url)
window.LogConfig.loggers.myPage.info()
```

---

## 🎨 Console Output Examples

### Development Mode
```
🎛️ Admin Frontend Logging System Initialized
   Environment: Development
   Log Level: 4 (DEBUG)
ℹ️ [ADMIN:VENDORS INFO] Vendors module loaded
ℹ️ [ADMIN:VENDORS INFO] Initializing vendors page
📤 [ADMIN:API DEBUG] GET /admin/vendors
📥 [ADMIN:API DEBUG] GET /admin/vendors {data...}
⚡ [ADMIN:PERF DEBUG] Load Vendors took 45ms
ℹ️ [ADMIN:VENDORS INFO] Vendors loaded: 25 items
```

### Production Mode (Admin)
```
🎛️ Admin Frontend Logging System Initialized
   Environment: Production
   Log Level: 2 (WARN)
⚠️ [ADMIN:API WARN] Slow API response: 2.5s
❌ [ADMIN:VENDORS ERROR] Failed to load vendor
```

---

## 📱 Frontend Detection

The system automatically detects which frontend based on URL:

| URL Path | Frontend | Prefix |
|----------|----------|--------|
| `/admin/*` | admin | `ADMIN:` |
| `/vendor/*` | vendor | `VENDOR:` |
| `/shop/*` | shop | `SHOP:` |

---

## 🛠️ Customization

### Add New Pre-configured Logger

Edit `log-config.js`:

```javascript
const adminLoggers = {
    // ... existing loggers
    myNewPage: createLogger('MY-NEW-PAGE', ACTIVE_LOG_LEVEL)
};
```

### Change Log Level for Frontend

Edit `log-config.js`:

```javascript
const DEFAULT_LOG_LEVELS = {
    admin: {
        development: LOG_LEVELS.DEBUG,
        production: LOG_LEVELS.INFO  // Change this
    }
};
```

---

## 📚 Full API Reference

```javascript
window.LogConfig = {
    // Log levels
    LOG_LEVELS: { ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4 },
    
    // Current config
    frontend: 'admin' | 'vendor' | 'shop',
    environment: 'development' | 'production',
    logLevel: 1 | 2 | 3 | 4,
    
    // Default logger
    log: { error(), warn(), info(), debug(), group(), groupEnd(), table(), time(), timeEnd() },
    
    // Pre-configured loggers
    loggers: { vendors, products, orders, ... },
    
    // Create custom logger
    createLogger(prefix, level?),
    
    // Utility functions
    logApiCall(method, url, data?, status),
    logError(error, context),
    logPerformance(operation, duration)
}
```

---

## 💡 Tips & Tricks

1. **Use Pre-configured Loggers**
   - Faster to write
   - Consistent naming
   - Already configured

2. **Log API Calls**
   - Easy to track requests
   - See request/response data
   - Debug API issues

3. **Track Performance**
   - Find slow operations
   - Optimize bottlenecks
   - Monitor page load times

4. **Group Related Logs**
   - Cleaner console
   - Easier to follow
   - Better debugging

5. **Use Debug Level in Development**
   - See everything
   - Find issues faster
   - Learn how code flows

---

## 📖 More Documentation

- [Admin Page Templates](../admin/page-templates.md)
- [Vendor Page Templates](../vendor/page-templates.md)
- [Shop Page Templates](../shop/page-templates.md)

---

**Print this page and keep it handy!** 📌

Quick pattern to remember:
```javascript
const log = window.LogConfig.loggers.myPage;
log.info('Hello from my page!');
```

That's it! 🎉
