Skip to content

Commit

Permalink
Logging debug message in debug job
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrajodas committed May 29, 2023
1 parent 6a4a473 commit a230385
Show file tree
Hide file tree
Showing 7 changed files with 128 additions and 22 deletions.
3 changes: 2 additions & 1 deletion example/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

use Keboola\Component\Logger;
use Keboola\Component\UserException;
use MyComponent\Component;

require __DIR__ . '/../vendor/autoload.php';

$logger = new Logger();
try {
$app = new MyComponent\Component($logger);
$app = new Component($logger);
$app->execute();
exit(0);
} catch (UserException $e) {
Expand Down
4 changes: 2 additions & 2 deletions src/BaseComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,11 @@ protected function initializeSyncActions(): void
}
if ($this->isSyncAction()) {
if ($this->logger instanceof SyncActionLogging) {
$this->logger->setupSyncActionLogging();
$this->logger->setupSyncActionLogging($this->config->getEnvComponentRunMode());
}
} else {
if ($this->logger instanceof AsyncActionLogging) {
$this->logger->setupAsyncActionLogging();
$this->logger->setupAsyncActionLogging($this->config->getEnvComponentRunMode());
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/Config/BaseConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ class BaseConfig implements ConfigInterface
{
protected array $config;

public const COMPONENT_RUN_MODE_RUN = 'run';

public const COMPONENT_RUN_MODE_DEBUG = 'debug';

private ConfigurationInterface $configDefinition;

/**
Expand Down Expand Up @@ -236,6 +240,11 @@ public function getEnvKbcStagingFileProvider(): string
return (string) getenv('KBC_STAGING_FILE_PROVIDER');
}

public function getEnvComponentRunMode(): string
{
return (string) getenv('KBC_COMPONENT_RUN_MODE');
}

public function getEncKbcProjectName(): string
{
$env = getenv('KBC_PROJECTNAME');
Expand Down
58 changes: 41 additions & 17 deletions src/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Keboola\Component;

use Keboola\Component\Config\BaseConfig;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger as MonologLogger;
Expand Down Expand Up @@ -37,6 +38,15 @@ public static function getDefaultCriticalHandler(): StreamHandler
return $handler;
}

public static function getDefaultDebugHandler(): StreamHandler
{
$handler = new StreamHandler('php://stdout');
$handler->setBubble(false);
$handler->setLevel(MonologLogger::DEBUG);
$handler->setFormatter(new LineFormatter("[%datetime%] %level_name%: %message% %context% %extra%\n"));
return $handler;
}

public static function getSyncActionErrorHandler(): StreamHandler
{
$logHandler = new StreamHandler('php://stderr');
Expand All @@ -55,6 +65,15 @@ public static function getSyncActionCriticalHandler(): StreamHandler
return $logHandler;
}

public static function getSyncActionDebugHandler(): StreamHandler
{
$logHandler = new StreamHandler('php://stdout');
$logHandler->setBubble(false);
$logHandler->setLevel(MonologLogger::DEBUG);
$logHandler->setFormatter(new LineFormatter("[%datetime%] %level_name%: %message% %context% %extra%\n"));
return $logHandler;
}

public function __construct()
{
parent::__construct('php-component');
Expand All @@ -67,27 +86,32 @@ public function __construct()
$this->pushHandler($logHandler);
}

public function setupSyncActionLogging(): void
public function setupSyncActionLogging(string $componentRunMode = BaseConfig::COMPONENT_RUN_MODE_RUN): void
{
$criticalHandler = self::getSyncActionCriticalHandler();
$errorHandler = self::getSyncActionErrorHandler();
$handlers = [
self::getSyncActionCriticalHandler(),
self::getSyncActionErrorHandler(),
];

$this->setHandlers([
$criticalHandler,
$errorHandler,
]);
if ($componentRunMode === BaseConfig::COMPONENT_RUN_MODE_DEBUG) {
$handlers[] = self::getSyncActionDebugHandler();
}

$this->setHandlers($handlers);
}

public function setupAsyncActionLogging(): void
public function setupAsyncActionLogging(string $componentRunMode = BaseConfig::COMPONENT_RUN_MODE_RUN): void
{
$criticalHandler = self::getDefaultCriticalHandler();
$errorHandler = self::getDefaultErrorHandler();
$logHandler = self::getDefaultLogHandler();

$this->setHandlers([
$criticalHandler,
$errorHandler,
$logHandler,
]);
$handlers = [
self::getDefaultCriticalHandler(),
self::getDefaultErrorHandler(),
self::getDefaultLogHandler(),
];

if ($componentRunMode === BaseConfig::COMPONENT_RUN_MODE_DEBUG) {
$handlers[] = self::getDefaultDebugHandler();
}

$this->setHandlers($handlers);
}
}
4 changes: 3 additions & 1 deletion src/Logger/AsyncActionLogging.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

namespace Keboola\Component\Logger;

use Keboola\Component\Config\BaseConfig;

interface AsyncActionLogging
{
public function setupAsyncActionLogging(): void;
public function setupAsyncActionLogging(string $componentRunMode = BaseConfig::COMPONENT_RUN_MODE_RUN): void;
}
4 changes: 3 additions & 1 deletion src/Logger/SyncActionLogging.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

namespace Keboola\Component\Logger;

use Keboola\Component\Config\BaseConfig;

interface SyncActionLogging
{
/**
* Sync actions MUST NOT output anything to stdout
*/
public function setupSyncActionLogging(): void;
public function setupSyncActionLogging(string $componentRunMode = BaseConfig::COMPONENT_RUN_MODE_RUN): void;
}
68 changes: 68 additions & 0 deletions tests/Logger/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
namespace Keboola\Component\Tests\Logger;

use DateTimeImmutable;
use Keboola\Component\Config\BaseConfig;
use Keboola\Component\Logger;
use Monolog\Handler\StreamHandler;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;

class LoggerTest extends TestCase
Expand Down Expand Up @@ -86,6 +88,72 @@ public function testSetupSyncActionLogging(): void
);
}

