wpdesk/wp-logs

There is no license information available for the latest version (1.13.2) of this package.

Maintainers

Package info

gitlab.wpdesk.dev/wpdesk/wp-logs

pkg:composer/wpdesk/wp-logs

Statistics

Installs: 57 197

Dependents: 5

Suggesters: 1

1.13.2 2024-08-13 10:21 UTC

README

Latest Stable Version Total Downloads License

wp-logs is a modern, flexible logging library for WordPress and WooCommerce plugins. It is fully PSR-3 compliant and built on top of the Monolog 2 library.

The library helps plugin developers seamlessly route log messages to WooCommerce's log system (WC_Logger) or the standard WordPress debug log (debug.log).

Key Features

  • PSR-3 Compliance: Support for standard logging methods (debug, info, warning, error, etc.) and placeholder interpolation (e.g., log('User {username} logged in', ['username' => 'john'])).
  • Automatic WooCommerce Integration: Logs automatically flow into WooCommerce's logger interface (found under WooCommerce -> Status -> Logs) via a dedicated handler.
  • Smart Fallback: If WooCommerce is not active or initialized, the library falls back to the WordPress error log (error_log), provided the WP_DEBUG_LOG constant is enabled.
  • FingersCrossedHandler: Optional log buffering that only writes messages if an error of a specific severity (e.g., error) occurs. This allows you to inspect full debug context for failing requests without cluttering the logs on success.
  • Sensitive Data Masking: Includes a built-in processor to automatically mask sensitive information (such as passwords, API keys, or tokens) before writing logs.
  • Session Tracking: Automatically attaches a unique session identifier (uid) to every log record in a request context, making log tracing straightforward in high-concurrency environments.

Requirements

  • PHP: >= 7.4 or ^8.0
  • WordPress: >= 5.0
  • WooCommerce: >= 3.5.0 (for WC_Logger integration)
  • Monolog: ^2.9.1

Installation

Install the package via Composer:

composer require wpdesk/wp-logs

Inter-plugin Compatibility

In WordPress environments, multiple plugins may load the same library in different versions. To avoid version conflicts, we strongly recommend using a solution like wpdesk/wp-autoloader or a similar dependency isolation mechanism.

Usage

1. Basic Logging (SimpleLoggerFactory)

SimpleLoggerFactory is the recommended factory for creating logger instances.

use WPDesk\Logger\SimpleLoggerFactory;

// Initialize the factory with your plugin's channel name
$factory = new SimpleLoggerFactory('my-plugin-channel');

// Get the PSR-3 (Monolog) logger instance
$logger = $factory->getLogger();

// Log messages with different severity levels
$logger->debug('This is a diagnostic debug message');
$logger->info('User performed action {action}', ['action' => 'export']);
$logger->warning('Warning: Something went wrong, but we can recover.');
$logger->error('An error occurred while communicating with the API.');

2. Advanced Logging with FingersCrossedHandler

If you want to keep logs clean under normal circumstances but need full context when errors occur, use the action_level option:

use WPDesk\Logger\SimpleLoggerFactory;
use Psr\Log\LogLevel;

$options = [
    'level'        => LogLevel::DEBUG,  // Minimum log level for buffered records
    'action_level' => LogLevel::ERROR,  // Buffer will only flush to logs if a message of this level or higher is logged
];

$factory = new SimpleLoggerFactory('my-plugin-channel', $options);
$logger = $factory->getLogger();

// The following messages are kept in memory and won't write to disk yet...
$logger->debug('Started processing order...');
$logger->info('Fetched data from database.');

// ...until an error occurs.
// When an ERROR (or higher) is logged, the ENTIRE buffer (including debug & info) is flushed to the log file!
$logger->error('Failed to write order to the database!');

3. Masking Sensitive Data (SensitiveDataProcessor)

Prevent credentials and API tokens from leaking into files using SensitiveDataProcessor:

use WPDesk\Logger\SimpleLoggerFactory;
use WPDesk\Logger\Processor\SensitiveDataProcessor;

$factory = new SimpleLoggerFactory('my-plugin-channel');
$logger = $factory->getLogger();

// Set up the processor with a mapping of search values to masked values
$sensitiveProcessor = new SensitiveDataProcessor([
    'super-secret-token' => '***MASKED_TOKEN***',
    'my_private_password' => '***MASKED_PASSWORD***'
]);

// Register the processor with Monolog
$logger->pushProcessor($sensitiveProcessor);

// Log message with sensitive information
$logger->info('Logging API key: super-secret-token');
// Output in log file: "Logging API key: ***MASKED_TOKEN***"

Legacy and Deprecated Methods (Backward Compatibility)

WPDeskLoggerFactory and LoggerFacade

The WPDeskLoggerFactory and LoggerFacade classes are deprecated since version 1.13.0. They write log entries to a shared file in /wp-content/uploads/wpdesk-logs/wpdesk_debug.log, which can lead to performance bottlenecks, write permission issues, and security vulnerabilities.

If your plugin still uses the legacy facades:

use WPDesk\Logger\LoggerFacade;

// Deprecated message logging
LoggerFacade::log_message('My debug message', [], 'source', \Psr\Log\LogLevel::DEBUG);

// Deprecated WP_Error / Exception logging
try {
    // some code...
} catch (\Exception $e) {
    LoggerFacade::log_exception($e);
}

Recommendation: Migrate your codebase to use the PSR-3 logger provided by SimpleLoggerFactory.

Running Tests

The library contains unit and integration tests. PHPUnit is required to run the test suites.

To run the unit tests:

composer phpunit-unit

To run the fast unit tests (without code coverage):

composer phpunit-unit-fast

To run the integration tests:

composer phpunit-integration

License

This project is licensed under the MIT License. See LICENSE.md for details.