Created
March 1, 2024 17:14
-
-
Save levi730/e72cccbfa44b795cc68519e4643db8d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
/* | |
* This file is part of the Monolog package. | |
* | |
* (c) Jordi Boggiano <[email protected]> | |
* | |
* For the full copyright and license information, please view the LICENSE | |
* file that was distributed with this source code. | |
*/ | |
namespace App; | |
use DateTimeInterface; | |
use Monolog\LogRecord; | |
/** | |
* Encodes message information into JSON in a format compatible with Cloud logging. | |
* | |
* @see https://cloud.google.com/logging/docs/structured-logging | |
* @see https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry | |
* | |
* @author Luís Cobucci <[email protected]> | |
*/ | |
final class GoogleCloudWithStackTraceLoggingFormatter extends \Monolog\Formatter\JsonFormatter | |
{ | |
protected function normalizeRecord(LogRecord $record): array | |
{ | |
$normalized = parent::normalizeRecord($record); | |
//The base "normalizeRecord" also strips out the stack trace. Here, we're putting it back in. | |
if(array_key_exists('exception', $record['context'])) { | |
$exception_rec = [ | |
'message' => $record['context']['exception']->getMessage(), | |
'code' => $record['context']['exception']->getCode(), | |
'file' => $record['context']['exception']->getFile(), | |
'line' => $record['context']['exception']->getLine(), | |
'trace' => $record['context']['exception']->getTrace(), | |
]; | |
$normalized['context']['exception'] = $exception_rec; | |
} | |
// Re-key level for GCP logging | |
$normalized['severity'] = $normalized['level_name']; | |
$normalized['time'] = $record->datetime->format(DateTimeInterface::RFC3339_EXTENDED); | |
// Remove keys that are not used by GCP | |
unset($normalized['level'], $normalized['level_name'], $normalized['datetime']); | |
return $normalized; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment