UNPKG

logstack-zee

Version:

Complete Node.js logging solution with 6 integration methods, S3 bidirectional operations, advanced analytics, and multi-cloud storage support for enterprise-scale applications.

258 lines (252 loc) โ€ข 10.4 kB
"use strict"; /** * ๐Ÿ”— API Logs Collection Name Demo - Cron Log Service * * This example demonstrates how to use the new apiLogsCollectionName field * to avoid conflicts with existing API logs collections in your database. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.config = void 0; exports.testApiLogsCollection = testApiLogsCollection; exports.testMultipleEnvironments = testMultipleEnvironments; exports.runApiLogsDemo = runApiLogsDemo; const main_1 = require("../src/main"); const apiLogs_1 = require("../src/apiLogs"); // ========================================== // ๐Ÿ—ƒ๏ธ CUSTOM API LOGS COLLECTION CONFIGURATION // ========================================== const config = { dbUri: process.env.DB_URI || 'mongodb://localhost:27017/api-logs-demo', uploadProvider: 'local', fileFormat: 'json', outputDirectory: 'api-logs-demo', // โœจ Custom collection names to avoid database conflicts collections: { jobsCollectionName: 'demo_jobs', // Custom jobs collection logsCollectionName: 'demo_logs', // Custom logs collection apiLogsCollectionName: 'demo_api_logs' // ๐ŸŽฏ Custom API logs collection }, logging: { level: 'info', enableConsole: true } }; exports.config = config; // ========================================== // ๐Ÿงช API LOGS COLLECTION TESTING // ========================================== async function testApiLogsCollection() { try { console.log('๐Ÿ—ƒ๏ธ Testing Custom API Logs Collection Name'); console.log('==========================================\n'); // Initialize the service console.log('๐Ÿš€ Initializing service with custom collections...'); await (0, main_1.init)(config); console.log('โœ… Service initialized successfully'); console.log(`๐Ÿ“‹ API logs will be saved to: "${config.collections?.apiLogsCollectionName}"`); // Test saving API logs with custom collection console.log('\n๐Ÿ’พ Testing API Log Saving...'); const apiLogData = { method: 'POST', path: '/api/users', requestBody: { name: 'John Doe', email: 'john@example.com' }, requestHeaders: { 'content-type': 'application/json' }, responseStatus: 201, responseBody: { id: 123, message: 'User created successfully' }, client_ip: '192.168.1.100', client_agent: 'Mozilla/5.0 (Demo Browser)' }; const savedLog = await (0, apiLogs_1.saveApiLog)(apiLogData, config); console.log('โœ… API log saved successfully'); console.log(`๐Ÿ“„ Log ID: ${savedLog._id}`); console.log(`๐Ÿ—‚๏ธ Saved to collection: ${config.collections?.apiLogsCollectionName}`); // Test retrieving API logs console.log('\n๐Ÿ“Š Testing API Log Retrieval...'); const logs = await (0, apiLogs_1.getApiLogs)({ method: 'POST', limit: 5 }, config); console.log(`โœ… Retrieved ${logs.length} API logs`); console.log(`๐Ÿ” Searched in collection: ${config.collections?.apiLogsCollectionName}`); // Show the latest log if (logs.length > 0) { const latestLog = logs[0]; console.log('\n๐Ÿ“‹ Latest API Log:'); console.log(` Method: ${latestLog.method}`); console.log(` Path: ${latestLog.path}`); console.log(` Status: ${latestLog.responseStatus}`); console.log(` Time: ${latestLog.request_time}`); } } catch (error) { console.error('โŒ API logs collection test failed:', error); throw error; } } // ========================================== // ๐Ÿข MULTIPLE ENVIRONMENTS DEMO // ========================================== async function testMultipleEnvironments() { console.log('\n๐Ÿข Testing Multiple Environment Collections'); console.log('==========================================\n'); const environments = [ { name: '๐Ÿงช Development', config: { ...config, collections: { jobsCollectionName: 'dev_jobs', logsCollectionName: 'dev_logs', apiLogsCollectionName: 'dev_api_logs' // Separate dev API logs } } }, { name: '๐Ÿš€ Production', config: { ...config, collections: { jobsCollectionName: 'prod_jobs', logsCollectionName: 'prod_logs', apiLogsCollectionName: 'prod_api_logs' // Separate prod API logs } } }, { name: '๐Ÿงช Testing', config: { ...config, collections: { jobsCollectionName: 'test_jobs', logsCollectionName: 'test_logs', apiLogsCollectionName: 'test_api_logs' // Separate test API logs } } } ]; for (const env of environments) { console.log(`${env.name} Environment`); console.log('โ”€'.repeat(25)); try { // Save a test API log for each environment const testLogData = { method: 'GET', path: '/health', responseStatus: 200, responseBody: { status: 'healthy', environment: env.name }, client_ip: '127.0.0.1' }; const savedLog = await (0, apiLogs_1.saveApiLog)(testLogData, env.config); console.log(`โœ… ${env.name} API log saved`); console.log(`๐Ÿ—‚๏ธ Collection: ${env.config.collections.apiLogsCollectionName}`); console.log(`๐Ÿ“„ Log ID: ${savedLog._id}`); } catch (error) { console.error(`โŒ ${env.name} failed:`, error instanceof Error ? error.message : error); } console.log(''); // Empty line for readability } } // ========================================== // ๐ŸŒ EXPRESS MIDDLEWARE DEMO // ========================================== function showExpressMiddlewareExample() { console.log('\n๐ŸŒ Express Middleware Usage Example'); console.log('===================================\n'); console.log('// Example Express.js integration with custom API logs collection'); console.log(''); console.log('const express = require("express");'); console.log('const { createApiLogMiddleware } = require("logstack");'); console.log(''); console.log('const app = express();'); console.log(''); console.log('// Your custom configuration'); console.log('const config = {'); console.log(' dbUri: "mongodb://localhost:27017/myapp",'); console.log(' collections: {'); console.log(' jobsCollectionName: "myapp_jobs",'); console.log(' logsCollectionName: "myapp_logs",'); console.log(' apiLogsCollectionName: "myapp_api_logs" // ๐ŸŽฏ Custom API logs collection'); console.log(' }'); console.log('};'); console.log(''); console.log('// Use the middleware with your custom collection'); console.log('app.use(createApiLogMiddleware(config));'); console.log(''); console.log('// Your API routes will now be logged to "myapp_api_logs" collection'); console.log('app.get("/api/users", (req, res) => {'); console.log(' res.json({ users: [] });'); console.log('});'); console.log(''); console.log('app.listen(3000);'); console.log(''); console.log('โœจ All API requests will be automatically logged to your custom collection!'); } // ========================================== // ๐Ÿƒโ€โ™‚๏ธ MAIN DEMO FUNCTION // ========================================== async function runApiLogsDemo() { try { console.log('๐Ÿ”— API Logs Collection Name Demo'); console.log('================================\n'); console.log('๐Ÿ’ก Benefits of custom API logs collection names:'); console.log(' โ€ข Avoid conflicts with existing collections'); console.log(' โ€ข Separate environments (dev, prod, test)'); console.log(' โ€ข Better database organization'); console.log(' โ€ข Easy data migration and cleanup'); console.log(''); // Test basic functionality await testApiLogsCollection(); // Test multiple environments await testMultipleEnvironments(); // Show Express middleware example showExpressMiddlewareExample(); console.log('\n๐ŸŽ‰ API Logs Collection Demo Complete!'); console.log('===================================='); console.log('โœ… Custom API logs collection working'); console.log('โœ… Multiple environment support'); console.log('โœ… Express middleware integration ready'); console.log('โœ… Database conflicts avoided'); console.log('\n๐Ÿš€ Ready for production with custom collection names!'); } catch (error) { console.error('\nโŒ API Logs Demo Failed:', error); console.log('\n๐Ÿ’ก Troubleshooting:'); console.log('1. Check MongoDB connection'); console.log('2. Ensure database permissions'); console.log('3. Verify collection name format'); process.exit(1); } } // ========================================== // ๐Ÿ“ USAGE NOTES // ========================================== /* ๐Ÿ”ง Configuration Options for apiLogsCollectionName: 1. Default behavior (if not specified): collections: { // apiLogsCollectionName will default to "apilogs" } 2. Custom collection name: collections: { apiLogsCollectionName: "my_custom_api_logs" } 3. Environment-specific collections: collections: { apiLogsCollectionName: `${process.env.NODE_ENV}_api_logs` } 4. App-specific collections: collections: { apiLogsCollectionName: "myapp_api_logs" } ๐Ÿ“‹ Collection Naming Best Practices: โ€ข Use descriptive names: "myapp_api_logs" instead of "logs" โ€ข Include environment: "prod_api_logs", "dev_api_logs" โ€ข Use consistent naming: snake_case or camelCase โ€ข Avoid special characters except underscore โ€ข Keep names short but meaningful */ // Run the demo if this file is executed directly if (require.main === module) { runApiLogsDemo().catch(console.error); }