-
Notifications
You must be signed in to change notification settings - Fork 56
Add a PSR-3 logger and support any PSR-3 logger #265
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
c39b1a6
First pass
pbowyer 5ba82c7
Always initialise xPDOLogger; extend tests
pbowyer eda4a17
Revisions to clean xPDO
pbowyer 69a290a
Change composer.json to support PHP 7.2.5+
pbowyer ddfba9e
Add logger to the container
pbowyer a3e952f
Test legacy logging
pbowyer 4ade225
Simplify logger initialization
pbowyer 1d940cd
Extend historic logging
pbowyer 2b27918
Fix regression in fatal logging, where the output was incorrect
pbowyer 134e0b4
Re-enable xPDOLoggerTest
pbowyer 44a54dd
Strip back additions to xPDO, use PSR3 logger only when in container
pbowyer 1382862
Compact into one method
pbowyer b6a5085
xPDO: remove unused resolveLogLocation helper
pbowyer c6ab4d9
xPDO: reduce backtrace overhead when resolving log location
pbowyer 5cb1309
Merge branch '3.x-psr-logger-take2' into 3.x-psr-logger
pbowyer 73c307e
Reduce backtrace overhead further
pbowyer 126e675
Allow psr/log ^3.0
pbowyer 4bcbbbb
Bugfix: debug_backtrace() was off by 1
pbowyer 5c94182
Add docblocks to public methods
opengeek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,300 @@ | ||
| <?php | ||
| /** | ||
| * This file is part of the xPDO package. | ||
| * | ||
| * Copyright (c) Jason Coward <jason@opengeek.com> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace xPDO\Logging; | ||
|
|
||
| use Psr\Log\AbstractLogger; | ||
| use Psr\Log\LogLevel; | ||
| use xPDO\Cache\xPDOCacheManager; | ||
| use xPDO\xPDO; | ||
|
|
||
| /** | ||
| * Minimal PSR-3 logger that preserves the legacy xPDO line format. | ||
| * | ||
| * Context interpolation replaces {placeholders} using stringified values: | ||
| * scalars are cast, DateTimeInterface uses DATE_ATOM, and arrays/objects | ||
| * fall back to print_r(). | ||
| */ | ||
| class xPDOLogger extends AbstractLogger | ||
| { | ||
| /** | ||
| * @var xPDO | ||
| */ | ||
| protected $xpdo; | ||
| /** | ||
| * @var string|array|null | ||
| */ | ||
| protected $target = null; | ||
| /** | ||
| * @var array | ||
| */ | ||
| protected $targetOptions = array(); | ||
|
|
||
| /** | ||
| * xPDOLogger constructor. | ||
| * | ||
| * @param xPDO $xpdo The xPDO instance used for configuration and debugging. | ||
| * @param array $options Optional logger configuration: | ||
| * - 'target' (string|array|null): Log destination or destinations. | ||
| * - 'target_options' (array): Options specific to the configured target(s). | ||
| */ | ||
| public function __construct(xPDO $xpdo, array $options = array()) | ||
| { | ||
| $this->xpdo = $xpdo; | ||
| if (array_key_exists('target', $options)) { | ||
| $this->target = $options['target']; | ||
| } | ||
| if (array_key_exists('target_options', $options) && is_array($options['target_options'])) { | ||
| $this->targetOptions = $options['target_options']; | ||
| } | ||
| } | ||
|
|
||
|
opengeek marked this conversation as resolved.
|
||
| /** | ||
| * Handles logging using the legacy xPDO format. | ||
| * | ||
| * For fatal log levels, all output buffers are flushed and the script | ||
| * exits immediately after writing the formatted log message. For other | ||
| * levels, the message is delegated to {@see log()} with a context | ||
| * payload that preserves legacy xPDO fields. | ||
| * | ||
| * @param int|string $level Numeric or string log level (xPDO or PSR-3 style). | ||
| * @param string $msg Log message to record. | ||
| * @param string $target Optional log target identifier. | ||
| * @param string $def Optional log message definition or label. | ||
| * @param string $file Optional file name associated with the log entry. | ||
| * @param string|int $line Optional line number associated with the log entry. | ||
| * | ||
| * @return void | ||
| */ | ||
| public function handleXpdo($level, $msg, $target= '', $def= '', $file= '', $line= '') | ||
| { | ||
| if ($level === xPDO::LOG_LEVEL_FATAL) { | ||
| while (ob_get_level() && @ob_end_flush()) {} | ||
| exit ('[' . date('Y-m-d H:i:s') . '] (' . $this->getLegacyLevelLabel($level) . $def . $file . $line . ') ' . $msg . "\n" . ($this->xpdo->getDebug() === true ? '<pre>' . "\n" . print_r(debug_backtrace(), true) . "\n" . '</pre>' : '')); | ||
| } | ||
| $context = array( | ||
| 'def' => $def, | ||
| 'file' => $file, | ||
| 'line' => $line, | ||
| 'xpdo_legacy' => true, | ||
| ); | ||
| if (!empty($target)) { | ||
| $context['target'] = $target; | ||
| } | ||
| $this->log($level, $msg, $context); | ||
| } | ||
|
|
||
| /** | ||
| * Logs with an arbitrary level. | ||
| * | ||
| * @param int|string $level | ||
| * @param mixed $message | ||
| * @param array $context | ||
| * @return void | ||
| */ | ||
| public function log($level, $message, array $context = array()): void | ||
| { | ||
| $isLegacy = !empty($context['xpdo_legacy']); | ||
| if ($isLegacy) { | ||
| unset($context['xpdo_legacy']); | ||
| $legacyLevel = is_int($level) ? $level : intval($level); | ||
| } else { | ||
| $legacyLevel = $this->mapPsrLevel($level); | ||
| } | ||
| if (!$this->shouldLog($legacyLevel)) { | ||
| return; | ||
| } | ||
|
|
||
| $def = isset($context['def']) ? $context['def'] : ''; | ||
| $file = isset($context['file']) ? $context['file'] : ''; | ||
| $line = isset($context['line']) ? $context['line'] : ''; | ||
| list($file, $line) = $this->resolveLogLocation($file, $line); | ||
|
|
||
| $target = $this->resolveTarget($context); | ||
| $targetOptions = $this->targetOptions; | ||
| if (is_array($target)) { | ||
| $targetOptions = array(); | ||
| if (isset($target['options'])) { | ||
| $targetOptions = &$target['options']; | ||
| } | ||
| $target = isset($target['target']) ? $target['target'] : 'ECHO'; | ||
| } | ||
|
|
||
| $levelText = $this->getLegacyLevelLabel($legacyLevel); | ||
| $defText = !empty($def) ? " in {$def}" : ''; | ||
| $fileText = !empty($file) ? " @ {$file}" : ''; | ||
| $lineText = !empty($line) ? " : {$line}" : ''; | ||
|
|
||
| $messageText = $isLegacy ? $message : $this->formatMessage($message, $context); | ||
|
|
||
| if ($target === 'HTML') { | ||
| $content = '<h5>[' . date('Y-m-d H:i:s') . '] (' . $levelText . $defText . $fileText . $lineText . ')</h5><pre>' . $messageText . '</pre>' . "\n"; | ||
| } else { | ||
| $content = '[' . date('Y-m-d H:i:s') . '] (' . $levelText . $defText . $fileText . $lineText . ') ' . $messageText . "\n"; | ||
| } | ||
|
|
||
| if ($this->writeToTarget($target, $targetOptions, $content, $levelText, $messageText, $defText, $fileText, $lineText)) { | ||
| return; | ||
| } | ||
|
|
||
| echo $content; | ||
| } | ||
|
|
||
| protected function shouldLog($legacyLevel): bool | ||
| { | ||
| if ($this->xpdo->getDebug() === true) { | ||
| return true; | ||
| } | ||
| if ($legacyLevel === xPDO::LOG_LEVEL_FATAL) { | ||
| return true; | ||
| } | ||
| return $legacyLevel <= $this->xpdo->getLogLevel(); | ||
| } | ||
|
|
||
| protected function resolveTarget(array $context) | ||
| { | ||
| if (array_key_exists('target', $context)) { | ||
| return $context['target']; | ||
| } | ||
| if ($this->target !== null) { | ||
| return $this->target; | ||
| } | ||
| return $this->xpdo->getLogTarget(); | ||
| } | ||
|
|
||
| protected function writeToTarget($target, & $targetOptions, $content, $levelText, $messageText, $defText, $fileText, $lineText): bool | ||
| { | ||
| if ($target === 'FILE' && $this->xpdo->getCacheManager()) { | ||
| $filename = isset($targetOptions['filename']) ? $targetOptions['filename'] : 'error.log'; | ||
| $filepath = isset($targetOptions['filepath']) ? $targetOptions['filepath'] : $this->xpdo->getCachePath() . xPDOCacheManager::LOG_DIR; | ||
| $this->xpdo->cacheManager->writeFile($filepath . $filename, $content, 'a'); | ||
| return true; | ||
| } | ||
|
|
||
| if ( | ||
| $target === 'ARRAY' && | ||
| isset($targetOptions['var']) && | ||
| (is_array($targetOptions['var']) || $targetOptions['var'] instanceof \ArrayAccess) | ||
| ) { | ||
| $targetOptions['var'][] = $content; | ||
| return true; | ||
| } | ||
|
|
||
| if ( | ||
| $target === 'ARRAY_EXTENDED' && | ||
| isset($targetOptions['var']) && | ||
| (is_array($targetOptions['var']) || $targetOptions['var'] instanceof \ArrayAccess) | ||
| ) { | ||
| $targetOptions['var'][] = array( | ||
| 'content' => $content, | ||
| 'level' => $levelText, | ||
| 'msg' => $messageText, | ||
| 'def' => $defText, | ||
| 'file' => $fileText, | ||
| 'line' => $lineText, | ||
| ); | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| protected function formatMessage($message, array $context): string | ||
| { | ||
| $messageText = $this->stringifyValue($message); | ||
| if (strpos($messageText, '{') === false) { | ||
| return $messageText; | ||
| } | ||
|
|
||
| $replace = array(); | ||
| foreach ($context as $key => $value) { | ||
| $replace['{' . $key . '}'] = $this->stringifyValue($value); | ||
| } | ||
|
|
||
| return strtr($messageText, $replace); | ||
| } | ||
|
|
||
| protected function stringifyValue($value): string | ||
| { | ||
| if (is_string($value)) { | ||
| return $value; | ||
| } | ||
| if (is_null($value)) { | ||
| return 'null'; | ||
| } | ||
| if (is_bool($value)) { | ||
| return $value ? 'true' : 'false'; | ||
| } | ||
| if (is_int($value) || is_float($value)) { | ||
| return (string) $value; | ||
| } | ||
| if ($value instanceof \DateTimeInterface) { | ||
| return $value->format(DATE_ATOM); | ||
| } | ||
| if (is_object($value) && method_exists($value, '__toString')) { | ||
| return (string) $value; | ||
| } | ||
| return print_r($value, true); | ||
| } | ||
|
|
||
| protected function resolveLogLocation($file, $line): array | ||
| { | ||
| if (empty($file)) { | ||
| $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); | ||
| if ($backtrace && isset($backtrace[2])) { | ||
| $file = $backtrace[2]['file']; | ||
| $line = $backtrace[2]['line']; | ||
| } | ||
| } | ||
| if (empty($file) && isset($_SERVER['SCRIPT_NAME'])) { | ||
| $file = $_SERVER['SCRIPT_NAME']; | ||
| } | ||
| return array($file, $line); | ||
| } | ||
|
|
||
| protected function mapPsrLevel($level): int | ||
| { | ||
| $level = strtolower((string) $level); | ||
| switch ($level) { | ||
| case LogLevel::DEBUG: | ||
| return xPDO::LOG_LEVEL_DEBUG; | ||
| case LogLevel::INFO: | ||
| return xPDO::LOG_LEVEL_INFO; | ||
| case LogLevel::NOTICE: | ||
| return xPDO::LOG_LEVEL_INFO; | ||
| case LogLevel::WARNING: | ||
| return xPDO::LOG_LEVEL_WARN; | ||
| case LogLevel::ERROR: | ||
| return xPDO::LOG_LEVEL_ERROR; | ||
| case LogLevel::CRITICAL: | ||
| case LogLevel::ALERT: | ||
| case LogLevel::EMERGENCY: | ||
| return xPDO::LOG_LEVEL_FATAL; | ||
| default: | ||
| return xPDO::LOG_LEVEL_INFO; | ||
| } | ||
| } | ||
|
|
||
| protected function getLegacyLevelLabel($legacyLevel): string | ||
| { | ||
| switch ($legacyLevel) { | ||
| case xPDO::LOG_LEVEL_DEBUG: | ||
| return 'DEBUG'; | ||
| case xPDO::LOG_LEVEL_INFO: | ||
| return 'INFO'; | ||
| case xPDO::LOG_LEVEL_WARN: | ||
| return 'WARN'; | ||
| case xPDO::LOG_LEVEL_ERROR: | ||
| return 'ERROR'; | ||
| default: | ||
| return 'FATAL'; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.