Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log PHP exceptions in Laravel Log

I'm starting to create a custom log feature for my application in Laravel 4 everything works fine for custom messages but when i try to log the exception messages within try..catch(Exception $e) doesn't write this exception on the log file.

<?php namespace Api\ApplicationEvents;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class LogWritter {

    public static function write( $logMessage, $logLevel)
    {
        $date = date('d_m_y');

        $logFile = public_path() . '\logs\log_' . $date . '.log';

        if ( !file_exists($logFile)) {
            $fp = fopen($logFile, 'w');
            fwrite($fp, '');
            fclose($fp);
        }

        $log = new Logger('Menu App Log: ');

        switch ($logLevel) {
            case 'Info':
                $log->pushHandler( new StreamHandler($logFile, Logger::INFO) ); 
                break;

            case 'Warn':
                $log->pushHandler( new StreamHandler($logFile, Logger::WARNING) ); 
                break;

            case 'Error':
                $log->pushHandler( new StreamHandler($logFile, Logger::ERROR) ); 
                break;
        }

        $log->addInfo($logMessage);
    }
}
?>

The call of the function is like that:

try { 
// code goes here 
} catch (Exception $e) {
   $exception = $e->getMessage();
   Api\ApplicationEvents\LogWritter::write( $exception, 'Error');
}

But for now can't write the exception message in the log file

Can somebody help me to get this going right, what am i doing wrong?

like image 326
martinezjc Avatar asked Nov 10 '22 04:11

martinezjc


1 Answers

Have you tried testing your Api\ApplicationEvents\LogWritter::write( $exception, 'Error'); code in isolation?

e.g. try this to test your code works

try { 
  throw new RuntimeException() 
} catch (Exception $e) {
   $exception = $e->getMessage();
   Api\ApplicationEvents\LogWritter::write( $exception, 'Error');
}

If that works fine you know there is nothing wrong with your class and method.

Edit:

Try this:

switch ($logLevel) {
    case 'Warn':
        $log->pushHandler( new StreamHandler($logFile, Logger::WARNING) ); 
        $log->addWarning($logMessage);
        break;

    case 'Error':
        $log->pushHandler( new StreamHandler($logFile, Logger::ERROR) ); 
        $log->addError($logMessage);            
        break;

    default:
        $log->pushHandler( new StreamHandler($logFile, Logger::INFO) ); 
        $log->addInfo($logMessage);
}
like image 177
GWed Avatar answered Nov 12 '22 19:11

GWed