Merge pull request #4283 from paulbalandan/errorlog-handler

Enhancements to ErrorlogHandler
This commit is contained in:
John Paul E. Balandan, CPA 2021-02-25 12:30:38 +08:00 committed by GitHub
commit 521c1cc681
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 104 additions and 31 deletions

View File

@ -129,23 +129,27 @@ class Logger extends BaseConfig
* The ChromeLoggerHandler requires the use of the Chrome web browser
* and the ChromeLogger extension. Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ]
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ],
/**
* Error Log Handler. Uncomment this block to use it.
* The ErrorlogHandler writes the logs to PHP's native `error_log()` function.
* Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ]
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /* The log levels this handler can handle. */
// 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
//
// /*
// * The message type where the error should go. Can be 0 or 4, or use the
// * class constants: `ErrorlogHandler::TYPE_OS` (0) or `ErrorlogHandler::TYPE_SAPI` (4)
// */
// 'messageType' => 0,
// ],
];
}

View File

@ -11,5 +11,6 @@
// Log language settings
return [
'invalidLogLevel' => '{0} is an invalid log level.',
'invalidLogLevel' => '{0} is an invalid log level.',
'invalidMessageType' => 'The given message type "{0}" is not supported.',
];

View File

@ -19,4 +19,9 @@ class LogException extends FrameworkException
{
return new static(lang('Log.invalidLogLevel', [$level]));
}
public static function forInvalidMessageType(string $messageType)
{
return new static(lang('Log.invalidMessageType', [$messageType]));
}
}

View File

@ -11,23 +11,51 @@
namespace CodeIgniter\Log\Handlers;
use CodeIgniter\Log\Exceptions\LogException;
/**
* Log error messages to PHP error log
* Log handler that writes to PHP's `error_log()`
*/
class ErrorlogHandler extends BaseHandler
{
/**
* Message is sent to PHP's system logger, using the Operating System's
* system logging mechanism or a file, depending on what the error_log
* configuration directive is set to.
*/
public const TYPE_OS = 0;
/**
* Constructor
* Message is sent directly to the SAPI logging handler.
*/
public const TYPE_SAPI = 4;
/**
* Says where the error should go. Currently supported are
* 0 (`TYPE_OS`) and 4 (`TYPE_SAPI`).
*
* @param array $config
* @var integer
*/
protected $messageType = 0;
/**
* Constructor.
*
* @param mixed[] $config
*/
public function __construct(array $config = [])
{
parent::__construct($config);
}
//--------------------------------------------------------------------
$messageType = $config['messageType'] ?? self::TYPE_OS;
if (! is_int($messageType) || ! in_array($messageType, [self::TYPE_OS, self::TYPE_SAPI], true))
{
throw LogException::forInvalidMessageType(print_r($messageType, true));
}
$this->messageType = $messageType;
}
/**
* Handles logging the message.
@ -42,8 +70,23 @@ class ErrorlogHandler extends BaseHandler
*/
public function handle($level, $message): bool
{
$msg = strtoupper($level) . ' --> ' . $message . "\n";
$message = strtoupper($level) . ' --> ' . $message . "\n";
return error_log($msg);
return $this->errorLog($message, $this->messageType);
}
/**
* Extracted call to `error_log()` in order to be tested.
*
* @param string $message
* @param integer $messageType
*
* @return boolean
*
* @codeCoverageIgnore
*/
protected function errorLog(string $message, int $messageType): bool
{
return error_log($message, $messageType);
}
}

View File

@ -2,18 +2,36 @@
namespace CodeIgniter\Log\Handlers;
use CodeIgniter\Log\Exceptions\LogException;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Mock\MockLogger as LoggerConfig;
use PHPUnit\Framework\MockObject\MockObject;
final class ErrorlogHandlerTest extends CIUnitTestCase
{
public function testHandle()
public function testHandlerThrowsOnInvalidMessageType(): void
{
$config = new LoggerConfig();
$this->expectException(LogException::class);
$this->getMockedHandler(['messageType' => 2]);
}
$config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical'];
public function testErrorLoggingWithErrorLog(): void
{
$logger = $this->getMockedHandler(['handles' => ['critical', 'error']]);
$logger->method('errorLog')->willReturn(true);
$logger->expects($this->once())->method('errorLog')->with("ERROR --> Test message.\n", 0);
$this->assertTrue($logger->handle('error', 'Test message.'));
}
$logger = new ErrorlogHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']);
$this->assertTrue($logger->handle('warning', 'This is a test log'));
/**
* @param array $config
*
* @return MockObject&ErrorlogHandler
*/
private function getMockedHandler(array $config = [])
{
return $this->getMockBuilder(ErrorlogHandler::class)
->onlyMethods(['errorLog'])
->setConstructorArgs([$config])
->getMock();
}
}

View File

@ -8,6 +8,7 @@ Release Date: Not released
Enhancements:
- New HTTP classes, ``Cookie`` and ``CookieStore``, for abstracting web cookies.
- New logger handler, ``ErrorlogHandler``, that writes to ``error_log()``.
Changes:

View File

@ -62,14 +62,15 @@ Using Multiple Log Handlers
---------------------------
The logging system can support multiple methods of handling logging running at the same time. Each handler can
be set to handle specific levels and ignore the rest. Currently, two handlers come with a default install:
be set to handle specific levels and ignore the rest. Currently, three handlers come with a default install:
- **File Handler** is the default handler and will create a single file for every day locally. This is the
recommended method of logging.
- **ChromeLogger Handler** If you have the `ChromeLogger extension <https://craig.is/writing/chrome-logger>`_
installed in the Chrome web browser, you can use this handler to display the log information in
Chrome's console window.
- **Errorlog Handler** this handler will log with php error_log
- **Errorlog Handler** This handler will take advantage of PHP's native ``error_log()`` function and write
the logs there. Currently, only the ``0`` and ``4`` message types of ``error_log()`` are supported.
The handlers are configured in the main configuration file, in the ``$handlers`` property, which is simply
an array of handlers and their configuration. Each handler is specified with the key being the fully