PHPackages                             arraypress/wp-logger - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. arraypress/wp-logger

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

arraypress/wp-logger
====================

A simple, lean logging library for WordPress plugins and themes with registry pattern support.

114PHP

Since Nov 27Pushed 5mo agoCompare

[ Source](https://github.com/arraypress/wp-logger)[ Packagist](https://packagist.org/packages/arraypress/wp-logger)[ RSS](/packages/arraypress-wp-logger/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

WordPress Logger
================

[](#wordpress-logger)

A simple, lean logging library for WordPress plugins and themes with smart defaults and registry pattern support. Zero-config initialization that automatically follows WordPress debug conventions.

Features
--------

[](#features)

- 🚀 **Zero Configuration**: Works immediately with WordPress debug settings
- 📦 **Registry Pattern**: Centralized logger management across plugins
- 🎯 **Smart Defaults**: Automatically follows `WP_DEBUG` - no boilerplate needed
- 📝 **Standard Log Levels**: Error, warning, info, and debug logging
- 🔒 **Automatic Security**: Built-in .htaccess and index.php protection
- 🐛 **Exception Handling**: Native support for exceptions and WP\_Error objects
- 📂 **Flexible Paths**: Use simple filenames or full paths
- ⚡ **Lightweight**: Minimal, focused code
- 🎛️ **Plugin-Specific Control**: Enable debugging per plugin via wp-config.php

Requirements
------------

[](#requirements)

- PHP 7.4 or later
- WordPress 5.0 or later

Installation
------------

[](#installation)

```
composer require arraypress/wp-logger
```

Basic Usage
-----------

[](#basic-usage)

### Using the Registry (Recommended)

[](#using-the-registry-recommended)

```
// Register once in your main plugin file
// Creates: wp-content/uploads/my-plugin/my-plugin.log
register_logger( 'my-plugin' );

// Get and use anywhere in your plugin
$logger = get_logger( 'my-plugin' );
$logger->error( 'Payment processing failed' );
$logger->warning( 'Low inventory alert' );
$logger->info( 'Order processed successfully' );
$logger->debug( 'Debug information' );
```

### Direct Instantiation

[](#direct-instantiation)

```
use ArrayPress\Logger\Logger;

// Create directly if you prefer
// Creates: wp-content/uploads/my-plugin/my-plugin.log
$logger = new Logger( 'my-plugin' );

// Start logging
$logger->error( 'Payment processing failed' );
$logger->info( 'Order processed successfully' );
```

### Custom Configuration

[](#custom-configuration)

```
// Custom filename within plugin directory
// Creates: wp-content/uploads/my-plugin/errors.log
register_logger( 'my-plugin', [
    'log_file' => 'errors.log'
] );

// Multiple loggers for different purposes
register_logger( 'my-plugin' );           // → uploads/my-plugin/my-plugin.log
register_logger( 'my-plugin-api', [
    'log_file' => 'api.log'                // → uploads/my-plugin-api/api.log
] );
register_logger( 'my-plugin-payments', [
    'log_file' => 'payments.log'           // → uploads/my-plugin-payments/payments.log
] );

// Full path override
register_logger( 'my-plugin', [
    'log_file' => WP_CONTENT_DIR . '/logs/custom.log'
] );

// Force enable logging regardless of WP_DEBUG
register_logger( 'my-plugin', [
    'enabled' => true
] );
```

Smart Debug Control
-------------------

[](#smart-debug-control)

The logger automatically detects debug settings in this order:

1. **Plugin-specific constant** (if defined)
2. **WP\_DEBUG constant** (WordPress standard)

### Via wp-config.php

[](#via-wp-configphp)

```
// Enable debugging for specific plugin only
define( 'MY_PLUGIN_DEBUG', true );

// Or use WordPress debug (affects all loggers using defaults)
define( 'WP_DEBUG', true );
```

Plugin Integration Pattern
--------------------------

[](#plugin-integration-pattern)

```
namespace MyPlugin;

use function ArrayPress\Logger\register_logger;
use function ArrayPress\Logger\get_logger;

class Plugin {

    public function __construct() {
        // Register logger once
        // Creates: wp-content/uploads/my-plugin/my-plugin.log
        register_logger( 'my-plugin' );
    }

    public function process_order( $order_data ) {
        $logger = get_logger( 'my-plugin' );
        $logger->info( 'Processing order', ['order_id' => $order_data['id']] );

        try {
            // Process order logic
            $logger->info( 'Order processed successfully' );
        } catch ( Exception $e ) {
            $logger->exception( $e, ['order_data' => $order_data] );
            throw $e;
        }
    }
}
```

### Creating Plugin Wrapper Functions (Optional)

[](#creating-plugin-wrapper-functions-optional)

For convenience, you can create wrapper functions in your plugin:

```
namespace MyPlugin;

use ArrayPress\Logger\Logger;
use function ArrayPress\Logger\get_logger;

function logger(): ?Logger {
    return get_logger( 'my-plugin' );
}

function log_error( string $message, array $context = [] ): void {
    logger()?->error( $message, $context );
}

function log_info( string $message, array $context = [] ): void {
    logger()?->info( $message, $context );
}

// Usage anywhere in your plugin
\MyPlugin\log_error( 'Database connection failed' );
\MyPlugin\log_info( 'Cache cleared successfully' );
```

Exception and Error Handling
----------------------------

[](#exception-and-error-handling)

### Exceptions

[](#exceptions)

```
try {
    process_payment( $data );
} catch ( Exception $e ) {
    $logger->exception( $e, ['user_id' => 123] );
    // Automatically logs message, file, line, and stack trace
}
```

### WordPress Errors

[](#wordpress-errors)

```
$result = wp_remote_get( $url );

if ( is_wp_error( $result ) ) {
    $logger->wp_error( $result, ['url' => $url] );
    // Automatically logs error code, message, and data
}
```

### Context Data

[](#context-data)

```
$logger->error( 'Database connection failed', [
    'host'     => DB_HOST,
    'database' => DB_NAME,
    'user_id'  => get_current_user_id(),
    'memory'   => memory_get_usage()
] );
```

Configuration Options
---------------------

[](#configuration-options)

OptionTypeDefaultDescription`enabled`boolFollows `{PLUGIN}_DEBUG` or `WP_DEBUG`Whether logging is enabled`log_file`string`uploads/{plugin-name}/{plugin-name}.log`Log file path or filenameFile Locations
--------------

[](#file-locations)

Default location pattern:

```
wp-content/uploads/{plugin-name}/{plugin-name}.log

```

Examples:

- `sugarcart` → `wp-content/uploads/sugarcart/sugarcart.log`
- `my-plugin` → `wp-content/uploads/my-plugin/my-plugin.log`
- `woocommerce` → `wp-content/uploads/woocommerce/woocommerce.log`

The library automatically:

- Creates directories as needed
- Adds `.htaccess` to deny direct access
- Adds `index.php` for additional security
- Uses proper WordPress file permissions

Log Format
----------

[](#log-format)

```
[2025-01-15T10:30:45+00:00] ERROR: Payment processing failed {"user_id":123,"amount":99.99}
[2025-01-15T10:30:46+00:00] INFO: Order processed successfully {"order_id":"12345"}
[2025-01-15T10:30:47+00:00] DEBUG: Cache cleared {"cache_key":"user_123_orders"}

```

API Reference
-------------

[](#api-reference)

### Registry Functions

[](#registry-functions)

- `register_logger( string $name, array $options = [] ): Logger` - Register a new logger
- `get_logger( string $name ): ?Logger` - Get a registered logger
- `has_logger( string $name ): bool` - Check if a logger exists
- `remove_logger( string $name ): bool` - Remove a logger

### Logging Methods

[](#logging-methods)

- `error( string $message, array $context = [] )` - Log error messages
- `warning( string $message, array $context = [] )` - Log warnings
- `info( string $message, array $context = [] )` - Log informational messages
- `debug( string $message, array $context = [] )` - Log debug information
- `log( string $message, array $context = [], string $level = 'INFO' )` - Generic logging

### Specialized Methods

[](#specialized-methods)

- `exception( Throwable $exception, array $context = [] )` - Log exceptions with trace
- `wp_error( WP_Error $wp_error, array $context = [] )` - Log WordPress errors

### Utility Methods

[](#utility-methods)

- `clear()` - Clear the log file
- `get_contents()` - Get log file contents
- `get_file()` - Get log file path
- `is_enabled()` - Check if logging is enabled

Why This Logger?
----------------

[](#why-this-logger)

Unlike complex logging libraries, this logger is designed specifically for WordPress with just enough features:

- **No configuration required** - Uses WordPress conventions by default
- **No dependencies** - Just one simple class
- **WordPress-native** - Uses WordPress functions and follows WordPress patterns
- **Registry pattern** - Centralized management without globals
- **Smart naming** - Each plugin gets its own named log file automatically
- **Predictable** - Does exactly what you expect, nothing more

Perfect for plugins and themes that need reliable logging without the overhead of large logging frameworks.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This project is licensed under the GPL-2.0-or-later License.

Support
-------

[](#support)

- [Documentation](https://github.com/arraypress/wp-logger)
- [Issue Tracker](https://github.com/arraypress/wp-logger/issues)

###  Health Score

19

—

LowBetter than 10% of packages

Maintenance48

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/cd6eb8aff0903d87eb674d1ba3c5f3653899c0d7661504eb0deb7798ed86b643?d=identicon)[arraypress](/maintainers/arraypress)

---

Top Contributors

[![arraypress](https://avatars.githubusercontent.com/u/22668877?v=4)](https://github.com/arraypress "arraypress (4 commits)")

### Embed Badge

![Health badge](/badges/arraypress-wp-logger/health.svg)

```
[![Health](https://phpackages.com/badges/arraypress-wp-logger/health.svg)](https://phpackages.com/packages/arraypress-wp-logger)
```

###  Alternatives

[psr/log

Common interface for logging libraries

10.4k1.2B9.2k](/packages/psr-log)[itsgoingd/clockwork

php dev tools in your browser

5.9k27.6M94](/packages/itsgoingd-clockwork)[graylog2/gelf-php

A php implementation to send log-messages to a GELF compatible backend like Graylog2.

41838.2M138](/packages/graylog2-gelf-php)[bugsnag/bugsnag-psr-logger

Official Bugsnag PHP PSR Logger.

32132.5M2](/packages/bugsnag-bugsnag-psr-logger)[consolidation/log

Improved Psr-3 / Psr\\Log logger based on Symfony Console components.

15462.2M7](/packages/consolidation-log)[ekino/newrelic-bundle

Integrate New Relic into Symfony2

28111.2M8](/packages/ekino-newrelic-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
