Skip to content

Add new on-demand configuration #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,37 @@

All notable changes to `laravel-http-client-logger` will be documented in this file.

## 1.0.0 - 202X-XX-XX
## Upgrade guides

### 0.2.0 => 0.3.0

This release includes breaking changes:

- `HttpLoggerInterface`: Signature changed with the addition of optional array parameter `$config`
- `HttpLoggingFilterInterface`: Signature changed with the addition of optional array parameter `$config`
- Macro `log()`: Signature changed with the addition of optional array parameter `$config`
- Macro `logWhen()`: Signature changed with the addition of optional array parameter `$config`

The following changes are required when updating:

- If the parameter `$context['replace']` is provided to any of the methods above this must instead be provided in the newly added `$config['replace']`
- The same change must be made if the parameter `$context['filename']` has been provided
- Any calls to the `log` or `logWhen` macro where logger or filter is provided must add an empty array before the logger parameter due to the new method signature
- Any custom implementation of `HttpLoggerInterface` and `HttpLoggingFilterInterface` must be refactored to fit the new method signature
- Optional: Republish configuration file

## Changes

### 0.3.0

- Add on-demand configuration array (breaking change)

### 0.2.0

- Refactor configuration (breaking change)
- Add logging to a flysystem disk
- Bugfix: `$context` not being passed down when using request macros

### 0.1.0

