Skip to content

Commit

Permalink
Logger context
Browse files Browse the repository at this point in the history
  • Loading branch information
darkdef committed Jan 3, 2024
1 parent 064e076 commit 0857a35
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 24 deletions.
26 changes: 26 additions & 0 deletions docs/en/connection/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,29 @@ return [
```

For other DBMS refer to ["Create connecton"](/docs/en/README.md#create-connection) section.

## Advanced usage of Logger

If you needed re-define logger messages or increase(decrease) level of log:
1. Create custom logger class
2. Use context for detect type of message in method "log"

```php
<?php

declare(strict_types=1);

use Yiisoft\Db\Driver\Pdo\LogTypes;

class MyLogger extends ParentLoggerClass implements LoggerInterface
{
public function log($level, string|\Stringable $message, array $context = []): void
{
if ($context[LogTypes::KEY] === LogTypes::TYPE_QUERY) {
... your logic here
}
}

// implements other methods of LoggerInterface without changes
}
```
14 changes: 3 additions & 11 deletions src/Driver/Pdo/AbstractPdoCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,21 +255,13 @@ protected function internalGetQueryResult(int $queryMode): mixed
return $result;
}

/**
* Logs the current database query if query logging is on and returns the profiling token if profiling is on.
*/
protected function logQuery(string $rawSql, string $category): void
{
$this->logger?->log(LogLevel::INFO, $rawSql, [$category]);
}

protected function queryInternal(int $queryMode): mixed
{
$logCategory = self::class . '::' . $this->getQueryMode($queryMode);
$rawSql = $this->getRawSql();

if ($this->logger !== null) {
$rawSql = $this->getRawSql();
$this->logQuery($rawSql, $logCategory);
$this->logger?->log(LogLevel::INFO, $rawSql, [$logCategory, LogTypes::KEY => LogTypes::TYPE_QUERY]);

Check failure on line 264 in src/Driver/Pdo/AbstractPdoCommand.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.1-ubuntu-latest

TypeDoesNotContainNull

src/Driver/Pdo/AbstractPdoCommand.php:264:13: TypeDoesNotContainNull: Psr\Log\LoggerInterface does not contain null (see https://psalm.dev/090)

Check failure on line 264 in src/Driver/Pdo/AbstractPdoCommand.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.1-ubuntu-latest

RedundantCondition

src/Driver/Pdo/AbstractPdoCommand.php:264:13: RedundantCondition: Type Psr\Log\LoggerInterface for $__tmp_nullsafe__8272 is never null (see https://psalm.dev/122)

Check failure on line 264 in src/Driver/Pdo/AbstractPdoCommand.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.2-ubuntu-latest

TypeDoesNotContainNull

src/Driver/Pdo/AbstractPdoCommand.php:264:13: TypeDoesNotContainNull: Psr\Log\LoggerInterface does not contain null (see https://psalm.dev/090)

Check failure on line 264 in src/Driver/Pdo/AbstractPdoCommand.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.2-ubuntu-latest

RedundantCondition

src/Driver/Pdo/AbstractPdoCommand.php:264:13: RedundantCondition: Type Psr\Log\LoggerInterface for $__tmp_nullsafe__8272 is never null (see https://psalm.dev/122)

Check failure on line 264 in src/Driver/Pdo/AbstractPdoCommand.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.1-ubuntu-latest

TypeDoesNotContainNull

src/Driver/Pdo/AbstractPdoCommand.php:264:13: TypeDoesNotContainNull: Psr\Log\LoggerInterface does not contain null (see https://psalm.dev/090)

Check failure on line 264 in src/Driver/Pdo/AbstractPdoCommand.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.1-ubuntu-latest

RedundantCondition

src/Driver/Pdo/AbstractPdoCommand.php:264:13: RedundantCondition: Type Psr\Log\LoggerInterface for $__tmp_nullsafe__8272 is never null (see https://psalm.dev/122)
}

$queryContext = new CommandContext(__METHOD__, $logCategory, $this->getSql(), $this->getParams());
Expand All @@ -279,7 +271,7 @@ protected function queryInternal(int $queryMode): mixed
* @psalm-suppress RedundantConditionGivenDocblockType
* @psalm-suppress DocblockTypeContradiction
*/
$this->profiler?->begin($rawSql ??= $this->getRawSql(), $queryContext);
$this->profiler?->begin($rawSql, $queryContext);
try {
/** @psalm-var mixed $result */
$result = parent::queryInternal($queryMode);
Expand Down
7 changes: 4 additions & 3 deletions src/Driver/Pdo/AbstractPdoConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,13 @@ public function open(): void
$connectionContext = new ConnectionContext(__METHOD__);

try {
$this->logger?->log(LogLevel::INFO, $token);
$this->logger?->log(LogLevel::INFO, $token, [LogTypes::KEY => LogTypes::TYPE_CONNECTION]);
$this->profiler?->begin($token, $connectionContext);
$this->initConnection();
$this->profiler?->end($token, $connectionContext);
} catch (PDOException $e) {
$this->profiler?->end($token, $connectionContext->setException($e));
$this->logger?->log(LogLevel::ERROR, $token);
$this->logger?->log(LogLevel::ERROR, $token, [LogTypes::KEY => LogTypes::TYPE_CONNECTION]);

throw new Exception($e->getMessage(), (array) $e->errorInfo, $e);
}
Expand All @@ -119,6 +119,7 @@ public function close(): void
$this->logger?->log(
LogLevel::DEBUG,
'Closing DB connection: ' . $this->driver->getDsn() . ' ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_CONNECTION],
);

$this->pdo = null;
Expand Down Expand Up @@ -225,7 +226,7 @@ protected function rollbackTransactionOnLevel(TransactionInterface $transaction,
try {
$transaction->rollBack();
} catch (Throwable $e) {
$this->logger?->log(LogLevel::ERROR, (string) $e, [__METHOD__]);
$this->logger?->log(LogLevel::ERROR, (string) $e, [__METHOD__, LogTypes::KEY => LogTypes::TYPE_TRANSACTION]);
/** hide this exception to be able to continue throwing original exception outside */
}
}
Expand Down
45 changes: 35 additions & 10 deletions src/Driver/Pdo/AbstractPdoTransaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ public function begin(string $isolationLevel = null): void
$this->logger?->log(
LogLevel::DEBUG,
'Begin transaction' . ($isolationLevel ? ' with isolation level ' . $isolationLevel : '')
. ' ' . __METHOD__
. ' ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);

$this->db->getPDO()?->beginTransaction();
Expand All @@ -70,13 +71,18 @@ public function begin(string $isolationLevel = null): void
}

if ($this->db->isSavepointEnabled()) {
$this->logger?->log(LogLevel::DEBUG, 'Set savepoint ' . $this->level . ' ' . __METHOD__);
$this->logger?->log(
LogLevel::DEBUG,
'Set savepoint ' . $this->level . ' ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);

$this->createSavepoint('LEVEL' . $this->level);
} else {
$this->logger?->log(
LogLevel::DEBUG,
'Transaction not started: nested transaction not supported ' . __METHOD__
'Transaction not started: nested transaction not supported ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);

throw new NotSupportedException('Transaction not started: nested transaction not supported.');
Expand All @@ -94,19 +100,28 @@ public function commit(): void
$this->level--;

if ($this->level === 0) {
$this->logger?->log(LogLevel::DEBUG, 'Commit transaction ' . __METHOD__);
$this->logger?->log(
LogLevel::DEBUG,
'Commit transaction ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);
$this->db->getPDO()?->commit();

return;
}

if ($this->db->isSavepointEnabled()) {
$this->logger?->log(LogLevel::DEBUG, 'Release savepoint ' . $this->level . ' ' . __METHOD__);
$this->logger?->log(
LogLevel::DEBUG,
'Release savepoint ' . $this->level . ' ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);
$this->releaseSavepoint('LEVEL' . $this->level);
} else {
$this->logger?->log(
LogLevel::INFO,
'Transaction not committed: nested transaction not supported ' . __METHOD__
'Transaction not committed: nested transaction not supported ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);
}
}
Expand Down Expand Up @@ -135,19 +150,28 @@ public function rollBack(): void
$this->level--;

if ($this->level === 0) {
$this->logger?->log(LogLevel::INFO, 'Roll back transaction ' . __METHOD__);
$this->logger?->log(
LogLevel::INFO,
'Roll back transaction ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);
$this->db->getPDO()?->rollBack();

return;
}

if ($this->db->isSavepointEnabled()) {
$this->logger?->log(LogLevel::DEBUG, 'Roll back to savepoint ' . $this->level . ' ' . __METHOD__);
$this->logger?->log(
LogLevel::DEBUG,
'Roll back to savepoint ' . $this->level . ' ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);
$this->rollBackSavepoint('LEVEL' . $this->level);
} else {
$this->logger?->log(
LogLevel::INFO,
'Transaction not rolled back: nested transaction not supported ' . __METHOD__
'Transaction not rolled back: nested transaction not supported ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]
);
}
}
Expand All @@ -160,7 +184,8 @@ public function setIsolationLevel(string $level): void

$this->logger?->log(
LogLevel::DEBUG,
'Setting transaction isolation level to ' . $this->level . ' ' . __METHOD__
'Setting transaction isolation level to ' . $this->level . ' ' . __METHOD__,
[LogTypes::KEY => LogTypes::TYPE_TRANSACTION]

Check warning on line 188 in src/Driver/Pdo/AbstractPdoTransaction.php

View check run for this annotation

Codecov / codecov/patch

src/Driver/Pdo/AbstractPdoTransaction.php#L187-L188

Added lines #L187 - L188 were not covered by tests
);
$this->setTransactionIsolationLevel($level);
}
Expand Down
14 changes: 14 additions & 0 deletions src/Driver/Pdo/LogTypes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Db\Driver\Pdo;

class LogTypes
{
public const KEY = 'log-type';

public const TYPE_CONNECTION = 'connection';
public const TYPE_QUERY = 'query';
public const TYPE_TRANSACTION = 'transaction';
}

0 comments on commit 0857a35

Please sign in to comment.