PHPackages                             kevinpirnie/kpt-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. kevinpirnie/kpt-logger

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

kevinpirnie/kpt-logger
======================

Simple Universal Application Logger for PHP with configurable output destinations and four standard log levels

v1.0.11(3mo ago)05754MITPHPPHP &gt;=8.4CI passing

Since Jan 25Pushed 3mo agoCompare

[ Source](https://github.com/kpirnie/kp-logger)[ Packagist](https://packagist.org/packages/kevinpirnie/kpt-logger)[ Docs](https://github.com/kpirnie/kpt-logger)[ Fund](https://ko-fi.com/kevinpirnie)[ Fund](https://www.paypal.biz/kevinpirnie)[ RSS](/packages/kevinpirnie-kpt-logger/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (4)

KPT Logger
==========

[](#kpt-logger)

A simple, universal application logger for PHP that provides basic logging capabilities with configurable output destinations and four standard log levels.

Features
--------

[](#features)

- **Four Log Levels**: ERROR, WARNING, INFO, DEBUG
- **Flexible Output**: Log to system log or custom file
- **Context Support**: Include additional data with log entries
- **Stack Traces**: Optional stack trace inclusion for debugging
- **Always-On Errors**: Error messages log even when logging is disabled
- **Thread-Safe**: File writing with exclusive locks
- **Easy Integration**: Simple static methods for quick logging

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

[](#requirements)

- PHP 8.0 or higher
- Write permissions for log file directory (if using file logging)

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

[](#installation)

Install via Composer:

```
composer require kevinpirnie/kpt-logger
```

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

[](#basic-usage)

### Initialize the Logger

[](#initialize-the-logger)

```
use KPT\Logger;

// Enable logging with stack traces
$logger = new Logger(true, true);

// Enable logging without stack traces
$logger = new Logger(true, false);

// Disable logging (errors still log)
$logger = new Logger(false);
```

### Log Messages

[](#log-messages)

```
// Log an error (always logs, even when disabled)
Logger::error("Database connection failed");

// Log a warning (only when enabled)
Logger::warning("API rate limit approaching");

// Log info (only when enabled)
Logger::info("User successfully logged in");

// Log debug info (only when enabled)
Logger::debug("Processing user data", ['user_id' => 123]);
```

### Using the Alias

[](#using-the-alias)

```
// You can also use the shorter LOG alias
LOG::error("Something went wrong!");
LOG::info("Operation completed");
```

Configuration
-------------

[](#configuration)

### Set Log File

[](#set-log-file)

```
// Log to a custom file
Logger::setLogFile('/var/log/myapp.log');

// Log to system log (default)
Logger::setLogFile(null);
```

### Advanced Logging with Context

[](#advanced-logging-with-context)

```
// Include additional context data
Logger::error("Payment processing failed", [
    'user_id' => 456,
    'amount' => 99.99,
    'transaction_id' => 'txn_123456'
]);

// Override stack trace setting per call
Logger::debug("Debugging info", [], false); // No stack trace
Logger::error("Critical error", [], true);  // Force stack trace
```

Log Levels
----------

[](#log-levels)

LevelConstantDescriptionAlways LogsERROR`Logger::LEVEL_ERROR`Error conditions✅ YesWARNING`Logger::LEVEL_WARNING`Warning conditionsOnly when enabledINFO`Logger::LEVEL_INFO`Informational messagesOnly when enabledDEBUG`Logger::LEVEL_DEBUG`Debug-level messagesOnly when enabledOutput Format
-------------

[](#output-format)

Log entries are formatted as follows:

```
[2024-08-18 14:30:25] ERROR: Database connection failed | Context: {"host":"localhost","port":3306} | Stack: [...]

```

**Format breakdown:**

- `[2024-08-18 14:30:25]` - Timestamp
- `ERROR` - Log level
- `Database connection failed` - Your message
- `Context: {...}` - Additional context data (if provided)
- `Stack: [...]` - Stack trace (if enabled)

Examples
--------

[](#examples)

### Basic Error Logging

[](#basic-error-logging)

```
try {
    // Some risky operation
    $result = riskyOperation();
} catch (Exception $e) {
    Logger::error("Operation failed: " . $e->getMessage(), [
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
}
```

### Application Monitoring

[](#application-monitoring)

```
// Track user actions
Logger::info("User login", ['user_id' => $userId, 'ip' => $_SERVER['REMOTE_ADDR']]);

// Monitor performance
$start = microtime(true);
processData();
$duration = microtime(true) - $start;

Logger::debug("Data processing completed", ['duration' => $duration]);
```

### API Integration Logging

[](#api-integration-logging)

```
// Log API calls
Logger::info("Making API request", ['endpoint' => $url, 'method' => 'POST']);

if ($response->getStatusCode() !== 200) {
    Logger::warning("API returned non-200 status", [
        'status' => $response->getStatusCode(),
        'body' => $response->getBody()
    ]);
}
```

File Logging Setup
------------------

[](#file-logging-setup)

```
// Set up file logging with error handling
if (!Logger::setLogFile('/var/log/myapp.log')) {
    // Fallback to system log if file setup fails
    Logger::setLogFile(null);
    Logger::warning("Could not set custom log file, using system log");
}
```

Best Practices
--------------

[](#best-practices)

1. **Initialize Early**: Set up the logger at the beginning of your application
2. **Use Appropriate Levels**: Reserve ERROR for actual errors, use DEBUG sparingly in production
3. **Include Context**: Add relevant data to help with debugging
4. **Handle File Permissions**: Ensure your application can write to the log directory
5. **Log File Rotation**: Implement log rotation for production environments
6. **Sensitive Data**: Avoid logging passwords or other sensitive information

Thread Safety
-------------

[](#thread-safety)

The logger uses `LOCK_EX` when writing to files, making it safe for concurrent access in multi-threaded environments.

Performance Considerations
--------------------------

[](#performance-considerations)

- Disabled logging levels have minimal performance impact (simple boolean check)
- Stack traces add overhead - disable in production if not needed
- File I/O is synchronous - consider async logging for high-traffic applications

Author
------

[](#author)

**Kevin Pirnie** -

License
-------

[](#license)

Part of the KP Library package.

Version
-------

[](#version)

Since version 8.4

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance82

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Every ~12 days

Total

2

Last Release

95d ago

PHP version history (2 changes)v1.0.03PHP &gt;=8.2

v1.0.11PHP &gt;=8.4

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

loggingdebugerrorloggerstack traceinfowarningfile-loggingsystem-log

###  Code Quality

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/kevinpirnie-kpt-logger/health.svg)

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

###  Alternatives

[analog/analog

Fast, flexible, easy PSR-3-compatible PHP logging package with dozens of handlers.

3451.5M24](/packages/analog-analog)[justbetter/magento2-sentry

Magento 2 Logger for Sentry

1851.5M3](/packages/justbetter-magento2-sentry)[inpsyde/wonolog

Monolog-based logging package for WordPress.

183617.9k7](/packages/inpsyde-wonolog)[rollbar/rollbar-laravel

Rollbar error monitoring integration for Laravel projects

14110.4M7](/packages/rollbar-rollbar-laravel)

PHPackages © 2026

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