在 Laravel 日志中记录 PHP 异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24898790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Log PHP exceptions in Laravel Log
提问by martinezjc
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.
我开始在 Laravel 4 中为我的应用程序创建自定义日志功能,对于自定义消息一切正常,但是当我尝试在其中记录异常消息时,try..catch(Exception $e)
不会在日志文件中写入此异常。
<?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?
有人可以帮我解决这个问题吗,我做错了什么?
采纳答案by Gaz_Edge
Have you tried testing your Api\ApplicationEvents\LogWritter::write( $exception, 'Error');
code in isolation?
您是否尝试过单独测试您的Api\ApplicationEvents\LogWritter::write( $exception, 'Error');
代码?
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);
}