Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

baskarks's avatar

How to create a centralized error logging package in lumen

I need to create centralized error logging package in lumen to handle for multiple lumen project

0 likes
2 replies
LaryAI's avatar
Level 58

To create a centralized error logging package in Lumen, you can follow these steps:

  1. Create a new package: Start by creating a new package for your error logging functionality. You can use Composer to create a new package skeleton. Run the following command in your terminal:
composer create-project --prefer-dist laravel/lumen-error-logging

This will create a new Lumen project with the necessary structure for your package.

  1. Implement the error logging functionality: Inside your package, you can create a new service provider that will handle the error logging. Create a new file called ErrorLoggingServiceProvider.php inside the app/Providers directory. In this file, you can define the logic for logging errors.

Here's an example of how the ErrorLoggingServiceProvider.php file could look like:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class ErrorLoggingServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('errorLogger', function () {
            $log = new Logger('error');
            $log->pushHandler(new StreamHandler(storage_path('logs/error.log'), Logger::ERROR));
            return $log;
        });
    }
}

In this example, we're using the Monolog library to handle the logging. We create a new logger instance and configure it to log only errors. The log file will be stored in the storage/logs directory.

  1. Register the service provider: To make Lumen aware of your error logging package, you need to register the service provider. Open the bootstrap/app.php file and add the following line at the bottom:
$app->register(App\Providers\ErrorLoggingServiceProvider::class);
  1. Use the error logger: Now that your error logging package is set up, you can start using it in your Lumen projects. In any of your Lumen project files, you can access the error logger instance using the app('errorLogger') function.

Here's an example of how you can use the error logger in a Lumen route:

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    app('errorLogger')->error('An error occurred');
    return 'Hello World';
});

In this example, we're logging an error message using the error logger instance.

That's it! You now have a centralized error logging package that can be used across multiple Lumen projects. Remember to customize the error logging logic according to your specific requirements.

Snapey's avatar

you dont want to use any of the existing services?

Please or to participate in this conversation.