1. Go to this page and download the library: Download antlerops/error-logger library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
antlerops / error-logger example snippets
use Antler\ErrorLogger\Logger;
use Antler\ErrorLogger\LoggerConfig;
use Antler\ErrorLogger\LogLevel;
// Quick setup with minimal configuration
$config = new LoggerConfig([
'project_hash' => 'your-project-identifier',
'remote_endpoint' => 'LOCAL_DOMAIN/api/log/rec'
]);
$logger = Logger::getInstance($config);
// Log examples
$logger->debug('SQL query executed', ['query' => $sql, 'duration' => $queryTime]);
$logger->info('User logged in', ['user_id' => $userId]);
$logger->warning('Deprecated feature used', ['feature' => 'oldApi']);
$logger->error('Payment failed', ['order_id' => $orderId, 'amount' => $amount]);
$logger->critical('System is out of disk space');
// Exceptions are automatically captured by the global handler
// but you can also log caught exceptions with full context
try {
// Your code
} catch (Exception $e) {
$logger->error('Caught exception', [
'exception' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode()
]);
}
try {
throw new Exception("Something went wrong");
} catch (Exception $e) {
$logger->error("Caught exception", ["exception" => $e]);
}
LogLevel::DEBUG // 100 - Detailed information for debugging
LogLevel::INFO // 200 - Interesting events in your application
LogLevel::WARNING // 300 - Non-error but potentially problematic situations
LogLevel::ERROR // 400 - Runtime errors that don't
// Set default tags for all logs
$logger->setDefaultTags(['app:api', 'env:production']);
// Log with specific tags
$logger->error("Payment failed", [
'order_id' => 12345,
'tags' => ['module:payments', 'customer:premium']
]);
// Result will
// All logs created in the same request will share the same request_id
$logger->info("Processing started");
$logger->debug("Query executed", ['query' => $sql]);
$logger->info("Processing completed");
// For web requests, any existing X-Request-ID header will be used as the request ID
// Start a timer
$logger->startTimer('database_query');
// Run database query
$results = $db->query($sql);
// Stop timer and log results
$logger->stopTimer('database_query', 'User search query completed', [
'query' => $sql,
'result_count' => count($results)
]);
// Log output will
// Push user context
$logger->pushContext(['user_id' => 123, 'role' => 'admin']);
// Log something with this context automatically 'user_update']);
// This log will have both user and operation context
$logger->info('Changed user email', ['old_email' => '[email protected]', 'new_email' => '[email protected]']);
// Pop operation context when done
$logger->popContext();
// This log will only have the user context
$logger->info('Admin panel exited');
// Pop user context
$logger->popContext();
// Configure log sampling (log 10% of entries)
$config = new LoggerConfig([
'project_hash' => 'your-project',
'sampling_rate' => 0.1, // Log 10% of entries
]);
// Configure circuit breaker (stop logging errors after threshold reached)
$config = new LoggerConfig([
'project_hash' => 'your-project',
'circuit_breaker_threshold' => 100, // Open circuit after 100 errors per minute
'circuit_breaker_cooldown' => 60, // Keep circuit open for 60 seconds
]);
$logger = Logger::getInstance($config);
$config = new LoggerConfig([
'project_hash' => 'your-project'
]);
// Add a message pattern filter (regex)
$config->addMessageFilter('/^Cache miss for key/');
// Add a context key/value filter (exact match)
$config->addContextFilter('status_code', 404);
// Add a context regex filter
$config->addContextFilter('url', '/\.jpg$/', true);
$logger = Logger::getInstance($config);
$config = new LoggerConfig([
'project_hash' => 'your-project',
'remote_endpoint' => 'https://your-log-endpoint.com',
'async_processing' => true
]);
$logger = Logger::getInstance($config);
// Logs will be sent asynchronously without blocking
$logger->info("User registered", ['user_id' => $userId]);
// For local development, keep file logging but disable remote
$logger = Logger::getInstance(new LoggerConfig([
'project_hash' => 'dev-project',
'use_remote_logging' => false,
'log_file_path' => __DIR__ . '/logs/dev.log',
'min_log_level' => LogLevel::DEBUG
]));
// For high-traffic production, focus on performance
$logger = Logger::getInstance(new LoggerConfig([
'project_hash' => 'prod-project',
'remote_endpoint' => 'LOCAL_DOMAIN/api/log/rec',
'min_log_level' => LogLevel::ERROR,
'use_file_logging' => false, // Skip file logging for performance
'rate_limit_per_minute' => 200, // Higher rate limit
'request_timeout' => 1, // Lower timeout to prevent blocking
'sampling_rate' => 0.2, // Sample 20% of all logs
'async_processing' => true // Async processing for better performance
]));
use Antler\ErrorLogger\Logger;
use Antler\ErrorLogger\LoggerConfig;
use Antler\ErrorLogger\LogLevel;
// In any controller, middleware, or service
// Initialize once with your configuration (in a bootstrap file or service provider)
$config = new LoggerConfig([
'project_hash' => env('ANTLER_PROJECT_HASH', 'your-project-identifier'),
'remote_endpoint' => env('ANTLER_LOG_ENDPOINT', 'https://your-log-endpoint.com'),
'log_file_path' => storage_path('logs/antler.log'),
'min_log_level' => LogLevel::WARNING,
]);
// Get the singleton instance
$logger = Logger::getInstance($config);
// Then use it anywhere in your application
Logger::getInstance()->info('User logged in', ['user_id' => auth()->id()]);
Logger::getInstance()->error('Payment failed', ['order_id' => $orderId]);
// app/Providers/LoggingServiceProvider.php
namespace App\Providers;
use Antler\ErrorLogger\Logger;
use Antler\ErrorLogger\LoggerConfig;
use Antler\ErrorLogger\LogLevel;
use Illuminate\Support\ServiceProvider;
class LoggingServiceProvider extends ServiceProvider
{
public function register()
{
// Configuration for the Antler Error Logger
$config = new LoggerConfig([
'project_hash' => env('ANTLER_PROJECT_HASH'),
'remote_endpoint' => env('ANTLER_LOG_ENDPOINT'),
'log_file_path' => storage_path('logs/antler.log'),
'min_log_level' => $this->getLogLevel(),
'use_remote_logging' => env('ANTLER_LOG_USE_REMOTE_LOGGING', true),
'use_file_logging' => env('ANTLER_LOG_USE_FILE_LOGGING', true),
'use_error_log' => env('ANTLER_LOG_USE_ERROR_LOG', true),
'rate_limit_per_minute' => env('ANTLER_LOG_RATE_LIMIT_PER_MINUTE', 60),
'sampling_rate' => env('ANTLER_LOG_SAMPLING_RATE', 1.0),
'circuit_breaker_threshold' => env('ANTLER_LOG_CIRCUIT_BREAKER_THRESHOLD', 0),
'async_processing' => env('ANTLER_LOG_ASYNC_PROCESSING', false),
]);
// Initialize the logger singleton
Logger::getInstance($config);
}
/**
* Convert environment log level to LogLevel constant
*/
private function getLogLevel()
{
$level = strtoupper(env('ANTLER_LOG_MIN_LOG_LEVEL', 'WARNING'));
$levels = [
'DEBUG' => LogLevel::DEBUG,
'INFO' => LogLevel::INFO,
'WARNING' => LogLevel::WARNING,
'ERROR' => LogLevel::ERROR,
'CRITICAL' => LogLevel::CRITICAL
];
return $levels[$level] ?? LogLevel::WARNING;
}
}
'providers' => [
// Other providers...
App\Providers\LoggingServiceProvider::class,
],
// app/Exceptions/Handler.php
namespace App\Exceptions;
use Antler\ErrorLogger\Logger;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
// ... other methods ...
/**
* Report or log an exception.
*
* @param \Throwable $e
* @return void
*/
public function report(Throwable $e)
{
// Log the exception with Antler Error Logger
Logger::getInstance()->error('Uncaught exception', [
'exception_class' => get_class($e),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'exception' => $e, // The Logger will extract the enhanced stack trace
]);
parent::report($e);
}
}