Logger Simple SDK
Complete documentation for PHP and Node.js clients. Learn how to integrate powerful logging into your applications in minutes.
Introduction
The Logger Simple PHP client provides a simple and robust way to send logs from your PHP applications. It's designed for sending logs only - view and analyze them through the Logger Simple Dashboard.
Installation
Manual Installation
Download the Logger.php
file and include it in your project:
require_once 'path/to/Logger.php'; // Create logger instance $logger = new LoggerSimple([ 'app_id' => 'your_app_id', 'api_key' => 'your_api_key' ]); // Or use helper function $logger = createLogger('your_app_id', 'your_api_key');
Requirements
- PHP 7.4+ or PHP 8.0+
- cURL extension enabled
- JSON extension enabled
- HTTPS outbound access on port 443
Quick Start
Get up and running with Logger Simple in just a few lines of code.
logSuccess('User logged in successfully', [ 'user_id' => 12345, 'ip' => $_SERVER['REMOTE_ADDR'] ]); $logger->logInfo('Processing order', [ 'order_id' => 'ORD-001', 'amount' => 99.99 ]); $logger->logWarning('High memory usage detected', [ 'memory_usage' => memory_get_usage(), 'threshold' => '128MB' ]); $logger->logError('Database connection failed', [ 'database' => 'mysql', 'error' => 'Connection timeout' ]); $logger->logCritical('Payment gateway unavailable', [ 'service' => 'stripe', 'downtime_minutes' => 5 ]); // Send heartbeat $logger->sendHeartbeat(); // Check metrics $metrics = $logger->getMetrics(); echo "Logs sent: " . $metrics['logsSent']; echo "Success rate: " . ($metrics['logsSuccess'] / $metrics['logsSent'] * 100) . "%";
Configuration
$logger = new LoggerSimple([ 'app_id' => 'your_app_id', 'api_key' => 'your_api_key', 'api_url' => 'https://api.logger-simple.com/', // Custom URL 'options' => [ 'timeout' => 30, // Request timeout (seconds) 'retryAttempts' => 3, // Number of retry attempts 'retryDelay' => 1000, // Delay between retries (ms) 'maxLogLength' => 10000, // Max message length 'enableCrashLogging' => true, // Auto-capture errors 'connectTimeout' => 10, // Connection timeout 'sslVerify' => true, // SSL verification 'userAgent' => 'MyApp/1.0' // Custom User-Agent ] ]);
Configuration Options
Option | Type | Default | Description |
---|---|---|---|
timeout |
int | 30 | Request timeout in seconds |
retryAttempts |
int | 3 | Number of retry attempts on failure |
retryDelay |
int | 1000 | Delay between retries in milliseconds |
maxLogLength |
int | 10000 | Maximum length of log messages |
enableCrashLogging |
bool | true | Automatically capture fatal errors |
Logging Methods
Log Levels
Logger Simple supports 5 log levels, each designed for specific use cases:
Method | Level | Use Case | Example |
---|---|---|---|
logSuccess() |
success | Important successful operations | User registration, payment completed |
logInfo() |
info | General information tracking | Process started, data imported |
logWarning() |
warning | Situations requiring attention | High memory usage, deprecated API |
logError() |
error | Recoverable errors | Database timeout, API failure |
logCritical() |
critical | Critical system errors | Service down, security breach |
Method Signatures
// All methods follow the same signature $logger->logSuccess(string $message, mixed $context = null): ?array $logger->logInfo(string $message, mixed $context = null): ?array $logger->logWarning(string $message, mixed $context = null): ?array $logger->logError(string $message, mixed $context = null): ?array $logger->logCritical(string $message, mixed $context = null): ?array // Generic method with dynamic level $logger->log(string $level, string $message, mixed $context = null): ?array // Examples with context $logger->logInfo('User action', [ 'user_id' => 123, 'action' => 'profile_update', 'timestamp' => time() ]); $logger->logError('Database error', [ 'query' => $sql, 'error' => $exception->getMessage(), 'duration_ms' => $executionTime ]);
Error Handling
Exception Logging
Automatically log exceptions with full context and stack traces:
try { // Code that might throw an exception $result = performRiskyOperation(); } catch (Exception $e) { // Log exception automatically with full context $logger->logException($e); // Or specify custom level $logger->logException($e, 'critical'); // The logged data includes: // - Exception class name // - Message // - File and line number // - Full stack trace // - Exception code // - Timestamp }
Automatic Crash Detection
When enableCrashLogging
is true, the logger automatically captures:
- Fatal errors (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE)
- Uncaught exceptions
- Full error context and stack traces
Framework Integration
Laravel Integration
// In AppServiceProvider use App\Services\LoggerSimple; class AppServiceProvider extends ServiceProvider { public function register() { $this->app->singleton(LoggerSimple::class, function () { return new LoggerSimple([ 'app_id' => config('logger.app_id'), 'api_key' => config('logger.api_key') ]); }); } } // In Controller class UserController extends Controller { private $logger; public function __construct(LoggerSimple $logger) { $this->logger = $logger; } public function store(Request $request) { try { $user = User::create($request->validated()); $this->logger->logSuccess('User created', [ 'user_id' => $user->id, 'email' => $user->email ]); return response()->json($user, 201); } catch (Exception $e) { $this->logger->logException($e); return response()->json(['error' => 'Creation failed'], 500); } } }
Symfony Integration
services: LoggerSimple: arguments: $config: app_id: '%env(LOGGER_APP_ID)%' api_key: '%env(LOGGER_API_KEY)%'
class ApiController extends AbstractController { private LoggerSimple $logger; public function __construct(LoggerSimple $logger) { $this->logger = $logger; } #[Route('/api/process', methods: ['POST'])] public function process(Request $request): JsonResponse { return $this->logger->measure('api_process', function() use ($request) { $this->logger->logInfo('API processing started'); // Process data... $result = $this->processData($request->getContent()); $this->logger->logSuccess('API processing completed'); return new JsonResponse($result); }); } }
Introduction
The Logger Simple Node.js module provides comprehensive logging capabilities with advanced features like batch processing, automatic heartbeats, and graceful shutdown handling.
Installation
npm install node-logger-simple # Or with yarn yarn add node-logger-simple
Manual Installation
Download the App.js
file and require it in your project:
const Logger = require('node-logger-simple'); // Create logger instance const logger = new Logger({ app_id: 'your_app_id', api_key: 'your_api_key' });
Requirements
- Node.js 14.0+ (LTS recommended)
- HTTPS outbound access on port 443
- No external dependencies required
Quick Start
const Logger = require('node-logger-simple'); // Initialize with auto-features enabled const logger = new Logger({ app_id: 'your_app_id', api_key: 'your_api_key', autoHeartbeat: true, enableCrashLogging: true, enableGracefulShutdown: true }); // Wait for ready event logger.on('ready', async () => { console.log('Logger connected and ready!'); // Send various log types await logger.logSuccess('Application started', { version: '1.0.0', environment: process.env.NODE_ENV }); await logger.logInfo('Processing request', { request_id: 'req_123', user_id: 456 }); await logger.logWarning('High memory usage', { memory_usage: process.memoryUsage(), threshold: '512MB' }); await logger.logError('Database connection failed', { database: 'mongodb', error: 'Connection timeout', retry_count: 3 }); await logger.logCritical('Service unavailable', { service: 'payment_processor', downtime_minutes: 2 }); }); // Handle errors logger.on('error', (error) => { console.error('Logger error:', error.message); }); // Handle graceful shutdown process.on('SIGINT', async () => { console.log('Shutting down...'); await logger.shutdown(); process.exit(0); });
Configuration
const logger = new Logger({ app_id: 'your_app_id', api_key: 'your_api_key', // Connection settings timeout: 30000, // Request timeout (ms) retryAttempts: 3, // Retry attempts on failure retryDelay: 1000, // Delay between retries (ms) // Features enableCrashLogging: true, // Auto-capture uncaught errors enableGracefulShutdown: true, // Handle shutdown signals autoHeartbeat: true, // Automatic heartbeat heartbeatInterval: 300000, // Heartbeat interval (ms) // Batch processing batchSize: 100, // Logs per batch flushInterval: 5000, // Batch flush interval (ms) // Limits maxLogLength: 10000, // Max message length // Custom options options: { userAgent: 'MyApp/1.0', customHeader: 'value' } });
Configuration Options
Option | Type | Default | Description |
---|---|---|---|
autoHeartbeat |
boolean | false | Enable automatic heartbeat |
heartbeatInterval |
number | 300000 | Heartbeat interval in milliseconds |
batchSize |
number | 100 | Number of logs per batch |
flushInterval |
number | 5000 | Batch flush interval in milliseconds |
enableGracefulShutdown |
boolean | false | Handle shutdown signals gracefully |
Events
Event System
The logger extends EventEmitter and provides detailed events for monitoring:
// Connection events logger.on('ready', () => { console.log('Logger is ready and connected'); }); logger.on('connected', (response) => { console.log('Connected to API:', response); }); logger.on('error', (error) => { console.error('Logger error:', error.message); }); // Logging events logger.on('logSent', (data) => { console.log(`Log sent: [${data.level}] ${data.message}`); }); logger.on('logError', (data) => { console.error(`Failed to send log: ${data.error.message}`); }); // Heartbeat events logger.on('heartbeat', (response) => { console.log('Heartbeat successful:', response); }); logger.on('heartbeatError', (error) => { console.error('Heartbeat failed:', error.message); }); // Batch events logger.on('batchProcessed', (data) => { console.log(`Batch processed: ${data.count} logs`); }); logger.on('batchError', (error) => { console.error('Batch processing failed:', error.message); }); // Shutdown events logger.on('shutdown', (data) => { if (data.graceful) { console.log('Graceful shutdown completed'); } else { console.error('Shutdown error:', data.error.message); } });
Available Events
Event | Data | Description |
---|---|---|
ready |
- | Logger initialized and connected |
connected |
response | Successfully connected to API |
logSent |
{level, message, result} | Log successfully sent |
logError |
{level, message, error} | Failed to send log |
heartbeat |
response | Heartbeat sent successfully |
shutdown |
{graceful, error?} | Logger shutdown completed |
Advanced Features
Batch Processing
Optimize performance with intelligent log batching:
// Queue logs for batch processing logger.queueLog('info', 'Batch log 1', { batch: true }); logger.queueLog('info', 'Batch log 2', { batch: true }); logger.queueLog('info', 'Batch log 3', { batch: true }); // Manual flush await logger.flushLogs(); // Get queue status const metrics = logger.getMetrics(); console.log(`Queue size: ${metrics.queueSize}`);
Data Retrieval
Retrieve logs and statistics from the API:
// Get recent logs with filters const logs = await logger.getLogs({ limit: 50, page: 1, log_level: 'error', start_date: '2025-01-01', end_date: '2025-01-31', search: 'database' }); console.log(`Found ${logs.logs.length} logs`); logs.logs.forEach(log => { console.log(`[${log.log_level}] ${log.message}`); }); // Get statistics const stats = await logger.getStats(7); // Last 7 days console.log('Statistics:', { total: stats.summary.total_logs, errors: stats.summary.error_logs, today: stats.summary.today_logs });
Graceful Shutdown
// Manual shutdown await logger.shutdown(); // Automatic shutdown on signals (when enableGracefulShutdown: true) // Handles: SIGTERM, SIGINT, SIGUSR2 // Shutdown process: // 1. Stop heartbeat timer // 2. Stop batch processing timer // 3. Flush pending logs // 4. Send final shutdown log // 5. Emit shutdown event
Troubleshooting
Common Issues
Debug Mode
Enable debug mode to troubleshoot connection issues:
// PHP Debug $logger = createLogger('test_app', 'test_key', [ 'timeout' => 5, 'retryAttempts' => 1 ]); if (!$logger->testConnection()) { echo "Connection failed\n"; exit(1); } // Node.js Debug const logger = new Logger({ app_id: 'test_app', api_key: 'test_key', timeout: 5000, retryAttempts: 1 }); logger.on('error', (error) => { console.error('Debug error:', error.message); });