PHPackages                             plopster/trace-code-maker - 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. plopster/trace-code-maker

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

plopster/trace-code-maker
=========================

A Laravel library designed to create and manage unique trace codes for monitoring, logging, and tracing errors or responses within services. Easy installation with automated setup commands.

v1.4.7(9mo ago)021MITPHPPHP ^8.1

Since Aug 20Pushed 9mo agoCompare

[ Source](https://github.com/Plopster-Software-Development/trace-code-maker-lib)[ Packagist](https://packagist.org/packages/plopster/trace-code-maker)[ RSS](/packages/plopster-trace-code-maker/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (13)Used By (0)

TraceCodeMaker Library
======================

[](#tracecodemaker-library)

Overview
--------

[](#overview)

`TraceCodeMaker` is a modern Laravel library designed to create and manage unique trace codes for monitoring, logging, and tracing errors or responses within services. The library features automatic installation, caching support, and comprehensive configuration options.

Features
--------

[](#features)

- ✅ **Automatic Installation**: Just two commands to get started
- ✅ **Auto-Discovery**: Automatically registers service provider and facade
- ✅ **Caching Support**: Optional caching for improved performance
- ✅ **Configurable**: Extensive configuration options
- ✅ **Validation**: Built-in parameter validation
- ✅ **Database Agnostic**: Works with any Laravel-supported database
- ✅ **Laravel 9, 10, 11, 12 Support**: Compatible with modern Laravel versions

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

[](#requirements)

- Laravel 9.x, 10.x, 11.x, or 12.x
- PHP 8.1 or higher

Quick Installation
------------------

[](#quick-installation)

### Step 1: Install via Composer

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

```
composer require plopster/trace-code-maker
```

### Step 2: Run Installation Command

[](#step-2-run-installation-command)

```
php artisan tracecodemaker:install
```

**That's it!** 🎉 The installation command will:

- Publish the configuration file
- Publish and run the migration
- Clear application cache
- Set up everything automatically

Manual Installation (Alternative)
---------------------------------

[](#manual-installation-alternative)

If you prefer manual installation:

### 1. Install Package

[](#1-install-package)

```
composer require plopster/trace-code-maker
```

### 2. Publish Files

[](#2-publish-files)

```
# Publish configuration and migrations
php artisan tracecodemaker:publish

# Or publish individually
php artisan tracecodemaker:publish --config
php artisan tracecodemaker:publish --migrations
```

### 3. Run Migration

[](#3-run-migration)

```
php artisan migrate
```

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

[](#configuration)

After installation, you can customize the library by editing the published configuration file:

```
config/tracecodemaker.php
```

### Configuration Options

[](#configuration-options)

#### Default Service

[](#default-service)

```
'default_service' => env('TRACE_CODE_DEFAULT_SERVICE', 'DefaultService'),
```

Sets the default service name when none is provided.

#### Trace Code Format

[](#trace-code-format)

```
'format' => [
    'service_code_length' => 3,     // Length of service code prefix
    'method_hash_length' => 5,      // Length of method hash
    'random_suffix_length' => 4,    // Length of random suffix
    'timestamp_format' => 'ymdHis', // Timestamp format
],
```

Customize how trace codes are generated.

#### Database Settings

[](#database-settings)

```
'database' => [
    'connection' => env('TRACE_CODE_DB_CONNECTION', config('database.default')),
    'table' => env('TRACE_CODE_DB_TABLE', 'trace_codes'),
],
```

Configure database connection and table name.

#### Cache Settings

[](#cache-settings)

```
'cache' => [
    'enabled' => env('TRACE_CODE_CACHE_ENABLED', true),
    'ttl' => env('TRACE_CODE_CACHE_TTL', 3600), // 1 hour
    'prefix' => 'tracecode:',
],
```

Enable/disable caching and set cache duration.

#### Validation Rules

[](#validation-rules)

```
'validation' => [
    'service' => 'required|string|max:100',
    'http_code' => 'required|integer|min:100|max:599',
    'method' => 'required|string|max:100',
    'class' => 'required|string|max:255',
    'description' => 'nullable|string|max:500',
],
```

Customize validation rules for input parameters.

### Environment Variables

[](#environment-variables)

You can configure the library using environment variables in your `.env` file:

```
# Default service name
TRACE_CODE_DEFAULT_SERVICE=MyApp

# Cache settings
TRACE_CODE_CACHE_ENABLED=true
TRACE_CODE_CACHE_TTL=3600

# Database settings
TRACE_CODE_DB_CONNECTION=mysql
TRACE_CODE_DB_TABLE=trace_codes
```

### Performance Optimization

[](#performance-optimization)

#### Caching

[](#caching)

The library includes built-in caching to improve performance:

- Trace codes are cached after creation
- Cache keys are generated based on service, HTTP code, method, and class
- Cache TTL is configurable (default: 1 hour)

#### Database Indexes

[](#database-indexes)

The migration includes optimized indexes for:

- `trace_code` (unique)
- `service`
- `http_code`
- `method`
- `class`
- `timestamp`

#### Memory Usage

[](#memory-usage)

- Validation rules are cached
- Database queries are optimized
- Minimal memory footprint

Usage
-----

[](#usage)

After installation, you can use `TraceCodeMaker` anywhere in your Laravel application.

### Basic Usage

[](#basic-usage)

```
use TraceCodeMaker;

$service = 'UserService';
$httpCode = 500;
$methodName = 'createUser';
$className = 'UserController';
$description = 'Internal server error during user creation'; // Optional

$response = TraceCodeMaker::fetchOrCreateTraceCode(
    $service,
    $httpCode,
    $methodName,
    $className,
    $description
);

if ($response['error']) {
    // Handle error
    logger()->error('TraceCodeMaker error: ' . $response['message']);
} else {
    // Use the trace code
    $traceCode = $response['traceCode'];
    logger()->error('Error occurred', ['trace_code' => $traceCode]);
}
```

### Advanced Usage Examples

[](#advanced-usage-examples)

#### In Exception Handling

[](#in-exception-handling)

```
use TraceCodeMaker;
use Illuminate\Http\JsonResponse;

class ApiController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        try {
            // Your business logic here
            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            $traceResponse = TraceCodeMaker::fetchOrCreateTraceCode(
                'ApiService',
                500,
                'store',
                self::class,
                $e->getMessage()
            );

            $traceCode = $traceResponse['error'] ? 'UNKNOWN' : $traceResponse['traceCode'];

            return response()->json([
                'error' => true,
                'message' => 'Internal server error',
                'trace_code' => $traceCode
            ], 500);
        }
    }
}
```

#### In Middleware

[](#in-middleware)

```
use TraceCodeMaker;

class ErrorTrackingMiddleware
{
    public function handle($request, Closure $next)
    {
        try {
            return $next($request);
        } catch (\Exception $e) {
            $traceResponse = TraceCodeMaker::fetchOrCreateTraceCode(
                'Middleware',
                $e->getCode() ?: 500,
                'handle',
                self::class
            );

            if (!$traceResponse['error']) {
                $request->attributes->set('trace_code', $traceResponse['traceCode']);
            }

            throw $e;
        }
    }
}
```

#### Using Configuration Defaults

[](#using-configuration-defaults)

```
// If you set a default service in config, you can omit it
$response = TraceCodeMaker::fetchOrCreateTraceCode(
    config('tracecodemaker.default_service'), // Uses default from config
    404,
    'show',
    'ProductController'
);
```

### Response Format

[](#response-format)

The `fetchOrCreateTraceCode` method returns an array with the following structure:

**Success Response:**

```
[
    'error' => false,
    'traceCode' => 'USR-500-a1b2c-240101123045ABCD'
]
```

**Error Response:**

```
[
    'error' => true,
    'message' => 'Validation failed: The service field is required.'
]
```

### Trace Code Format

[](#trace-code-format-1)

Generated trace codes follow this pattern: `{SERVICE_CODE}-{HTTP_CODE}-{METHOD_HASH}-{TIMESTAMP}{RANDOM_SUFFIX}`

Example: `USR-500-a1b2c-240101123045ABCD`

- **USR**: First 3 characters of service name (configurable)
- **500**: HTTP status code
- **a1b2c**: MD5 hash of class.method (first 5 chars, configurable)
- **240101123045**: Timestamp in ymdHis format (configurable)
- **ABCD**: Random suffix (4 chars, configurable)

Testing
-------

[](#testing)

The library includes comprehensive tests. To run them:

```
# Install dev dependencies
composer install --dev

# Run tests
vendor/bin/phpunit

# Run tests with coverage
vendor/bin/phpunit --coverage-html coverage
```

### Test Database

[](#test-database)

Tests use SQLite in-memory database by default. You can configure this in `phpunit.xml`.

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

#### Migration Not Found

[](#migration-not-found)

```
# Publish migrations manually
php artisan tracecodemaker:publish --migrations

# Then run migrations
php artisan migrate
```

#### Cache Issues

[](#cache-issues)

```
# Clear application cache
php artisan cache:clear

# Clear config cache
php artisan config:clear
```

#### Service Provider Not Registered

[](#service-provider-not-registered)

For Laravel 10 and below, manually add to `config/app.php`:

```
'providers' => [
    // ...
    TraceCodeMaker\TraceCodeMakerServiceProvider::class,
],

'aliases' => [
    // ...
    'TraceCodeMaker' => TraceCodeMaker\Facades\TraceCodeMaker::class,
],
```

#### Database Connection Issues

[](#database-connection-issues)

Ensure your database configuration is correct:

```
TRACE_CODE_DB_CONNECTION=mysql
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
```

### Debug Mode

[](#debug-mode)

Enable debug logging by setting:

```
APP_DEBUG=true
LOG_LEVEL=debug
```

Version Compatibility
---------------------

[](#version-compatibility)

Laravel VersionPHP VersionPackage Version12.x8.1+1.0+11.x8.1+1.0+10.x8.1+1.0+9.x8.1+1.0+Contributing
------------

[](#contributing)

Contributions are welcome! Please follow these steps:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Development Setup

[](#development-setup)

```
# Clone the repository
git clone https://github.com/yourusername/trace-code-maker-lib.git
cd trace-code-maker-lib

# Install dependencies
composer install

# Run tests
vendor/bin/phpunit
```

### Coding Standards

[](#coding-standards)

- Follow PSR-12 coding standards
- Add tests for new features
- Update documentation as needed
- Ensure backward compatibility

License
-------

[](#license)

This project is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

Support
-------

[](#support)

If you encounter any issues or have questions:

- Check the [troubleshooting section](#troubleshooting)
- Open an issue on GitHub
- Review existing issues and discussions

Changelog
---------

[](#changelog)

### v1.0.0

[](#v100)

- Initial release
- Laravel 9-12 support
- Auto-discovery support
- Caching mechanism
- Configurable validation
- Artisan commands for installation
- Comprehensive documentation

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance58

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity55

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

Recently: every ~90 days

Total

12

Last Release

274d ago

PHP version history (2 changes)v1.4.5PHP ^8.0

v1.4.6PHP ^8.1

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

laravelloggingmonitoringtraceerror-tracking

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/plopster-trace-code-maker/health.svg)

```
[![Health](https://phpackages.com/badges/plopster-trace-code-maker/health.svg)](https://phpackages.com/packages/plopster-trace-code-maker)
```

###  Alternatives

[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[rollbar/rollbar-laravel

Rollbar error monitoring integration for Laravel projects

14110.4M7](/packages/rollbar-rollbar-laravel)[yadahan/laravel-authentication-log

Laravel Authentication Log provides authentication logger and notification for Laravel.

416632.8k5](/packages/yadahan-laravel-authentication-log)[inspector-apm/inspector-laravel

Code Execution Monitoring, built for developers.

2332.0M2](/packages/inspector-apm-inspector-laravel)

PHPackages © 2026

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