Logger

Introduction

The Logger class in JiFramework provides a robust and flexible logging system for your application. It allows you to record messages at various severity levels to log files, aiding in debugging, monitoring, and auditing. The class supports log rotation based on file size, maintains a specified number of log files, and can be configured to suit different environments and requirements.

By using the Logger class, developers can systematically capture important events and errors, making it easier to diagnose issues and understand the application's behavior over time.

Configuration

By default, the Logger class comes pre-configured with standard logging settings in the Config class. However, you're free to modify these settings to better suit your specific requirements.

Configuration Options:

namespace JIFramework\Config;

class Config {
    // Enable or disable logging
    const LOG_ENABLED = true;

    // Logging level ('DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY')
    const LOG_LEVEL = 'DEBUG';

    // Path to the log file directory (ensure it exists and is writable)
    const LOG_FILE_PATH = __DIR__ . '/../Logs/';

    // Log file name
    const LOG_FILE_NAME = 'app.log';

    // Maximum size of a log file in bytes before rotation (e.g., 5MB)
    const LOG_MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB

    // Maximum number of log files to keep after rotation
    const LOG_MAX_FILES = 5;
}

Explanation:

  • LOG_ENABLED (bool): Enables or disables logging functionality.
  • LOG_LEVEL (string): Sets the minimum severity level of messages to log. Messages below this level will be ignored.
  • LOG_FILE_PATH (string): Specifies the directory where log files will be stored.
  • LOG_FILE_NAME (string): The name of the log file.
  • LOG_MAX_FILE_SIZE (int): Maximum size in bytes of a single log file before it is rotated.
  • LOG_MAX_FILES (int): Number of rotated log files to keep. Older files beyond this limit will be deleted.

__construct()

Method: __construct(string $logFilePath = null)

Description: Initializes the Logger instance, sets up the logging configuration, and opens the log file for writing.

Parameters:

  • $logFilePath (string, optional): Custom path to the log file. If null, the default path from the configuration is used.

Throws:

  • Exception
  • If logging is enabled but the log file cannot be opened for writing.

Usage:


// Option 1: Initialize the Logger through the App
use JIFramework\Core\App\App;
$app = new App();
$logger = $app->logger;

// Option 2: Directly instantiate the Logger
use JIFramework\Core\Logger\Logger;
$logger = new Logger('/path/to/custom/logfile.log');

Explanation:

  • Option 1: Initializes the App class and retrieves the Logger instance through it, using the framework's main entry point.
  • Option 2: Directly creates a Logger instance, optionally specifying a custom log file path.

log()

Method: log(string $level, string $message, array $context = []): void

Description: Logs a message with a specified severity level, interpolating context values into the message.

Parameters:

  • $level (string): The severity level of the message (e.g., 'DEBUG', 'ERROR').
  • $message (string): The log message, which may include placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->log('INFO', 'User {username} logged in.', ['username' => 'john_doe']);

Explanation:

  • Validates the provided log level; defaults to 'DEBUG' if invalid.
  • Checks if the message's severity meets the current log level threshold.
  • Interpolates context values into the message.
  • Formats the log entry according to the specified log format.
  • Writes the log entry to the log file.

debug()

Method: debug(string $message, array $context = []): void

Description: Logs a message at the 'DEBUG' level.

Parameters:

  • $message (string): The log message.
  • $context (array, optional): Context values for placeholders.

Returns: void

Usage:

$logger->debug('Debugging data: {data}', ['data' => $debugData]);

Explanation:

  • Convenience method that calls log('DEBUG', $message, $context).

info()

Method: info(string $message, array $context = []): void

Description: Logs a message at the 'INFO' level.

Parameters:

  • $message (string): The log message, which may include placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->info('User {username} registered.', ['username' => 'jane_doe']);

Explanation:

  • Convenience method that calls log('INFO', $message, $context).

notice()

Method: notice(string $message, array $context = []): void

Description: Logs a message at the 'NOTICE' level.

Parameters:

  • $message (string): The log message, which may include placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->notice('Password reset requested for user {email}.', ['email' => '[email protected]']);

Explanation:

  • Convenience method that calls log('NOTICE', $message, $context).

warning()

Method: warning(string $message, array $context = []): void

Description: Logs a message at the 'WARNING' level.

Parameters:

  • $message (string): The log message, which may include placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->warning('Disk space low: {freeSpace} MB remaining.', ['freeSpace' => 200]);

Explanation:

  • Convenience method that calls log('WARNING', $message, $context).

error()

Method: error(string $message, array $context = []): void

Description: Logs a message at the 'ERROR' level.

Parameters:

  • $message (string): The log message, which may include placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->error('Failed to send email to {email}.', ['email' => '[email protected]']);

Explanation:

  • Convenience method that calls log('ERROR', $message, $context).

critical()

Method: critical(string $message, array $context = []): void

Description: Logs a message at the 'CRITICAL' level.

Parameters:

  • $message (string): The log message, which may include placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->critical('Database connection failed: {error}', ['error' => $errorMessage]);

Explanation:

  • Convenience method that calls log('CRITICAL', $message, $context).

alert()

Method: alert(string $message, array $context = []): void

Description: Logs a message at the 'ALERT' level.

Parameters:

  • $message (string): The log message, potentially containing placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->alert('Application configuration missing critical settings.');

Explanation:

  • Convenience method that calls log('ALERT', $message, $context).

emergency()

Method: emergency(string $message, array $context = []): void

Description: Logs a message at the 'EMERGENCY' level.

Parameters:

  • $message (string): The log message, potentially containing placeholders for context values.
  • $context (array, optional): An associative array of context values to replace placeholders in the message.

Returns: void

Usage:

$logger->emergency('System is unusable: {details}', ['details' => $details]);

Explanation:

  • Convenience method that calls log('EMERGENCY', $message, $context).

setLogFile()

Method: setLogFile(string $logFilePath): void

Description: Sets a custom log file path and reopens the log file accordingly.

Parameters:

  • $logFilePath (string): The new path to the log file.

Throws:

  • Exception: If the log file cannot be opened.

Returns: void

Usage:

$logger->setLogFile('/path/to/new/logfile.log');

Explanation:

  • Closes the current log file if it's open.
  • Sets the new log file path.
  • Ensures the directory exists.
  • Opens the new log file for appending messages.

__destruct()

Method: __destruct()

Description: Closes the log file handle when the Logger object is destroyed.

Parameters: None

Returns: void

Usage:

  • Automatically called by PHP's garbage collector when the object is no longer in use.

Explanation:

  • Ensures that the file handle is properly closed to prevent resource leaks.