Skip to content

Commit

Permalink
Refactoring logg func (#50)
Browse files Browse the repository at this point in the history
* Refactor vlog func;

* Update usage;

* Add tests;

* Update docs;

* Apply fixes from StyleCI

---------

Co-authored-by: StyleCI Bot <[email protected]>
  • Loading branch information
hans-thomas and StyleCIBot authored Jan 6, 2025
1 parent e1a79d4 commit aec3ed3
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 19 deletions.
42 changes: 38 additions & 4 deletions docs/content/docs/Basics/helpers.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ Valravn includes several global functions that you can use in your code.
{{< /column >}}

{{< column "method" >}}
[logg](#logg)
[vlog](#vlog)
{{< /column >}}

{{< column "method" >}}
Expand All @@ -125,9 +125,43 @@ Resolve the given id to a related model.

Resolve given Model to a resource class.

##### logg

Log the given exception to a specific channel and format.
##### vlog

Log the error in a dedicated channel with a simplified format.

```php
class someClass {
public function someMethod(): void
{
try{
// do something
}catch (Exception $e){
vlog('The reason');
}
}
}
```
The logged content should be like this:

```text
[2025-01-06 07:57:54] testing.DEBUG: At: [Namespace\someClass::someMethod] => "The reason"
```

Also, You can pass the exception to track the issue.

```php
catch (Exception $e){
vlog('The reason',['previous' => $e]);
}
```

And if you just want to log the error, you need to pass the exception only.

```php
catch (Exception $e){
vlog($e);
}
```

##### slugify

Expand Down
2 changes: 1 addition & 1 deletion src/Exceptions/VException.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function __construct(
*/
public function render(): JsonResponse
{
logg(self::class, $this, ['errorCode' => $this->getErrorCode(), 'responseCode' => $this->getCode()]);
vlog($this);

return new JsonResponse([
'title' => 'Unexpected error!',
Expand Down
17 changes: 10 additions & 7 deletions src/Helpers/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,19 +79,22 @@ function resolveMorphableToResource(?Model $morphable): JsonResource
}
}

if (!function_exists('logg')) {
if (!function_exists('vlog')) {
/**
* Log the given exception to a specific channel and format.
*
* @param string $location
* @param Throwable $e
* @param array $context
* @param Throwable|string $message
* @param array $context
*
* @return void
*/
function logg(string $location, Throwable $e, array $context = []): void
function vlog(Throwable|string $message, array $context = []): void
{
Log::channel('valravn')->debug($location.' => '.'message: '.$e->getMessage(), $context);
$backtrace = debug_backtrace(limit: 2)[1];
$location = $backtrace['class'].'::'.$backtrace['function'];
$message = is_string($message) ? $message : $message->getMessage();

Log::channel('valravn')->debug("At: [$location] => \"$message\"", $context);
}
}

Expand All @@ -111,7 +114,7 @@ function valravn_config(string $key): string|array

if (!function_exists('slugify')) {
/**
* Make a english or non-english string to a slug.
* Make an english or non-english string to a slug.
*
* @param string $string
* @param string $separator
Expand Down
1 change: 0 additions & 1 deletion src/ValravnServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ private function registerPublishes()
*/
private function registerMacros()
{
// TODO: should be documented
if (env('ENABLE_DB_LOG', false)) {
DB::listen(function (QueryExecuted $query) {
$bindings = implode(',', $query->bindings);
Expand Down
4 changes: 2 additions & 2 deletions tests/Feature/Commands/MigrationTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ protected function setUp(): void

protected function tearDown(): void
{
parent::tearDown();

$file = base_path("database/migrations/Blog/{$this->datePrefix}_create_posts_table.php");
File::delete($file);

parent::tearDown();
}

/**
Expand Down
4 changes: 2 additions & 2 deletions tests/Feature/Commands/PivotTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ protected function setUp(): void

protected function tearDown(): void
{
parent::tearDown();

$pivot = database_path("migrations/Blog/{$this->datePrefix}_create_category_post_table.php");
File::delete($pivot);

parent::tearDown();
}

/**
Expand Down
89 changes: 87 additions & 2 deletions tests/Feature/Helper/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,40 @@
use Hans\Valravn\Tests\Core\Resources\User\UserResource;
use Hans\Valravn\Tests\TestCase;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Optional;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class FunctionsTest extends TestCase
{
private User $user;
private Post $post;
private string $date;

/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();

$this->user = UserFactory::new()->create();
$this->post = PostFactory::new()->create();
$this->date = now()->format('Y-m-d');
config()->set('logging.channels.valravn', [
'driver' => 'daily',
'path' => storage_path('logs/valravn.log'),
'level' => 'debug',
'days' => 1,
'replace_placeholders' => true,
]);
}

protected function tearDown(): void
{
File::delete(storage_path("logs/valravn-$this->date.log"));

parent::tearDown();
}

/**
Expand Down Expand Up @@ -152,8 +171,7 @@ public function resolveMorphableToResourceWithResourceCollectionableImplemented(
*/
public function slugify(): void
{
// poetry meaning: if you are alive now, don't let the present pass without happiness -Omar Khayyam
// p.s.: obviously it is very complex and deep, so I can't translate it properly.
// Poetry meaning: if you are alive now, don't let the present pass without happiness -Omar Khayyam
$non_english_string = 'گر یک نفست ز زندگانی گذرد / مگذار ک جز به شادمانی گذرد';
$slug = slugify($non_english_string);

Expand All @@ -163,4 +181,71 @@ public function slugify(): void
$slug
);
}

/**
* @test
*
* @return void
*/
public function vlogLogFile(): void
{
self::assertFileDoesNotExist(storage_path("logs/valravn-$this->date.log"));

vlog('The reason');

self::assertFileExists(storage_path("logs/valravn-$this->date.log"));
}

/**
* @test
*
* @return void
*/
public function vlogContent(): void
{
$file = storage_path("logs/valravn-$this->date.log");
$e = new NotFoundHttpException('Failed to found your data');
vlog('The reason: {r}', ['r' => 'something', 'previous' => $e]);

$actual = file_get_contents($file);
$expected = <<<EOT
At: [Hans\Valravn\Tests\Feature\Helper\FunctionsTest::vlogContent] => "The reason: something"
EOT;

self::assertStringContainsString(
$expected,
$actual
);

$expected = <<<'EOD'
[object] (Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException(code: 0): Failed to found your data
EOD;

self::assertStringContainsString(
$expected,
$actual
);
}

/**
* @test
*
* @return void
*/
public function vlogThrowableAsMessage(): void
{
$file = storage_path("logs/valravn-$this->date.log");
$e = new NotFoundHttpException('Failed to found your data');
vlog($e);

$actual = file_get_contents($file);
$expected = <<<EOT
At: [Hans\Valravn\Tests\Feature\Helper\FunctionsTest::vlogThrowableAsMessage] => "Failed to found your data"
EOT;

self::assertStringContainsString(
$expected,
$actual
);
}
}

0 comments on commit aec3ed3

Please sign in to comment.