Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Log Manager Laravel Package

sinarajabpour1998/log-manager

Laravel log manager with UI components and migrations to store custom activity logs and system error logs in database tables. Define log types in config, use LogFacade to generate logs, and hook into Exception Handler to capture errors.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Run composer require sinarajabpour1998/log-manager to add the package to your Laravel project.

  2. Publish Assets and Run Migrations Execute these commands to set up the database tables and Blade components:

    php artisan vendor:publish --tag=log-manager
    php artisan migrate
    
  3. Add Log Menu to Sidebar Include the Blade component in your layout (e.g., resources/views/layouts/app.blade.php):

    <x-log-menu />
    
  4. Configure Log Types Define custom log types in config/log-manager.php:

    'log_types' => [
        'login' => 'ورود به سایت',
        'registration' => 'ثبت نام در سایت',
    ],
    
  5. First Log Entry Use the facade to generate a log entry:

    use Sinarajabpour1998\LogManager\Facades\LogFacade;
    LogFacade::generateLog("login");
    

Implementation Patterns

Core Workflows

1. Logging Custom Events

  • Pattern: Use LogFacade::generateLog("type") to log predefined events (e.g., user actions).
  • Example:
    // In a controller or service
    LogFacade::generateLog("registration");
    
  • Integration Tip: Centralize log generation in a service layer to avoid scattering calls across controllers.

2. Handling System Errors

  • Pattern: Override App\Exceptions\Handler to log errors via LogFacade::generateErrorLog($e).
  • Example:
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            if ($this->shouldReport($e)) {
                LogFacade::generateErrorLog($e);
            }
        });
    }
    
  • Integration Tip: Extend the error log with additional context (e.g., user ID, request data) by passing a custom payload:
    LogFacade::generateErrorLog($e, ['user_id' => auth()->id()]);
    

3. Permissions and Access Control

  • Pattern: Define permissions in a seeder (e.g., LogPermissionSeeder) to restrict log viewing/editing.
  • Example:
    // In a seeder
    use Sinarajabpour1998\LogManager\Models\LogPermission;
    LogPermission::create(['name' => 'view_logs', 'description' => 'View all logs']);
    
  • Integration Tip: Use Laravel’s gate system to enforce permissions in controllers:
    public function showLogs()
    {
        $this->authorize('view_logs');
        // Show logs logic
    }
    

4. Extending Log Types Dynamically

  • Pattern: Add new log types via config or a database-backed system.
  • Example:
    // Dynamically fetch log types from a database table
    $logTypes = DB::table('log_types')->pluck('name', 'key')->toArray();
    config(['log-manager.log_types' => $logTypes]);
    
  • Integration Tip: Use a service provider’s boot method to merge dynamic config:
    public function boot()
    {
        $this->mergeConfigFrom(__DIR__.'/log-types.php', 'log-manager.log_types');
    }
    

5. Logging SMS Events

  • Pattern: Use the generateSmsLog method for SMS-related events (added in v1.1).
  • Example:
    LogFacade::generateSmsLog("verification", ["phone" => "+123456789"]);
    

Integration Tips

  1. Facade Aliasing Add an alias in config/app.php for cleaner usage:

    'aliases' => [
        'Log' => Sinarajabpour1998\LogManager\Facades\LogFacade::class,
    ],
    

    Now use Log::generateLog("type") instead of the full facade path.

  2. Middleware for Automatic Logging Create middleware to log requests automatically:

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        LogFacade::generateLog("api_request", [
            'method' => $request->method(),
            'path' => $request->path(),
        ]);
        return $response;
    }
    
  3. Queue Log Entries for Performance Dispatch log entries to a queue to avoid blocking user requests:

    use Illuminate\Support\Facades\Bus;
    Bus::dispatch(new GenerateLogJob("login"));
    

    Implement GenerateLogJob to extend ShouldQueue and call LogFacade::generateLog().

  4. Customize Log Menu Override the log-menu Blade component to add filters or actions:

    @extends('log-manager::log-menu')
    @section('extra-actions')
        <button class="btn btn-sm btn-primary">Custom Action</button>
    @endsection
    

Gotchas and Tips

Pitfalls

  1. Facade Resolution Issues

    • Gotcha: If BaseFacade errors persist after upgrading, ensure the service provider is registered in config/app.php:
      'providers' => [
          Sinarajabpour1998\LogManager\LogManagerServiceProvider::class,
      ],
      
    • Fix: Clear Laravel caches (php artisan cache:clear) and restart your server.
  2. Missing Log Types

    • Gotcha: Attempting to log a type not defined in config/log-manager.php will fail silently or throw an error.
    • Fix: Validate log types before generation:
      $validTypes = config('log-manager.log_types');
      if (!array_key_exists($type, $validTypes)) {
          throw new \InvalidArgumentException("Invalid log type: {$type}");
      }
      LogFacade::generateLog($type);
      
  3. Permission Mismatches

    • Gotcha: Logs may not display if permissions aren’t set in the database.
    • Fix: Run the seeder to initialize permissions:
      php artisan db:seed --class=LogPermissionSeeder
      
  4. Error Log Overwriting

    • Gotcha: The error_trace field may truncate long stack traces if the database column is too small.
    • Fix: Check the error_logs migration and adjust the error_trace column size if needed (e.g., text instead of mediumText).
  5. Blade Component Not Found

    • Gotcha: The <x-log-menu /> component may fail if the view is not published or the namespace is incorrect.
    • Fix: Verify the component is published and the namespace in resources/views/vendor/log-manager/log-menu.blade.php matches your setup.
  6. Git Ignoring Custom Logs

    • Gotcha: Log files in storage/logs/customLogs/ might be ignored by Git.
    • Fix: Explicitly add the directory to .gitignore or ensure it’s tracked:
      !storage/logs/customLogs/
      

Debugging Tips

  1. Log Facade Instantiation Debug facade resolution by checking if the service provider is bound:

    dd(app(Sinarajabpour1998\LogManager\LogManagerServiceProvider::class));
    
  2. Query Logs for Errors Enable Laravel’s query log to debug database issues:

    DB::enableQueryLog();
    LogFacade::generateLog("test");
    dd(DB::getQueryLog());
    
  3. Check Published Views Verify the Blade component exists after publishing:

    ls resources/views/vendor/log-manager/
    
  4. Validate Migrations Ensure the logs and error_logs tables exist:

    php artisan db:show logs
    php artisan db:show error_logs
    
  5. Test Error Logging Force an error to test generateErrorLog:

    throw new \Exception("Test error for logging");
    

    Check the error_logs table for the entry.


Extension Points

  1. Custom Log Models Extend the Log or ErrorLog models to add fields:

    php artisan make:model LogExtension -m
    

    Add a log_id foreign key and customize the migration.

  2. Hooks for Pre/Post Logging Use Laravel’s events to add logic before/after logging:

    // In EventServiceProvider
    protected $listen = [
        'log.generating' => [LogHookListener::class, 'beforeGenerate'],
        'log.generated' => [LogHookListener::class, 'afterGenerate'],
    ];
    
  3. API for Log Export Create a controller to export logs as CSV/JSON:

    public function exportLogs()
    {
        return Excel::download(new LogsExport, 'logs.xlsx');
    }
    
  4. Webhook Notifications

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours