PHP code example of kevinpirnie / kpt-logger

1. Go to this page and download the library: Download kevinpirnie/kpt-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/ */

    

kevinpirnie / kpt-logger example snippets


use KPT\Logger;

// Enable logging with stack traces
$logger = new Logger(true, true);

// Enable logging without stack traces
$logger = new Logger(true, false);

// Disable logging (errors still log)
$logger = new Logger(false);

// Log an error (always logs, even when disabled)
Logger::error("Database connection failed");

// Log a warning (only when enabled)
Logger::warning("API rate limit approaching");

// Log info (only when enabled)
Logger::info("User successfully logged in");

// Log debug info (only when enabled)
Logger::debug("Processing user data", ['user_id' => 123]);

// You can also use the shorter LOG alias
LOG::error("Something went wrong!");
LOG::info("Operation completed");

// Log to a custom file
Logger::setLogFile('/var/log/myapp.log');

// Log to system log (default)
Logger::setLogFile(null);

// Include additional context data
Logger::error("Payment processing failed", [
    'user_id' => 456,
    'amount' => 99.99,
    'transaction_id' => 'txn_123456'
]);

// Override stack trace setting per call
Logger::debug("Debugging info", [], false); // No stack trace
Logger::error("Critical error", [], true);  // Force stack trace

try {
    // Some risky operation
    $result = riskyOperation();
} catch (Exception $e) {
    Logger::error("Operation failed: " . $e->getMessage(), [
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
}

// Track user actions
Logger::info("User login", ['user_id' => $userId, 'ip' => $_SERVER['REMOTE_ADDR']]);

// Monitor performance
$start = microtime(true);
processData();
$duration = microtime(true) - $start;

Logger::debug("Data processing completed", ['duration' => $duration]);

// Log API calls
Logger::info("Making API request", ['endpoint' => $url, 'method' => 'POST']);

if ($response->getStatusCode() !== 200) {
    Logger::warning("API returned non-200 status", [
        'status' => $response->getStatusCode(),
        'body' => $response->getBody()
    ]);
}

// Set up file logging with error handling
if (!Logger::setLogFile('/var/log/myapp.log')) {
    // Fallback to system log if file setup fails
    Logger::setLogFile(null);
    Logger::warning("Could not set custom log file, using system log");
}