public function testDebugLogging(): void
{
$logger = new Logger();
$logger->setupAsyncActionLogging(BaseConfig::COMPONENT_RUN_MODE_DEBUG);

$handlers = $logger->getHandlers();

$this->assertCount(4, $handlers);

// Init streams (stream is created with first message)
$logger->critical('');
$logger->error('');
$logger->info('');
$logger->debug('');

/** @var StreamHandler $handlerCritical */
$handlerCritical = $handlers[0];
/** @var StreamHandler $handlerError */
$handlerError = $handlers[1];
/** @var StreamHandler $handlerLog */
$handlerLog = $handlers[2];
/** @var StreamHandler $handlerDebug */
$handlerDebug = $handlers[3];

// Connect tester (logger) to the streams
/** @var resource $streamCritical */
$streamCritical = $handlerCritical->getStream();
/** @var resource $streamError */
$streamError = $handlerError->getStream();
/** @var resource $streamLog */
$streamLog = $handlerLog->getStream();
/** @var resource $streamDebug */
$streamDebug = $handlerDebug->getStream();
StreamTester::attach($streamCritical);
StreamTester::attach($streamError);
StreamTester::attach($streamLog);
StreamTester::attach($streamDebug);

// Log some messages
$logger->info('Info!', ['context' => 'info']);
$logger->error('Error!', ['context' => 'error']);
$logger->critical('Critical!', ['context' => 'critical']);
$logger->debug('Debug message!', ['context' => 'debug context']);

Assert::assertStringContainsString('Info!', StreamTester::getContent());
Assert::assertStringContainsString('Error!', StreamTester::getContent());
Assert::assertStringContainsString(
'CRITICAL: Critical! {"context":"critical"}',
StreamTester::getContent()
);
Assert::assertStringContainsString(
'DEBUG: Debug message! {"context":"debug context"}',
StreamTester::getContent()
);

$this->assertSame(Logger::CRITICAL, $handlerCritical->getLevel());
$this->assertSame(Logger::WARNING, $handlerError->getLevel());
$this->assertSame(Logger::INFO, $handlerLog->getLevel());
$this->assertSame(Logger::DEBUG, $handlerDebug->getLevel());

$this->assertSame('php://stderr', $handlerCritical->getUrl());
$this->assertSame('php://stderr', $handlerError->getUrl());
$this->assertSame('php://stdout', $handlerLog->getUrl());
$this->assertSame('php://stdout', $handlerDebug->getUrl());
}

public function testSetupAsyncActionLogging(): void
{
$logger = new Logger();
Expand Down

0 comments on commit a230385

Please sign in to comment.