Skip to content

Commit

Permalink
Update logging
Browse files Browse the repository at this point in the history
  • Loading branch information
odan committed Oct 25, 2023
1 parent 7bd5b8e commit 75dc0e0
Show file tree
Hide file tree
Showing 12 changed files with 29 additions and 276 deletions.
4 changes: 1 addition & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@
"nyholm/psr7-server": "^1.0",
"php-di/php-di": "^7",
"selective/basepath": "^2",
"slim/slim": "^4",
"symfony/uid": "^6"
"slim/slim": "^4"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3",
"mikey179/vfsstream": "^1.6",
"phpstan/phpstan": "1.*",
"phpunit/phpunit": "^10",
"selective/test-traits": "^4",
Expand Down
31 changes: 20 additions & 11 deletions config/container.php
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
<?php

use App\Factory\LoggerFactory;
use App\Handler\DefaultErrorHandler;
use Cake\Database\Connection;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Log\LoggerInterface;
use Selective\BasePath\BasePathMiddleware;
use Slim\App;
use Slim\Factory\AppFactory;
Expand Down Expand Up @@ -60,11 +63,6 @@
return $container->get(App::class)->getRouteCollector()->getRouteParser();
},

// The logger factory
LoggerFactory::class => function (ContainerInterface $container) {
return new LoggerFactory($container->get('settings')['logger']);
},

BasePathMiddleware::class => function (ContainerInterface $container) {
return new BasePathMiddleware($container->get(App::class));
},
Expand All @@ -84,21 +82,32 @@
return $method->invoke($driver);
},

LoggerInterface::class => function (ContainerInterface $container) {
$settings = $container->get('settings')['logger'];

$logger = new Logger('app');

if (isset($settings['path'])) {
$filename = sprintf('%s/app.log', $settings['path']);
$level = $settings['level'];
$rotatingFileHandler = new RotatingFileHandler($filename, 0, $level, true, 0777);
$rotatingFileHandler->setFormatter(new LineFormatter(null, null, false, true));
$logger->pushHandler($rotatingFileHandler);
}

return $logger;
},

