ekahal/lumberjack

A simple logging tool for PHP - supports Laravel, CodeIgniter, and plain PHP

Installs: 57

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Forks: 0

pkg:composer/ekahal/lumberjack

v2.0.0 2026-01-09 09:04 UTC

This package is auto-updated.

Last update: 2026-01-09 09:10:52 UTC


README

A simple and elegant logging mechanism for PHP applications. Track user actions, API calls, and events with ease. Now supports Laravel, CodeIgniter, and plain PHP!

Requirements

  • PHP >= 8.1
  • MongoDB (via MongoDB PHP extension or mongodb/mongodb package)
  • For Laravel: Laravel >= 10.0 and jenssegers/mongodb package (optional, for Eloquent integration)

MongoDB Atlas Support

LumberJack automatically detects MongoDB Atlas clusters and uses the correct connection protocol (mongodb+srv://). Simply provide your Atlas host (e.g., cluster0.abcde.mongodb.net) and the package will handle the rest. For non-Atlas MongoDB instances, it will use the standard mongodb:// protocol.

Installation

Install the package via Composer:

composer require ekahal/lumberjack

Framework Support

LumberJack now supports multiple PHP frameworks:

  • Laravel - Full integration with ServiceProvider, routes, and middleware
  • CodeIgniter - Adapter for CodeIgniter 3.x/4.x
  • Plain PHP - Works with any PHP application

Laravel Installation

Additional Requirements

For Laravel, you may also want to install:

composer require jenssegers/mongodb

Environment Configuration

Add the following to your .env file:

MONGODB_HOST=cluster0.abcde.mongodb.net
MONGODB_DATABASE=database
MONGODB_USERNAME=username
MONGODB_PASSWORD=password
LUMBERJACK_SECRET=your-secret-code-here

Database Configuration

Add the MongoDB connection to your config/database.php. You can use either method:

Method 1: DSN (Recommended for Atlas)

'connections' => [
    // ... other connections
    
    'ekljmongodb' => [
        'driver' => 'mongodb',
        'dsn' => 'mongodb+srv://' . env('MONGODB_USERNAME') . ':' . env('MONGODB_PASSWORD') . '@' . env('MONGODB_HOST') . '/' . env('MONGODB_DATABASE') . '?retryWrites=true&w=majority',
        'database' => env('MONGODB_DATABASE', 'myappdb'),
    ],
],

Method 2: Individual Config Values (Auto-detects Atlas)

'connections' => [
    // ... other connections
    
    'ekljmongodb' => [
        'driver' => 'mongodb',
        'host' => env('MONGODB_HOST', 'localhost'),
        'port' => env('MONGODB_PORT', 27017),
        'database' => env('MONGODB_DATABASE', 'myappdb'),
        'username' => env('MONGODB_USERNAME'),
        'password' => env('MONGODB_PASSWORD'),
        // Optional: Force SRV protocol even for non-Atlas hosts
        // 'use_srv' => true,
    ],
],

Note: When using individual config values, LumberJack automatically detects MongoDB Atlas clusters (hosts containing .mongodb.net or .mongodb.com) and uses mongodb+srv:// protocol. For local MongoDB instances, it uses the standard mongodb:// protocol.

Publish Configuration

Publish the configuration file (optional):

php artisan vendor:publish --provider="Ekahal\LumberJack\ServiceProvider" --tag="lumberjack-config"

Laravel Usage

use Ekahal\LumberJack\LumberJack;

// Log a simple action
LumberJack::log(
    user_id: auth()->id(),
    url: request()->url(),
    action: 'CREATE'
);

// Track with additional details
LumberJack::track(
    user_id: auth()->id(),
    url: request()->url(),
    action: 'UPDATE',
    ip: request()->ip(),
    location: 'New York, US',
    browser: request()->userAgent(),
    device: 'Desktop'
);

// Fetch logs
$logs = LumberJack::fetch([
    'user_id' => auth()->id(),
    'action' => 'CREATE',
]);

// Delete logs older than 3 days
use Carbon\Carbon;
$deletedCount = LumberJack::delete(Carbon::now()->subDays(3));
// Or using DateTime
$deletedCount = LumberJack::delete(new \DateTime('-7 days'));

CodeIgniter Installation

Configuration

Create a config file application/config/lumberjack.php:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// For MongoDB Atlas (automatically detected)
$config['mongodb_host'] = 'cluster0.abcde.mongodb.net';
$config['mongodb_database'] = 'myapp';
$config['mongodb_username'] = 'username';
$config['mongodb_password'] = 'password';

// For local MongoDB
// $config['mongodb_host'] = 'localhost';
// $config['mongodb_port'] = 27017;
// $config['mongodb_database'] = 'myapp';
// $config['mongodb_username'] = 'username'; // Optional
// $config['mongodb_password'] = 'password'; // Optional

// Optional: Force SRV protocol even for non-Atlas hosts
// $config['use_srv'] = true;

Note: LumberJack automatically detects MongoDB Atlas clusters (hosts containing .mongodb.net or .mongodb.com) and uses mongodb+srv:// protocol. For local MongoDB instances, it uses the standard mongodb:// protocol with the specified port.

CodeIgniter Usage

use Ekahal\LumberJack\Adapters\CodeIgniter\LumberJack;

// Log a simple action
LumberJack::log(
    user_id: $this->session->userdata('user_id'),
    url: current_url(),
    action: 'VIEW'
);

// Track with additional details
LumberJack::track(
    user_id: $this->session->userdata('user_id'),
    url: current_url(),
    action: 'CREATE',
    ip: $this->input->ip_address(),
    location: 'New York, US',
    browser: $this->input->user_agent(),
    device: 'Desktop'
);

// Fetch logs
$logs = LumberJack::fetch([
    'user_id' => $this->session->userdata('user_id'),
    'action' => 'CREATE',
]);

// Delete logs older than 3 days
$deletedCount = LumberJack::delete(new \DateTime('-3 days'));
// Or using date string
$deletedCount = LumberJack::delete('2024-01-01 00:00:00');

Plain PHP Installation

Initialization

Initialize LumberJack with your MongoDB configuration:

require_once 'vendor/autoload.php';

use Ekahal\LumberJack\Adapters\PlainPHP\LumberJack;

// For MongoDB Atlas (automatically detected)
LumberJack::init([
    'mongodb_host' => 'cluster0.abcde.mongodb.net',
    'mongodb_database' => 'myapp',
    'mongodb_username' => 'username',
    'mongodb_password' => 'password',
]);

// For local MongoDB
// LumberJack::init([
//     'mongodb_host' => 'localhost',
//     'mongodb_port' => 27017,
//     'mongodb_database' => 'myapp',
//     'mongodb_username' => 'username', // Optional
//     'mongodb_password' => 'password', // Optional
// ]);

// Optional: Force SRV protocol even for non-Atlas hosts
// LumberJack::init([
//     'mongodb_host' => 'custom-host.com',
//     'mongodb_database' => 'myapp',
//     'use_srv' => true,
// ]);

Note: LumberJack automatically detects MongoDB Atlas clusters (hosts containing .mongodb.net or .mongodb.com) and uses mongodb+srv:// protocol. For local MongoDB instances, it uses the standard mongodb:// protocol with the specified port.

Plain PHP Usage

use Ekahal\LumberJack\Adapters\PlainPHP\LumberJack;

// Log a simple action
LumberJack::log(
    user_id: 123,
    url: '/api/users',
    action: 'CREATE'
);

// Track with additional details
LumberJack::track(
    user_id: 123,
    url: '/api/users',
    action: 'UPDATE',
    ip: $_SERVER['REMOTE_ADDR'] ?? '',
    location: 'New York, US',
    browser: $_SERVER['HTTP_USER_AGENT'] ?? '',
    device: 'Desktop'
);

// Fetch logs
$logs = LumberJack::fetch([
    'user_id' => 123,
    'action' => 'CREATE',
    'from' => '2024-01-01 00:00:00',
    'to' => '2024-12-31 23:59:59',
]);

foreach ($logs as $log) {
    echo "User {$log['user_id']} performed {$log['action']} on {$log['url']}\n";
}

// Delete logs older than 3 days
$deletedCount = LumberJack::delete(new \DateTime('-3 days'));
// Or using date string
$deletedCount = LumberJack::delete('2024-01-01 00:00:00');
echo "Deleted {$deletedCount} log entries\n";

Frontend Usage (JavaScript)

Laravel Only

The Laravel adapter automatically injects JavaScript functions into your HTML pages. You can use them in vanilla JavaScript, Vue, React, or any other framework.

Simple Logging

// Log an action
lumberjack.log(
    'your-secret-code',  // From LUMBERJACK_SECRET env variable
    123,                 // User ID
    '/dashboard',        // URL
    'VIEW'               // Action
);

Advanced Tracking

// Track with additional details
lumberjack.track(
    'your-secret-code',  // Secret
    123,                 // User ID
    '/api/users',        // URL
    'CREATE',            // Action
    '192.168.1.1',       // IP (optional)
    'New York, US',      // Location (optional)
    'Chrome 120.0',      // Browser (optional)
    'Desktop'            // Device (optional)
);

Note: Make sure you have a CSRF token meta tag in your HTML <head>:

<meta name="csrf-token" content="{{ csrf_token() }}">

For Other Frameworks

For CodeIgniter and plain PHP, you'll need to create your own API endpoints. See the examples directory for reference implementations.

Deleting Logs

All adapters support deleting logs prior to a specific date:

Laravel

use Carbon\Carbon;

// Delete logs older than 3 days
$deletedCount = LumberJack::delete(Carbon::now()->subDays(3));

// Delete logs older than 1 week
$deletedCount = LumberJack::delete(Carbon::now()->subWeek());

// Delete logs before a specific date
$deletedCount = LumberJack::delete(new \DateTime('2024-01-01 00:00:00'));

CodeIgniter

// Delete logs older than 3 days
$deletedCount = LumberJack::delete(new \DateTime('-3 days'));

// Delete logs before a specific date string
$deletedCount = LumberJack::delete('2024-01-01 00:00:00');

Plain PHP

// Delete logs older than 3 days
$deletedCount = LumberJack::delete(new \DateTime('-3 days'));

// Delete logs before a specific date string
$deletedCount = LumberJack::delete('2024-01-01 00:00:00');

echo "Deleted {$deletedCount} log entries\n";

The delete() method returns the number of deleted entries. It accepts either a DateTime object or a date string that can be parsed by PHP's DateTime constructor.

Fetching Logs

All adapters support fetching logs with optional filters:

// Fetch all logs
$logs = LumberJack::fetch();

// Fetch with filters
$logs = LumberJack::fetch([
    'user_id' => 123,
    'url' => '/api/users',
    'action' => 'CREATE',
    'ip' => '192.168.1.1',
    'location' => 'New York',
    'browser' => 'Chrome',
    'device' => 'Desktop',
    'from' => '2024-01-01 00:00:00',
    'to' => '2024-12-31 23:59:59',
]);

Note: Return types differ by framework:

  • Laravel: Returns Illuminate\Database\Eloquent\Collection (if using Eloquent) or array
  • CodeIgniter/Plain PHP: Returns array

Recommended Action Codes

For consistency, consider using these action codes:

  • CREATE or C - Create operations
  • READ or R - Read/View operations
  • UPDATE or U - Update operations
  • DELETE or D - Delete operations
  • LOGIN - User login
  • LOGOUT - User logout
  • DOWNLOAD - File downloads
  • UPLOAD - File uploads

API Endpoints (Laravel Only)

The Laravel adapter automatically registers the following routes:

  • POST /lumberjack/log - Simple logging endpoint
  • POST /lumberjack/track - Advanced tracking endpoint

Both endpoints require:

  • secret - Must match your LUMBERJACK_SECRET value
  • user_id - User identifier
  • url - URL being tracked
  • action - Action being performed

Architecture

LumberJack uses a framework-agnostic core architecture:

┌─────────────────────────────────────┐
│      Framework-Specific Adapters    │
│  Laravel | CodeIgniter | Plain PHP  │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│         LumberJackCore              │
│    (Framework-Agnostic Logic)       │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│      StorageInterface               │
│  MongoDBStorage | (Other Storages)  │
└─────────────────────────────────────┘

This architecture allows you to:

  • Use the same core functionality across different frameworks
  • Easily add support for new frameworks
  • Swap storage backends without changing application code

Features

  • Multi-framework support - Laravel, CodeIgniter, and plain PHP
  • MongoDB Atlas support - Automatic detection and correct protocol usage
  • ✅ Simple and intuitive API
  • ✅ Framework-agnostic core architecture
  • ✅ MongoDB storage for scalability
  • ✅ Flexible filtering options
  • ✅ Log deletion by date
  • ✅ Type-safe PHP 8.1+ implementation
  • ✅ Automatic JavaScript injection (Laravel)
  • ✅ JSON API responses (Laravel)
  • ✅ Request validation (Laravel)
  • ✅ Error handling

Examples

Check the examples/ directory for complete working examples:

  • laravel-example.php - Laravel usage
  • codeigniter-example.php - CodeIgniter usage
  • plain-php-example.php - Plain PHP usage

Security

  • All JavaScript API calls require a secret key (Laravel)
  • CSRF protection via Laravel's built-in middleware (Laravel)
  • Input validation on all endpoints (Laravel)
  • For other frameworks, implement your own security measures

License

MIT

Support

For issues, questions, or contributions, please visit the GitHub repository.