
CustomLogger
April 23, 2024
CustomLogger
A lightweight PHP logging utility I developed that provides flexible logging capabilities with WordPress integration. It implements a singleton pattern for global access and includes features like stack trace logging and custom error handling.
What It Does
- Provides multiple logging levels (INFO, WARN, ERROR, FATAL, TRACE, DEBUG)
- Implements stack trace logging for debugging
- Integrates seamlessly with WordPress
- Handles PHP errors and exceptions automatically
- Supports file-based logging with customizable paths
How It Works
The logger uses a singleton pattern to ensure a single instance throughout the application. It formats log messages with timestamps, user information, and appropriate stack traces based on the logging level.
// Example of logging levels
class LoggingLevel {
const INFO = 'INFO';
const WARN = 'WARN';
const ERROR = 'ERROR';
const FATAL = 'FATAL';
const TRACE = 'TRACE';
const DEBUG = 'DEBUG';
}
// Example of logger usage
$logger = CustomLogger::getInstance('/path/to/logfile.log');
$logger->log("This is an info message"); // Default level is INFO
$logger->log("This is a warning", LoggingLevel::WARN);
$logger->log("This is an error", LoggingLevel::ERROR);
Technical Bits
- Implemented using PHP's object-oriented features
- Uses singleton design pattern for global access
- Integrates with WordPress user system
- Implements custom error and exception handlers
- Supports array and object logging
- Includes stack trace and error trace functionality
Features
- Multiple Log Levels: Support for 6 different severity levels
- WordPress Integration: Automatic user tracking and plugin support
- Stack Trace Logging: Detailed debugging information for TRACE, ERROR, and FATAL levels
- Custom Error Handling: Automatic logging of PHP errors and exceptions
- Session-based Error Tracking: Prevents duplicate error logging
Why I Built It
I needed a flexible logging solution for WordPress projects that could handle different types of errors and provide detailed debugging information. This logger helps track issues and maintain application stability.
Future Ideas
- Add log rotation functionality
- Implement log level filtering
- Add support for different log formats (JSON, XML)
- Create a log viewer interface
- Add email notifications for critical errors
- Implement log compression