- initial release
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,20 @@ Http::log(['note' => 'Something to log'])->get('https://example.com');
Http::logWhen($condition, ['note' => 'Something to log'])->get('https://example.com');
```

### Providing on-demand configuration
It is possible to provide on-demand configuration which will override the package configuration specified in `config/laravel-http-client-logger.php`:
```php
Http::log($context, ['example-config-key' => 'value'])->get('https://example.com');
// or
Http::logWhen($condition, $context, ['example-config-key' => 'value'])->get('https://example.com');
```

### Specifying a logger
The default logger and filter are specified in the package configuration `logger` and `filter` respectively but can be changed at runtime using:
```php
Http::log($context, $logger, $filter)->get('https://example.com');
Http::log($context, $config, $logger, $filter)->get('https://example.com');
// or
Http::logWhen($condition, $context, $logger, $filter)->get('https://example.com');
Http::logWhen($condition, $context, $config, $logger, $filter)->get('https://example.com');
```
Note that the logger must implement `HttpLoggerInterface` while the filter must implement `HttpLoggingFilterInterface`.

Expand Down
4 changes: 3 additions & 1 deletion config/http-client-logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@
*/
'log_to_disk' => [
'enabled' => env('HTTP_CLIENT_LOGGER_DISK_LOG_ENABLED', true),
'disk' => env('HTTP_CLIENT_LOGGER_DISK'), // uses the default filesystem disk unless specified
'disk' => env('HTTP_CLIENT_LOGGER_DISK'), // uses the default filesystem disk if none is specified
'separate' => true,
'timestamp' => 'Y-m-d-Hisu', // Leaving empty will remove the timestamp
'filename' => '',
],
];
49 changes: 22 additions & 27 deletions src/HttpLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ class HttpLogger implements HttpLoggerInterface
protected ResponseInterface $response;
protected float $sec;
protected array $context;
protected array $replace;
protected string $filename;
protected array $config;
protected string $fileExt = '.txt';

public function __construct(PsrMessageToStringConverter $psrMessageStringConverter)
Expand All @@ -30,46 +29,42 @@ public function log(
RequestInterface $request,
ResponseInterface $response,
float $sec,
array $context = []
array $context = [],
array $config = []
): void {
$this->request = $request;
$this->response = $response;
$this->sec = $sec;
$this->replace = $this->getReplace($context);
$this->filename = $this->getFileName($context);
$this->context = $this->getContextCleaned($context); // must be called after the two above since the $context array is modified
$this->context = $context;
$this->config = array_replace_recursive(config('http-client-logger'), $config); // Note this does not work optimally!

if (config('http-client-logger.log_to_channel.enabled')) {
$this->logToChannel(config('http-client-logger.log_to_channel.channel') ?? config('logging.default'));
if (Arr::get($this->config, 'log_to_channel.enabled')) {
$this->logToChannel(Arr::get($this->config, 'log_to_channel.channel') ?? config('logging.default'));
}

if (config('http-client-logger.log_to_disk.enabled')) {
$this->logToDisk(config('http-client-logger.log_to_disk.disk') ?? config('filesystems.default'));
if (Arr::get($this->config, 'log_to_disk.enabled')) {
$this->logToDisk(Arr::get($this->config, 'log_to_disk.disk') ?? config('filesystems.default'));
}
}

protected function getContextCleaned(array $context): array
protected function getReplace(): array
{
return Arr::except($context, ['replace', 'filename']);
return Arr::get($this->config, 'replace', []);
}

protected function getReplace(array $context): array
protected function getFileName(): string
{
return Arr::get($context, 'replace', []);
}

protected function getFileName(array $context): string
{
return Arr::get($context, 'filename', now()->format('Y-m-d-Hisu'));
return (Arr::get($this->config, 'log_to_disk.timestamp') ? now()->format(Arr::get($this->config, 'log_to_disk.timestamp')) : '')
.Arr::get($this->config, 'log_to_disk.filename');
}

protected function getMessage(): string
{
return "Time {$this->sec}sec\r\n"
."Request\r\n"
.$this->psrMessageStringConverter->toString($this->request, $this->replace)."\r\n"
.$this->psrMessageStringConverter->toString($this->request, $this->getReplace())."\r\n"
."Response\r\n"
.$this->psrMessageStringConverter->toString($this->response, $this->replace);
.$this->psrMessageStringConverter->toString($this->response, $this->getReplace());
}

protected function logToChannel(string $channel): void
Expand All @@ -87,18 +82,18 @@ protected function logToChannel(string $channel): void

protected function logToDisk(string $disk): void
{
if (config('http-client-logger.log_to_disk.separate')) {
if (Arr::get($this->config, 'log_to_disk.separate')) {
Storage::disk($disk)->put(
$this->filename.'-request'.Str::start($this->fileExt, '.'),
$this->psrMessageStringConverter->toString($this->request, $this->replace)
$this->getFileName().'-request'.Str::start($this->fileExt, '.'),
$this->psrMessageStringConverter->toString($this->request, $this->getReplace())
);
Storage::disk($disk)->put(
$this->filename.'-response'.Str::start($this->fileExt, '.'),
$this->psrMessageStringConverter->toString($this->response, $this->replace)
$this->getFileName().'-response'.Str::start($this->fileExt, '.'),
$this->psrMessageStringConverter->toString($this->response, $this->getReplace())
);
} else {
Storage::disk($disk)->put(
$this->filename.Str::start($this->fileExt, '.'),
$this->getFileName().Str::start($this->fileExt, '.'),
$this->getMessage()
);
}
Expand Down
3 changes: 2 additions & 1 deletion src/HttpLoggerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public function log(
RequestInterface $request,
ResponseInterface $response,
float $sec,
array $context = []
array $context = [],
array $config = []
): void;
}
3 changes: 2 additions & 1 deletion src/HttpLoggingFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ public function shouldLog(
RequestInterface $request,
ResponseInterface $response,
float $sec,
array $context = []
array $context = [],
array $config = []
): bool {
if (! config('http-client-logger.enabled')) {
return false;
Expand Down
3 changes: 2 additions & 1 deletion src/HttpLoggingFilterInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public function shouldLog(
RequestInterface $request,
ResponseInterface $response,
float $sec,
array $context = []
array $context = [],
array $config = []
): bool;
}
6 changes: 4 additions & 2 deletions src/LaravelHttpClientLoggerServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,25 @@ public function packageBooted()
{
PendingRequest::macro('log', function (
$context = [],
$config = [],
?HttpLoggerInterface $logger = null,
?HttpLoggingFilterInterface $filter = null
) {
return $this->withMiddleware((new LoggingMiddleware(
$logger ?? resolve(HttpLoggerInterface::class),
$filter ?? resolve(HttpLoggingFilterInterface::class)
))->__invoke($context));
))->__invoke($context, $config));
});

PendingRequest::macro('logWhen', function (
$condition,
$context = [],
$config = [],
?HttpLoggerInterface $logger = null,
?HttpLoggingFilterInterface $filter = null
) {
if ($condition) {
return $this->log($context, $logger, $filter);
return $this->log($context, $config, $logger, $filter);
} else {
return $this;
}
Expand Down
12 changes: 6 additions & 6 deletions src/Middleware/LoggingMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,20 @@ public function __construct(HttpLoggerInterface $logger, HttpLoggingFilterInterf
* @param array $context
* @return callable(RequestInterface, array): PromiseInterface
*/
public function __invoke($context = []): callable
public function __invoke($context = [], $config = []): callable
{
return function (callable $handler) use ($context): callable {
return function (RequestInterface $request, array $options) use ($context, $handler): PromiseInterface {
return function (callable $handler) use ($context, $config): callable {
return function (RequestInterface $request, array $options) use ($context, $config, $handler): PromiseInterface {
$start = microtime(true);

$promise = $handler($request, $options);

return $promise->then(
function (ResponseInterface $response) use ($context, $request, $start) {
function (ResponseInterface $response) use ($context, $config, $request, $start) {
$sec = microtime(true) - $start;

if ($this->filter->shouldLog($request, $response, $sec, $context)) {
$this->logger->log($request, $response, $sec, $context);
if ($this->filter->shouldLog($request, $response, $sec, $context, $config)) {
$this->logger->log($request, $response, $sec, $context, $config);
}

return $response;
Expand Down
4 changes: 2 additions & 2 deletions tests/HttpLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public function test_replaces_placeholders_from_request()
{
Log::swap(new LogFake);

$this->logger->log($this->request, new Response(200), 0.2, ['test123', 'replace' => ['example.com' => 'mock.org']]);
$this->logger->log($this->request, new Response(200), 0.2, ['test123'], ['replace' => ['example.com' => 'mock.org']]);

Log::assertLogged('debug', function ($message, $context) {
return Str::contains($message, 'mock.org')
Expand All @@ -132,7 +132,7 @@ public function test_replaces_placeholders_from_response()
{
Log::swap(new LogFake);

$this->logger->log($this->request, new Response(200, [], 'My name is John Doe'), 0.2, ['test123', 'replace' => ['Doe' => 'Smith']]);
$this->logger->log($this->request, new Response(200, [], 'My name is John Doe'), 0.2, ['test123'], ['replace' => ['Doe' => 'Smith']]);

Log::assertLogged('debug', function ($message, $context) {
return Str::contains($message, 'Smith')
Expand Down
5 changes: 5 additions & 0 deletions tests/MacroTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ public function test_log_with_context()
// TODO: Implement
}

public function test_log_with_config()
{
// TODO: Implement
}

public function test_log_with_logger()
{
// TODO: Implement
Expand Down