Files
orion/docs/frontend/shared/logging.md
Samir Boulahtit d648c921b7
Some checks failed
CI / ruff (push) Successful in 10s
CI / validate (push) Has been cancelled
CI / dependency-scanning (push) Has been cancelled
CI / docs (push) Has been cancelled
CI / deploy (push) Has been cancelled
CI / pytest (push) Has been cancelled
docs: add consolidated dev URL reference and migrate /shop to /storefront
- Add Development URL Quick Reference section to url-routing overview
  with all login URLs, entry points, and full examples
- Replace /shop/ path segments with /storefront/ across 50 docs files
- Update file references: shop_pages.py → storefront_pages.py,
  templates/shop/ → templates/storefront/, api/v1/shop/ → api/v1/storefront/
- Preserve domain references (orion.shop) and /store/ staff dashboard paths
- Archive docs left unchanged (historical)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 13:23:44 +01:00

8.6 KiB
Raw Blame History

Quick Reference: Centralized Logging System

🚀 Quick Start

In Any Page File (Admin/Store/Shop):

// 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

window.LogConfig.loggers.stores
window.LogConfig.loggers.storeTheme
window.LogConfig.loggers.products
window.LogConfig.loggers.orders
window.LogConfig.loggers.users
window.LogConfig.loggers.dashboard
window.LogConfig.loggers.imports

Store Frontend

window.LogConfig.loggers.dashboard
window.LogConfig.loggers.products
window.LogConfig.loggers.orders
window.LogConfig.loggers.theme
window.LogConfig.loggers.analytics

Shop Frontend

window.LogConfig.loggers.catalog
window.LogConfig.loggers.cart
window.LogConfig.loggers.checkout
window.LogConfig.loggers.product

🎨 Basic Logging

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

const url = '/api/stores';

// 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

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

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

Grouped Logging

log.group('Loading Data');
log.info('Fetching users...');
log.info('Fetching products...');
log.info('Fetching orders...');
log.groupEnd();

Table Logging

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

Timer Logging

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

📋 Complete Page Template

// 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

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:

const myLog = window.LogConfig.createLogger('MY-PAGE', 4); // Force DEBUG

🔍 Debugging Tips

Check Current Config

console.log(window.LogConfig.frontend);    // 'admin' | 'store' | 'shop'
console.log(window.LogConfig.environment); // 'development' | 'production'
console.log(window.LogConfig.logLevel);    // 1 | 2 | 3 | 4

Test Logger

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

Enable Debug Mode

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

⚠️ Common Mistakes

WRONG

// 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

// 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:STORES INFO] Stores module loaded
 [ADMIN:STORES INFO] Initializing stores page
📤 [ADMIN:API DEBUG] GET /admin/stores
📥 [ADMIN:API DEBUG] GET /admin/stores {data...}
⚡ [ADMIN:PERF DEBUG] Load Stores took 45ms
 [ADMIN:STORES INFO] Stores 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:STORES ERROR] Failed to load store

📱 Frontend Detection

The system automatically detects which frontend based on URL:

URL Path Frontend Prefix
/admin/* admin ADMIN:
/store/* store STORE:
/storefront/* storefront SHOP:

🛠️ Customization

Add New Pre-configured Logger

Edit log-config.js:

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

Change Log Level for Frontend

Edit log-config.js:

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

📚 Full API Reference

window.LogConfig = {
    // Log levels
    LOG_LEVELS: { ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4 },

    // Current config
    frontend: 'admin' | 'store' | '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: { stores, 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


Print this page and keep it handy! 📌

Quick pattern to remember:

const log = window.LogConfig.loggers.myPage;
log.info('Hello from my page!');

That's it! 🎉