Skip to content

Commit

Permalink
Logger context (#794)
Browse files Browse the repository at this point in the history
* Logger context

Co-authored-by: Alexander Makarov <[email protected]>
Co-authored-by: Sergei Predvoditelev <[email protected]>
  • Loading branch information
3 people authored Jan 21, 2024
1 parent 38c9090 commit ef81e8b
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 15 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- Bug #788: Fix casting integer to string in `AbstractCommand::getRawSql()` (@Tigrov)
- Enh #789: Remove unnecessary type casting to array in `AbstractDMLQueryBuilder::getTableUniqueColumnNames()` (@Tigrov)
- Enh #795: Allow to use `DMLQueryBuilderInterface::batchInsert()` method with empty columns (@Tigrov)
- Enh #794: Add message type to log context (@darkdef)

## 1.2.0 November 12, 2023

Expand Down
27 changes: 27 additions & 0 deletions docs/en/connection/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,30 @@ return [
```

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

## Advanced usage of Logger

If you need to redefine logger messages or increase/decrease logging level:

1. Create a custom logger class
2. Use the context to detect type of the message in the "log" method

```php
<?php

declare(strict_types=1);

use Yiisoft\Db\Driver\Pdo\LogType;

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

// implements other methods of LoggerInterface without changes
}
```
2 changes: 1 addition & 1 deletion src/Driver/Pdo/AbstractPdoCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ protected function internalGetQueryResult(int $queryMode): mixed
*/
protected function logQuery(string $rawSql, string $category): void
{
$this->logger?->log(LogLevel::INFO, $rawSql, [$category]);
$this->logger?->log(LogLevel::INFO, $rawSql, [$category, 'type' => LogType::QUERY]);
}

protected function queryInternal(int $queryMode): mixed
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, ['type' => LogType::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, ['type' => LogType::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__,
['type' => LogType::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__, 'type' => LogType::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 : '')

Check failure on line 62 in src/Driver/Pdo/AbstractPdoTransaction.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.1-ubuntu-latest

RiskyTruthyFalsyComparison

src/Driver/Pdo/AbstractPdoTransaction.php:62:40: RiskyTruthyFalsyComparison: Operand of type null|string contains type string, which can be falsy and truthy. This can cause possibly unexpected behavior. Use strict comparison instead. (see https://psalm.dev/356)
. ' ' . __METHOD__
. ' ' . __METHOD__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::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__,
['type' => LogType::TRANSACTION]
);
$this->setTransactionIsolationLevel($level);
}
Expand Down
12 changes: 12 additions & 0 deletions src/Driver/Pdo/LogType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Db\Driver\Pdo;

final class LogType
{
public const CONNECTION = 'connection';
public const QUERY = 'query';
public const TRANSACTION = 'transaction';
}
2 changes: 1 addition & 1 deletion tests/Common/CommonPdoCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ protected function createQueryLogger(string $sql, array $params = []): LoggerInt
->with(
LogLevel::INFO,
$sql,
$params
$params + ['type' => 'query']
);
return $logger;
}
Expand Down

0 comments on commit ef81e8b

Please sign in to comment.