Comprehensive PHP Logger with Email Notifications | Critical Error Tracking in PHP (3 Step)

PHP Logger with Email Notifications: This tutorial demonstrates how to create a powerful PHP logger…

Topics: PHP, Logging, Email Notifications, Error Handling, Web Development, PHP File Logging, Critical Error Handling, PHP Tutorials, PHP Best Practices, Software Development


1. PHP Logger with Email Notifications: Features and Implementation

This PHP logger writes logs to a file and sends email notifications for critical issues. It includes a flexible configuration, supports custom severity levels, and demonstrates best practices for file handling and error notifications in PHP.


2. Requirements Analysis

  • Purpose: Create a logging system that writes logs to a file and sends email notifications for critical errors.
  • Features:
    1. Log messages to a file with timestamps and severity levels.
    2. Notify via email for “ERROR” or “CRITICAL” logs.
    3. Configurable log file path and email settings.
  • Input: Log messages with severity (INFO, WARNING, ERROR, CRITICAL).
  • Output:
    • Log entries stored in a file.
    • Emails sent for critical issues.
  • Constraints:
    • Use only PHP-compatible syntax.
    • Handle errors gracefully to avoid application crashes.

3. File Structure

project/
│
├── logger/
│   ├── Logger.php         # Core PHP Logger class
│   ├── config.php         # Configuration for email and file paths
│
├── logs/
│   └── app.log            # Example log file (generated dynamically)
│
└── index.php              # Example usage of the PHP Logger

4. Step-by-Step Guide for Creating a PHP Logger

4.1 Configuration (config.php)

<?php
return [
    'log_file' => __DIR__ . '/../logs/app.log',
    'email' => [
        'enabled' => true,
        'to' => 'admin@example.com',
        'from' => 'logger@example.com',
        'subject' => 'Critical Error Notification',
        'smtp_host' => 'smtp.example.com',
        'smtp_port' => 587,
        'smtp_user' => 'user@example.com',
        'smtp_pass' => 'password',
    ],
];

4.2 PHP Logger Class (Logger.php)

<?php

class Logger
{
    private $config;
    private $logFile;

    public function __construct($config)
    {
        $this->config = $config;
        $this->logFile = $config['log_file'];
        if (!file_exists(dirname($this->logFile))) {
            mkdir(dirname($this->logFile), 0777, true);
        }
    }

    public function log($message, $severity = 'INFO')
    {
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = "[$timestamp] [$severity] $message" . PHP_EOL;

        // Write to log file
        file_put_contents($this->logFile, $logEntry, FILE_APPEND);

        // Send email for critical errors
        if (in_array($severity, ['ERROR', 'CRITICAL']) && $this->config['email']['enabled']) {
            $this->sendEmailNotification($message, $severity);
        }
    }

    private function sendEmailNotification($message, $severity)
    {
        $emailConfig = $this->config['email'];
        $subject = $emailConfig['subject'] . " ($severity)";
        $body = "A critical issue occurred:nn$message";

        // Basic email headers
        $headers = "From: " . $emailConfig['from'];

        // Sending email (simple PHP mail function for demonstration)
        mail($emailConfig['to'], $subject, $body, $headers);
    }
}

4.3 Example Usage (index.php)

<?php

require_once 'logger/Logger.php';

$config = require 'logger/config.php';
$logger = new Logger($config);

// Log messages
$logger->log("This is an informational message.", 'INFO');
$logger->log("This is a warning message.", 'WARNING');
$logger->log("This is an error message.", 'ERROR');
$logger->log("Critical system failure!", 'CRITICAL');

5. Explanation

  1. Configuration (config.php):
    • Stores file path and email settings.
    • Ensures flexibility for changing email or log paths.
  2. PHP Logger Class (Logger.php):
    • Handles logging of messages with timestamps and severity levels.
    • Sends emails for errors and critical logs using PHP’s mail() function.
    • Creates log directories if they don’t exist.
  3. Example Usage (index.php):
    • Demonstrates how to use the PHP Logger class to log messages of various severities.
  4. PHP Logger Class:
    • Contains methods for logging messages to a file and sending email notifications.
    • Log levels (INFO, WARNING, ERROR, etc.) categorize the messages for better debugging.
  5. log() Method:
    • Appends log entries to the specified file.
    • Sends an email notification for ERROR or FATAL levels when enabled.
  6. sendEmail() Method:
    • Uses PHP’s mail() function to send email notifications.
    • Can be replaced with PHPMailer for more robust email handling.

