0

First of all, I'm sorry for the complicated title, but I couldn't find any other suitable titles to represent the error.

I'm using Laravel 4 for my project.

I have a Log::listen in my global.php file.

Log::listen(function($level, $message, $context){
    switch($level){
        case 'info':
            Log::useFiles(storage_path().'/logs/laravel.info.log');
            break;

        case 'error':
            Log::useFiles(storage_path().'/logs/laravel.error.log');
            break;
    }
});

When I run this code

for($i = 1; $i <= 5; $i++){
    Log::info($i);
}

Its output is this

[2015-04-15 11:54:07] production.INFO: 1 [] []
[2015-04-15 11:54:07] production.INFO: 2 [] []
[2015-04-15 11:54:07] production.INFO: 2 [] []
[2015-04-15 11:54:07] production.INFO: 3 [] []
[2015-04-15 11:54:07] production.INFO: 3 [] []
[2015-04-15 11:54:07] production.INFO: 3 [] []
[2015-04-15 11:54:07] production.INFO: 4 [] []
[2015-04-15 11:54:07] production.INFO: 4 [] []
[2015-04-15 11:54:07] production.INFO: 4 [] []
[2015-04-15 11:54:07] production.INFO: 4 [] []
[2015-04-15 11:54:07] production.INFO: 5 [] []
[2015-04-15 11:54:07] production.INFO: 5 [] []
[2015-04-15 11:54:07] production.INFO: 5 [] []
[2015-04-15 11:54:07] production.INFO: 5 [] []
[2015-04-15 11:54:07] production.INFO: 5 [] []

I have found that when I remove the Log::listen and simply add Log::useFiles(storage_path().'/logs/laravel.log'); the problem resolves.

Hovewer I have to use the listener and the for loop.

Any help is appreciated.

Thank you in advance.

yenerunver
  • 416
  • 1
  • 5
  • 26

1 Answers1

1

The problem is that every Log::userFiles() call adds a new handler to the stack. And if you have 2, 3, 4 handlers the same message will be written 2, 3, 4 times.

I'm not sure if this is a good way to do it, but it should work:
(actually I'm almost certain there has to be a better way, but I couldn't find it right away)

Log::listen(function($level, $message, $context){
    $monolog = Log::getMonolog();
    // clear all existing log handlers
    for($i=0; $i<count($monolog->getHandlers()); $i++){
        $monolog->popHandler();
    }
    Log::useFiles(storage_path().'/logs/laravel.' . $level . '.log');
});

As you can see I also made the switch case obsolete by directly using the level in the filename.

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270