PHPackages                             flowlog/flowlog-laravel - 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. flowlog/flowlog-laravel

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

flowlog/flowlog-laravel
=======================

Laravel SDK for Flowlog - Async logging with automatic context extraction

0.1.12(5mo ago)087MITPHPPHP ^8.2CI passing

Since Nov 9Pushed 5mo agoCompare

[ Source](https://github.com/gwdhost/flowlog-sdk-laravel)[ Packagist](https://packagist.org/packages/flowlog/flowlog-laravel)[ RSS](/packages/flowlog-flowlog-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (14)Used By (0)

Flowlog Laravel SDK
===================

[](#flowlog-laravel-sdk)

Laravel SDK for Flowlog - Async logging with automatic context extraction, exception reporting, and configurable event logging.

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

[](#requirements)

- PHP 8.2 or higher
- Laravel 10, 11, or 12

Features
--------

[](#features)

- 🔄 **Async Logging**: Logs are batched and sent asynchronously via Laravel queues
- 🎯 **Automatic Context Extraction**: Automatically extracts user, request, route, and trace information
- 🚨 **Exception Reporting**: Automatically reports exceptions with full context
- 📊 **Query Logging**: Log slow and failed database queries (configurable)
- 🌐 **HTTP Logging**: Log HTTP requests and responses (configurable)
- ⚙️ **Job/Queue Logging**: Log job processing, completion, and failures (enabled by default)
- 🎛️ **Fully Configurable**: Enable/disable features via config file

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

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require flowlog/flowlog-laravel
```

### 2. Publish Configuration

[](#2-publish-configuration)

```
php artisan vendor:publish --tag=flowlog-config
```

### 3. Configure Environment Variables

[](#3-configure-environment-variables)

Add to your `.env` file:

#### Required Variables

[](#required-variables)

```
FLOWLOG_API_KEY=your-api-key-here
```

#### Optional Variables

[](#optional-variables)

```
# API Configuration
FLOWLOG_API_URL=https://flowlog.io/api/v1/logs
FLOWLOG_SERVICE=my-laravel-app  # Defaults to APP_NAME if not set
FLOWLOG_ENV=production           # Defaults to APP_ENV if not set

# Batch Configuration
FLOWLOG_BATCH_SIZE=50            # Max logs per batch (default: 50)
FLOWLOG_BATCH_INTERVAL=5         # Flush interval in seconds (default: 5)
FLOWLOG_BATCH_MAX_SIZE=65536     # Max batch size in bytes, 64KB (default: 65536)

# Feature Toggles
FLOWLOG_QUERY_LOGGING=false      # Enable slow/failed query logging (default: false)
FLOWLOG_HTTP_LOGGING=false       # Enable HTTP request/response logging (default: false)
FLOWLOG_JOB_LOGGING=true         # Enable job/queue logging (default: true)
FLOWLOG_EXCEPTION_REPORTING=true # Auto-report exceptions (default: true)

# Query Logging Configuration
FLOWLOG_QUERY_SLOW_THRESHOLD=1000  # Log queries slower than this in ms (default: 1000)
FLOWLOG_QUERY_LOG_FAILED=true      # Log failed queries (default: true)
FLOWLOG_QUERY_LOG_ALL=false        # Log all queries, not just slow/failed (default: false)

# HTTP Logging Configuration
FLOWLOG_HTTP_LOG_HEADERS=false    # Include headers in HTTP logs (default: false)

# Exception Reporting Configuration
FLOWLOG_EXCEPTION_LEVEL=error     # Exception log level: 'error' or 'critical' (default: 'error')

# Queue Configuration
FLOWLOG_QUEUE_CONNECTION=sync     # Queue connection (default: sync, uses QUEUE_CONNECTION if set)
FLOWLOG_QUEUE_NAME=default        # Queue name (default: 'default')
FLOWLOG_QUEUE_TRIES=3             # Number of retry attempts (default: 3)
FLOWLOG_QUEUE_DEBOUNCE_DELAY=3    # Seconds to wait before sending (default: 3)
# Note: FLOWLOG_QUEUE_BACKOFF is configured in config/flowlog.php as an array [1, 5, 10]
# representing retry delays in seconds. Cannot be set via .env directly.

# Chunking Configuration
FLOWLOG_CHUNK_SIZE=100            # Number of logs per chunk when sending (default: 100)

# Fallback Log Channel
FLOWLOG_FALLBACK_LOG_CHANNEL=single  # Channel for internal SDK logs (default: 'single')
```

### 4. Add Flowlog Channel to Logging Config

[](#4-add-flowlog-channel-to-logging-config)

Edit `config/logging.php` and add the Flowlog channel to your stack:

```
'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily', 'flowlog'], // Add 'flowlog' here
        'ignore_exceptions' => false,
    ],

    // ... other channels

    'flowlog' => [
        'driver' => 'flowlog',
    ],
],
```

### 5. (Optional) Add Middleware for Iteration/Trace IDs

[](#5-optional-add-middleware-for-iterationtrace-ids)

**Important**: The service provider automatically registers `FlowlogTerminatingMiddleware` for flushing logs at the end of requests. However, if you want automatic iteration key and trace ID generation, or automatic handling of the `X-Flowlog-Ignore` header, you need to manually register `FlowlogMiddleware`.

**Note**: The `FlowlogMiddleware` handles the `X-Flowlog-Ignore`header to prevent infinite loops. When this header is present, logging will be skipped for that request. Without this middleware, you can still use the guard programmatically (see "Preventing Infinite Loops" section).

#### Laravel 11 and 12

[](#laravel-11-and-12)

Add the middleware to `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \Flowlog\FlowlogLaravel\Middleware\FlowlogMiddleware::class,
    ]);

    $middleware->api(append: [
        \Flowlog\FlowlogLaravel\Middleware\FlowlogMiddleware::class,
    ]);
})
```

#### Laravel 10

[](#laravel-10)

Add the middleware to `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
    'web' => [
        // ... existing middleware
        \Flowlog\FlowlogLaravel\Middleware\FlowlogMiddleware::class,
    ],

    'api' => [
        // ... existing middleware
        \Flowlog\FlowlogLaravel\Middleware\FlowlogMiddleware::class,
    ],
];
```

Usage
-----

[](#usage)

### Basic Logging

[](#basic-logging)

Use Laravel's standard logging methods - they will automatically be sent to Flowlog if the channel is in your stack:

```
use Illuminate\Support\Facades\Log;

