Skip to content

Commit

Permalink
PsrLogger
Browse files Browse the repository at this point in the history
  • Loading branch information
mabar committed Aug 6, 2019
1 parent d29fe3c commit 7533a37
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
11 changes: 11 additions & 0 deletions .docs/README.md
Expand Up @@ -8,6 +8,7 @@
- [Events](#events)
- [Bridges](#bridges)
- [Symfony\Console](#symfony-console)
- [Psr\Log](#psr-log)

## Installation

Expand Down Expand Up @@ -157,3 +158,13 @@ extensions:
From this moment when you type `bin/console`, there'll be registered commands from Doctrine DBAL.

![Commands](assets/commands.png)

### Psr\Log

Log all queries with a PSR-3 logger, e.g. [Monolog](https://github.com/contributte/monolog)

```yaml
dbal:
configuration:
sqlLogger: Nettrine\DBAL\Logger\PsrLogger()
```
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -37,6 +37,7 @@ composer require nettrine/dbal
- [Events](https://github.com/nettrine/dbal/blob/master/.docs/#events)
- [Bridges](https://github.com/nettrine/dbal/blob/master/.docs/#bridges)
- [Symfony\Console](https://github.com/nettrine/dbal/blob/master/.docs/#symfony-console)
- [Psr\Log](https://github.com/nettrine/dbal/blob/master/.docs/#psr-log)

## Maintainers

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Expand Up @@ -30,7 +30,8 @@
"phpstan/phpstan-shim": "^0.11.2",
"phpstan/phpstan-deprecation-rules": "^0.11.0",
"phpstan/phpstan-nette": "^0.11.0",
"phpstan/phpstan-strict-rules": "^0.11.0"
"phpstan/phpstan-strict-rules": "^0.11.0",
"psr/log": "^1.1"
},
"autoload": {
"psr-4": {
Expand Down
46 changes: 46 additions & 0 deletions src/Logger/PsrLogger.php
@@ -0,0 +1,46 @@
<?php declare(strict_types = 1);

namespace Nettrine\DBAL\Logger;

use Doctrine\DBAL\Logging\SQLLogger;
use Psr\Log\LoggerInterface;

class PsrLogger implements SQLLogger
{

/** @var LoggerInterface */
private $logger;

/** @var float */
private $startTime;

/** @var string */
private $query;

public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}

/**
* @param string $sql
* @param mixed[]|null $params
* @param mixed[]|null $types
* @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint
*/
public function startQuery($sql, ?array $params = null, ?array $types = null): void
{
$this->query = $sql;
$this->startTime = microtime(true);
}

public function stopQuery(): void
{
$time = round((microtime(true) - $this->startTime) * 1000);

$this->logger->debug('Query: ' . $this->query, [
'time' => sprintf('%s ms', $time),
]);
}

}

0 comments on commit 7533a37

Please sign in to comment.