|
3 | 3 | namespace danielme85\LaravelLogToDB; |
4 | 4 |
|
5 | 5 | use danielme85\LaravelLogToDB\Models\DBLogException; |
| 6 | +use Monolog\Formatter\LineFormatter; |
6 | 7 | use Monolog\Handler\AbstractProcessingHandler; |
| 8 | +use Monolog\Handler\ErrorLogHandler; |
| 9 | +use Monolog\Logger; |
7 | 10 |
|
8 | 11 | /** |
9 | 12 | * Class LogToDbHandler |
@@ -54,22 +57,25 @@ function __construct(array $config, |
54 | 57 | */ |
55 | 58 | protected function write(array $record): void |
56 | 59 | { |
57 | | - if (!empty($record)) { |
58 | | - if (!empty($record['context']['exception']) && is_object($record['context']['exception']) && |
59 | | - get_class($record['context']['exception']) === DBLogException::class) { |
60 | | - //Do nothing if empty log record or an error Exception from itself. |
61 | | - } else { |
62 | | - try { |
63 | | - $log = new LogToDB($this->config); |
64 | | - $log->newFromMonolog($record); |
65 | | - } catch (DBLogException $e) { |
66 | | - //do nothing if exception of self |
67 | | - } catch (\Throwable $e) { |
68 | | - //convert any runtime Exception while logging to a special class so we can avoid our own |
69 | | - //exceptions for 99% less infinite loops! |
70 | | - throw new DBLogException($e->getMessage()); |
71 | | - } |
72 | | - } |
| 60 | + try { |
| 61 | + $log = new LogToDB($this->config); |
| 62 | + $log->newFromMonolog($record); |
| 63 | + } catch (\Exception $e) { |
| 64 | + $this->emergencyLog([ |
| 65 | + 'message' => 'There was an error while trying to write the log to a DB, log record pushed to error_log()', |
| 66 | + 'level' => Logger::CRITICAL, |
| 67 | + 'level_name' => 'critical', |
| 68 | + 'context' => LogToDB::parseIfException(['exception' => $e]), |
| 69 | + 'extra' => [] |
| 70 | + ]); |
| 71 | + $this->emergencyLog($record); |
73 | 72 | } |
74 | 73 | } |
| 74 | + |
| 75 | + protected function emergencyLog(array $record) |
| 76 | + { |
| 77 | + $errorHandler = new ErrorLogHandler(); |
| 78 | + $errorHandler->setFormatter(new LineFormatter('%level_name%: %message% %context%')); |
| 79 | + $errorHandler->handle($record); |
| 80 | + } |
75 | 81 | } |
0 commit comments