ErrorMiddleware::class => function (ContainerInterface $container) {
$settings = $container->get('settings')['error'];
$app = $container->get(App::class);

$logger = $container->get(LoggerFactory::class)
->addFileHandler('error.log')
->createLogger();

$errorMiddleware = new ErrorMiddleware(
$app->getCallableResolver(),
$app->getResponseFactory(),
(bool)$settings['display_error_details'],
(bool)$settings['log_errors'],
(bool)$settings['log_error_details'],
$logger
);

$errorMiddleware->setDefaultErrorHandler($container->get(DefaultErrorHandler::class));
Expand Down
62 changes: 2 additions & 60 deletions docs/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,72 +13,14 @@ To help you learn more about what's happening within your application,
this Slim skeleton provides robust logging services that allow you to log messages to files,
the system error log, and even to Slack to notify your entire team.

Under the hood, this project utilizes the [Monolog](https://github.com/Seldaek/monolog) library,
This project uses the [Monolog](https://seldaek.github.io/monolog/) package,
which provides support for a variety of powerful log handlers.

## Configuration

The directory for all log files is: `logs/`

The default settings are stored in `config/defaults.php`, `$settings['logger']`

## Usage

It's recommended using the `App\Factory\LoggerFactory` class to
create a custom logger for each context.

The `LoggerFactory` provides methods to generate a
file- and console based logging output.

Inject the `LoggerFactory` instance and generate a specific logger as follows:

```php
<?php

use App\Factory\LoggerFactory;
use Psr\Log\LoggerInterface;

final class Example
{
private LoggerInterface $logger;

// ...

public function __construct(LoggerFactory $loggerFactory) {
$this->logger = $loggerFactory
->addFileHandler('my_log_file.log')
->createLogger();
}

// ...
}
```

Creating a file logger:

```php
$this->logger = $loggerFactory->addFileHandler('my_log_file.log')->createInstance();
$this->logger->info('Test');
```

Creating a console logger:

```php
$this->logger = $loggerFactory->addConsoleHandler()->createInstance();
$this->logger->info('Console test output');
```


Creating a file and console logger:

```php
$this->logger = $loggerFactory
->addFileHandler('my_log_file.log')
->addConsoleHandler()
->createInstance();

$this->logger->info('File and console output');
```
The directory for all log files is: `logs/`

## Read more

Expand Down
7 changes: 2 additions & 5 deletions src/Domain/Customer/Service/CustomerCreator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace App\Domain\Customer\Service;

use App\Domain\Customer\Repository\CustomerRepository;
use App\Factory\LoggerFactory;
use Psr\Log\LoggerInterface;

final class CustomerCreator
Expand All @@ -17,13 +16,11 @@ final class CustomerCreator
public function __construct(
CustomerRepository $repository,
CustomerValidator $customerValidator,
LoggerFactory $loggerFactory
LoggerInterface $logger
) {
$this->repository = $repository;
$this->customerValidator = $customerValidator;
$this->logger = $loggerFactory
->addFileHandler('customer_creator.log')
->createLogger();
$this->logger = $logger;
}

public function createCustomer(array $data): int
Expand Down
7 changes: 2 additions & 5 deletions src/Domain/Customer/Service/CustomerUpdater.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace App\Domain\Customer\Service;

use App\Domain\Customer\Repository\CustomerRepository;
use App\Factory\LoggerFactory;
use DomainException;
use Psr\Log\LoggerInterface;

Expand All @@ -18,13 +17,11 @@ final class CustomerUpdater
public function __construct(
CustomerRepository $repository,
CustomerValidator $customerValidator,
LoggerFactory $loggerFactory
LoggerInterface $logger
) {
$this->repository = $repository;
$this->customerValidator = $customerValidator;
$this->logger = $loggerFactory
->addFileHandler('customer_updater.log')
->createLogger();
$this->logger = $logger;
}

public function updateCustomer(int $customerId, array $data): void
Expand Down
77 changes: 0 additions & 77 deletions src/Factory/LoggerFactory.php

This file was deleted.

7 changes: 2 additions & 5 deletions src/Handler/DefaultErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace App\Handler;

use App\Factory\LoggerFactory;
use App\Renderer\JsonRenderer;
use DomainException;
use Fig\Http\Message\StatusCodeInterface;
Expand All @@ -29,13 +28,11 @@ final class DefaultErrorHandler implements ErrorHandlerInterface
public function __construct(
JsonRenderer $jsonRenderer,
ResponseFactoryInterface $responseFactory,
LoggerFactory $loggerFactory
LoggerInterface $logger,
) {
$this->jsonRenderer = $jsonRenderer;
$this->responseFactory = $responseFactory;
$this->logger = $loggerFactory
->addFileHandler('error.log')
->createLogger();
$this->logger = $logger;
}

/**
Expand Down
5 changes: 0 additions & 5 deletions tests/TestCase/Action/Customer/CustomerCreatorActionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ public function testCreateCustomer(): void
$this->assertJsonContentType($response);
$this->assertJsonData(['customer_id' => 1], $response);

// Check logger
// No logger errors
$this->assertSame([], $this->getLoggerErrors());
$this->assertTrue($this->getLogger()->hasInfoThatContains('Customer created successfully: 1'));

// Check database
$this->assertTableRowCount(1, 'customers');

Expand Down
3 changes: 0 additions & 3 deletions tests/TestCase/Action/Customer/CustomerUpdaterActionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,6 @@ public function testUpdateCustomer(): void
$this->assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
$this->assertJsonContentType($response);

// Check logger
$this->assertTrue($this->getLogger()->hasInfoThatContains('Customer updated successfully'));

// Check database
$expected = [
'id' => '1',
Expand Down
52 changes: 0 additions & 52 deletions tests/TestCase/Factory/LoggerFactoryTest.php

This file was deleted.

2 changes: 0 additions & 2 deletions tests/Traits/AppTestTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ trait AppTestTrait
use ContainerTestTrait;
use HttpTestTrait;
use HttpJsonTestTrait;
use LoggerTestTrait;
use MockTestTrait;

protected App $app;
Expand All @@ -41,7 +40,6 @@ protected function setUpApp(): void
$this->app = $container->get(App::class);

$this->setUpContainer($container);
$this->setUpLogger();

/** @phpstan-ignore-next-line */
if (method_exists($this, 'setUpDatabase')) {
Expand Down
Loading

0 comments on commit 75dc0e0

Please sign in to comment.