Log::info('User logged in', ['user_id' => 123]);
Log::error('Payment failed', ['order_id' => 456]);
Log::warning('Slow query detected');
```

### Using the Flowlog Facade

[](#using-the-flowlog-facade)

For more control, use the Flowlog facade:

```
use Flowlog\FlowlogLaravel\Facades\Flowlog;

// Basic logging
Flowlog::info('Application started');
Flowlog::error('Something went wrong', ['error_code' => 'E001']);
Flowlog::warn('Deprecated API used');
Flowlog::debug('Debug information');
Flowlog::critical('System failure');

// Set iteration key for grouping related logs
Flowlog::setIterationKey('request-123')->info('Processing request');

// Set trace ID for request tracing
Flowlog::setTraceId('trace-456')->info('Request started');

// Add context that will be included in all subsequent logs
Flowlog::withContext(['feature' => 'checkout'])->info('Checkout started');
Flowlog::info('Payment processed'); // Will include 'feature' => 'checkout'

// Report exceptions
try {
    // some code
} catch (\Exception $e) {
    Flowlog::reportException($e, ['additional' => 'context']);
}
```

### Using Helper Function

[](#using-helper-function)

You can also use the helper function:

```
flowlog()->info('Hello from Flowlog');
flowlog()->error('An error occurred', ['details' => '...']);
```

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

[](#configuration)

All configuration is in `config/flowlog.php`. Key options:

### API Configuration

[](#api-configuration)

```
'api_url' => env('FLOWLOG_API_URL', 'https://flowlog.io/api/v1/logs'),
'api_key' => env('FLOWLOG_API_KEY'),
'service' => env('FLOWLOG_SERVICE', config('app.name')),
'env' => env('FLOWLOG_ENV', env('APP_ENV', 'production')),
```

### Batch Configuration

[](#batch-configuration)

```
'batch' => [
    'size' => 50,              // Max logs per batch
    'interval' => 5,           // Flush interval in seconds
    'max_size_bytes' => 65536, // Max batch size in bytes (64KB)
],
```

### Feature Toggles

[](#feature-toggles)

```
'features' => [
    'query_logging' => false,        // Log slow/failed queries
    'http_logging' => false,         // Log HTTP requests/responses
    'job_logging' => true,           // Log job events (enabled by default)
    'exception_reporting' => true,   // Auto-report exceptions (enabled by default)
],
```

### Query Logging

[](#query-logging)

```
'query' => [
    'slow_threshold_ms' => 1000, // Log queries slower than this
    'log_failed' => true,         // Log failed queries
],
```

### HTTP Logging

[](#http-logging)

```
'http' => [
    'exclude_routes' => ['health', 'nova/*'], // Routes to exclude
    'log_headers' => false,                    // Include headers in logs
    'sanitize_headers' => ['authorization', 'cookie', 'x-api-key'],
],
```

### Exception Reporting

[](#exception-reporting)

```
'exceptions' => [
    'dont_report' => [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Validation\ValidationException::class,
        // Add exceptions you don't want to report
    ],
    'level' => 'error', // 'error' or 'critical'
],
```

Automatic Context Extraction
----------------------------

[](#automatic-context-extraction)

The SDK automatically extracts the following context:

- **User ID**: From authenticated user (`auth()->id()`)
- **Request ID**: From `X-Request-ID` header or generated UUID
- **Trace ID**: From `X-Trace-Id` header or generated UUID (if middleware is used)
- **Iteration Key**: From `X-Iteration-Key` header or request context (if middleware is used)
- **Route Information**: Route name, action, URI, parameters
- **HTTP Information**: Method, URL, path, IP, user agent
- **Session ID**: If session is started

Preventing Infinite Loops
-------------------------

[](#preventing-infinite-loops)

The SDK includes built-in guards to prevent infinite loops when logging. The guard mechanism uses the `X-Flowlog-Ignore` header or programmatic guards.

### Using the X-Flowlog-Ignore Header

[](#using-the-x-flowlog-ignore-header)

Set the `X-Flowlog-Ignore` header on HTTP requests to prevent logging:

```
// In your HTTP client request
$response = Http::withHeaders([
    'X-Flowlog-Ignore' => '1',
])->post('https://api.example.com/endpoint');
```

When this header is present, the SDK will:

- Skip HTTP request/response logging
- Skip query logging
- Skip job event logging
- Prevent log flushing

### Programmatic Guard Control

[](#programmatic-guard-control)

You can also control the guard programmatically:

```
use Flowlog\FlowlogLaravel\Guards\FlowlogGuard;

