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
Table of Contents
Toggle1. 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:
- Log messages to a file with timestamps and severity levels.
- Notify via email for “ERROR” or “CRITICAL” logs.
- 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
- Configuration (
config.php
):- Stores file path and email settings.
- Ensures flexibility for changing email or log paths.
- 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.
- Example Usage (
index.php
):- Demonstrates how to use the PHP Logger class to log messages of various severities.
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.
log()
Method:- Appends log entries to the specified file.
- Sends an email notification for
ERROR
orFATAL
levels when enabled.
sendEmail()
Method:- Uses PHP’s
mail()
function to send email notifications. - Can be replaced with PHPMailer for more robust email handling.
- Uses PHP’s
6. Enhancements (Optional)
- Add SMTP Support:
Use the PHPMailer library for more robust email notifications. - 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 thelog()
method. - Verify the Log File
Check the contents of theapp.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!
- Database Logging:
Store logs in a database for better querying and analysis. - 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); } }
- 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
. - 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(); }
- 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!
- 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
- Streamline Laravel Naming Conventions: 10 Steps to Clean and Maintainable Code
- PHP Best Practices: Secure Your Web Applications with 10 Essential Step
- Laravel CI/CD Pipeline: Easy GitHub, Jenkins, and Docker Step-by-Step Guide (5 Step)
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! 😊