6. Enhancements (Optional)

  1. Add SMTP Support:
    Use the PHPMailer library for more robust email notifications.
  2. Log Rotation
    Prevent log files from growing indefinitely.

    private function rotateLog()
    {
        if (file_exists($this->logFile) && filesize($this->logFile) > 1024 * 1024) { // 1MB limit
            $backupFile = $this->logFile . '.' . time();
            rename($this->logFile, $backupFile);
        }
    }

    Call rotateLog() at the start of the log() method.

  3. Verify the Log File
    Check the contents of the app.log file for the logged messages. It should look like this:
[2024-11-28 12:34:56] [INFO]: Application started successfully.
[2024-11-28 12:35:10] [WARNING]: Memory usage is high.
[2024-11-28 12:35:30] [CRITICAL]: Database connection failed!
  1. Database Logging:
    Store logs in a database for better querying and analysis.
  2. Improving the PHP Logger (Optional)
    Enhance the php logger by adding features like:

    • Logging to a database instead of a file.
    • Including stack traces for errors.
    • Adding support for other notification channels (e.g., SMS, Slack).

    Example: Logging to a Database

    // Additional method in PHP Logger class for database logging
    private function logToDatabase($level, $message) {
        $pdo = new PDO('mysql:host=localhost;dbname=log_db', 'root', '');
        $stmt = $pdo->prepare("INSERT INTO logs (level, message, created_at) VALUES (:level, :message, NOW())");
        $stmt->execute(['level' => $level, 'message' => $message]);
    }

    Modify the log() method to include database logging:

    public function log($level, $message) {
        $timestamp = date("Y-m-d H:i:s");
        $logMessage = "[$timestamp] [$level]: $message" . PHP_EOL;
    
        // Write to log file
        file_put_contents($this->logFile, $logMessage, FILE_APPEND);
    
        // Log to database
        $this->logToDatabase($level, $message);
    
        // Send email for critical errors
        if ($level === 'CRITICAL') {
            $this->sendEmail($logMessage);
        }
    }
  3. Customizable Severity Levels:
    Allow users to specify which log levels trigger email notifications.

    'email_notifications' => [
        'enabled' => true,
        'levels' => ['ERROR', 'FATAL'], // Add this key
        ...
    ]

    Modify the email logic to check against levels.

  4. Use PHPMailer for EmailsFor more reliable email delivery, replace the mail() function:
    use PHPMailerPHPMailerPHPMailer;
    
    private function sendEmail($message)
    {
        $mail = new PHPMailer(true);
        $mail->setFrom($this->emailConfig['from']);
        $mail->addAddress($this->emailConfig['to']);
        $mail->Subject = $this->emailConfig['subject'];
        $mail->Body = $message;
    
        $mail->send();
    }
  5. Email Notification
    For critical errors, ensure that the admin receives an email with the error message. The email should contain the following information:Subject:

    Critical Error Notification

    Body:

    [2024-11-28 12:35:30] [CRITICAL]: Database connection failed!
  6. JSON Logs:
    Format logs as JSON for structured logging.

7. Conclusion

Creating a custom php logger with email notifications enhances error tracking and system monitoring. The solution is simple yet extensible, allowing for future enhancements like SMTP integration or log rotation. This demonstrates how PHP can effectively handle both file-based logging and email notifications.


DoFollow

Stay Connected!

  • Connect with me on LinkedIn to discuss ideas or projects.
  • Check out my Portfolio for exciting projects.
  • Give my GitHub repositories a star ⭐ on GitHub if you find them useful!

Your support and feedback mean a lot! 😊

If you need any support regarding your website

If you like our blog, Please support us to improve

Buy Me a Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *

RECENT POST
Leetcode Solutions

633. Sum of Square Numbers

Sum of Square Numbers Difficulty: Medium Topics: Math, Two Pointers, Binary Search Given a non-negative integer c, decide whether there’re

Leetcode Solutions

624. Maximum Distance in Arrays

Maximum Distance in Arrays Difficulty: Medium Topics: Array, Greedy You are given m arrays, where each array is sorted in

Leetcode Solutions

592. Fraction Addition and Subtraction

Fraction Addition and Subtraction Difficulty: Medium Topics: Math, String, Simulation Given a string expression representing an expression of fraction addition