// Set ignore guard
FlowlogGuard::setIgnore(true);

try {
    // Your code here - logging will be skipped
} finally {
    // Reset guard
    FlowlogGuard::setIgnore(false);
}
```

### ProcessLogJob Integration

[](#processlogjob-integration)

If you're using `ProcessLogJob` to process incoming logs, you should set the guard when the job starts:

```
use Flowlog\FlowlogLaravel\Guards\FlowlogGuard;

class ProcessLogJob implements ShouldQueue
{
    public function handle(): void
    {
        FlowlogGuard::whileInProcessLogJob(function () {
            // Your job logic here
            // Queries and job events won't be logged
        });
    }
}
```

Alternatively, you can set the `X-Flowlog-Ignore` header on the HTTP request that triggers the job.

**Note**: The SDK automatically sets `X-Flowlog-Ignore` when `SendLogsJob` makes HTTP requests to the Flowlog API to prevent infinite loops.

Queue Configuration
-------------------

[](#queue-configuration)

Logs are sent asynchronously via Laravel queues. Configure in `config/flowlog.php`:

```
'queue' => [
    'connection' => null,  // null = use default connection
    'queue' => 'default',
    'tries' => 3,
    'backoff' => [1, 5, 10], // Retry delays in seconds
],
```

Make sure your queue worker is running:

```
php artisan queue:work
```

Testing
-------

[](#testing)

When running tests, the Flowlog channel will be automatically disabled if the API key is not set. You can also mock the Flowlog facade in tests:

```
use Flowlog\FlowlogLaravel\Facades\Flowlog;

Flowlog::shouldReceive('info')
    ->once()
    ->with('Test message');
```

### Preventing Logging in Tests

[](#preventing-logging-in-tests)

To prevent logging during tests, you can set the ignore guard:

```
use Flowlog\FlowlogLaravel\Guards\FlowlogGuard;

beforeEach(function () {
    FlowlogGuard::setIgnore(true);
});

afterEach(function () {
    FlowlogGuard::setIgnore(false);
});
```

Or use the `X-Flowlog-Ignore` header in your test HTTP requests:

```
$response = $this->withHeaders([
    'X-Flowlog-Ignore' => '1',
])->get('/api/endpoint');
```

License
-------

[](#license)

MIT

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance70

Regular maintenance activity

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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 ~1 days

Total

13

Last Release

169d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5539e95c5d81bf23ff53c776d9fccbc1630e5b72d7cde2441c4020c8c05f73b4?d=identicon)[AndreasGJ](/maintainers/AndreasGJ)

---

Top Contributors

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

---

Tags

asynclaravelloggingqueuemonologflowlog

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/flowlog-flowlog-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/flowlog-flowlog-laravel/health.svg)](https://phpackages.com/packages/flowlog-flowlog-laravel)
```

###  Alternatives

[shaffe/laravel-mail-log-channel

A package to support logging via email in Laravel

1286.2k](/packages/shaffe-laravel-mail-log-channel)[naoray/laravel-github-monolog

Log driver to store logs as github issues

10619.4k](/packages/naoray-laravel-github-monolog)[yzen.dev/mono-processor

This Processor will display in the logs bread crumbs by which you can more quickly and accurately identify the cause of the error.

116.1k](/packages/yzendev-mono-processor)

PHPackages © 2026

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