Skip to content
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

Added withLogger macro for Request #10

Merged
merged 5 commits into from
Aug 23, 2024
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
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ Http::get()->toData(...); // will be method not found exception

### Available Methods

#### Request

- [withLogger](#withlogger)

#### Response

Expand All @@ -76,6 +79,43 @@ Http::get()->toData(...); // will be method not found exception

### Method Listing

#### withLogger()

Adds the ability to log HTTP requests and responses.

```php
use Illuminate\Support\Facades\Http;

Http::withLogger('some_channel')->get();
```

This method will log HTTP requests and responses.

It is also possible to use your own handler, message formatting and path to the log file.
To do this, you need to specify the desired channel name from the log file and define the necessary parameters in it.

For example:

```php
// config/logging.php
return [
// ...

'channels' => [
'some' => [
'driver' => 'single',
'level' => env('LOG_LEVEL', 'debug'),
'path' => storage_path('logs/some.log'),
'handler' => \App\Logging\SomeHandlerStack::class,
'formatter' => \App\Logging\MessageFormatter::class,
],
],
];

// Usage
return Http::withLogger('some')->...
```

#### toData()

The class instance will be returned.
Expand Down
3 changes: 3 additions & 0 deletions config/http.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

declare(strict_types=1);

use DragonCode\LaravelHttpMacros\Macros\Requests\WithLoggerMacro;
use DragonCode\LaravelHttpMacros\Macros\Responses\ToDataCollectionMacro;
use DragonCode\LaravelHttpMacros\Macros\Responses\ToDataMacro;

return [
'macros' => [
'request' => [
WithLoggerMacro::class,

// CustomMacro::class,
// 'toFoo' => CustomMacro::class,
],
Expand Down
27 changes: 27 additions & 0 deletions ide.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"$schema": "https://laravel-ide.com/schema/laravel-ide-v2.json",
"completions": [
{
"complete": "configKey",
"options": {
"prefix": "logging.channels"
},
"condition": [
{
"methodNames": [
"withLogger"
],
"classFqn": [
"\\Illuminate\\Http\\Client\\Factory",
"\\Illuminate\\Http\\Client\\PendingRequest",
"\\Illuminate\\Http\\Client\\Request",
"\\Illuminate\\Support\\Facades\\Http"
],
"parameters": [
1
]
}
]
}
]
}
51 changes: 51 additions & 0 deletions src/Macros/Requests/WithLoggerMacro.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace DragonCode\LaravelHttpMacros\Macros\Requests;

use Closure;
use DragonCode\LaravelHttpMacros\Macros\Macro;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use Illuminate\Http\Client\PendingRequest;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

use function call_user_func;
use function config;
use function storage_path;

/**
* Adds the ability to log HTTP requests and responses.
*/
class WithLoggerMacro extends Macro
{
public static function callback(): Closure
{
return function (string $channel): PendingRequest {
$config = config('logging.channels.' . $channel);

$handler = call_user_func([$config['handler'] ?? HandlerStack::class, 'create']);
$formatter = $config['formatter'] ?? MessageFormatter::class;

$path = $config['path'] ?? storage_path('logs/laravel.log');

$logger = (new Logger($channel))->pushHandler(
new StreamHandler($path)
);

$handler->push(
Middleware::log($logger, new $formatter())
);

return $this->setHandler($handler);
};
}

public static function name(): string
{
return 'withLogger';
}
}
4 changes: 2 additions & 2 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use DragonCode\LaravelHttpMacros\Commands\GenerateHelperCommand;
use DragonCode\LaravelHttpMacros\Macros\Macro;
use Illuminate\Http\Client\Request;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;

Expand Down Expand Up @@ -42,7 +42,7 @@ protected function bootCommands(): void
protected function bootRequestMacros(): void
{
foreach ($this->requestMacros() as $name => $macro) {
Request::macro($this->resolveName($name, $macro), $macro::callback());
PendingRequest::macro($this->resolveName($name, $macro), $macro::callback());
}
}

Expand Down
28 changes: 28 additions & 0 deletions tests/Fixtures/Logging/MessageFormater.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Tests\Fixtures\Logging;

use GuzzleHttp\MessageFormatterInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class MessageFormater implements MessageFormatterInterface
{
public function __construct(
protected string $template = 'REQUEST: {request} RESPONSE: {response}'
) {}

public function format(
RequestInterface $request,
?ResponseInterface $response = null,
?Throwable $error = null
): string {
return str_replace(['{request}', '{response}'], [
$request->getUri(),
$response->getBody()->getContents(),
], $this->template);
}
}
3 changes: 2 additions & 1 deletion tests/Helpers/fake.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
declare(strict_types=1);

use Illuminate\Http\Client\Factory;
use Illuminate\Support\Facades\Http;

function fakeRequest(): Factory
{
return (new Factory())->fake([
return Http::fake([
'simple' => [
'id' => 1,
'title' => 'Qwerty 1',
Expand Down
12 changes: 12 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Config\Repository;
use Orchestra\Testbench\TestCase as BaseTestCase;
use Spatie\LaravelData\LaravelDataServiceProvider;
use Tests\Fixtures\Logging\MessageFormater;

abstract class TestCase extends BaseTestCase
{
Expand All @@ -28,6 +29,17 @@ protected function defineEnvironment($app): void

'toFoo' => ToDataMacro::class,
]);

$config->set('logging.channels.foo', [
'driver' => 'single',
'path' => storage_path('logs/foo.log'),
]);

$config->set('logging.channels.bar', [
'driver' => 'single',
'path' => storage_path('logs/bar.log'),
'formatter' => MessageFormater::class,
]);
});
}
}