我开始在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);
}
}
?>
该功能的调用就是这样:
try {
// code goes here
} catch (Exception $e) {
$exception = $e->getMessage();
Api\ApplicationEvents\LogWritter::write( $exception, 'Error');
}
但是现在无法在日志文件
中编写异常消息有人可以帮助我做正确的事吗,我做错了什么?
答案 0 :(得分:1)
您是否尝试过单独测试Api\ApplicationEvents\LogWritter::write( $exception, 'Error');
代码?
e.g。试试这个来测试代码的工作原理
try {
throw new RuntimeException()
} catch (Exception $e) {
$exception = $e->getMessage();
Api\ApplicationEvents\LogWritter::write( $exception, 'Error');
}
如果情况正常,你就知道你的班级和方法没有任何问题。
编辑:
试试这个:
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);
}