Skip to content

Commit 93b96f4

Browse files
committed
feat: [Logger] handle logging via channel
1 parent 406265d commit 93b96f4

File tree

2 files changed

+30
-22
lines changed

2 files changed

+30
-22
lines changed

src/Logger.php

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,31 @@ public function __construct(LoggerInterface $logger, Dispatcher $dispatcher = nu
4848
*/
4949
protected function writeLog($level, $message, $context)
5050
{
51+
$info = $this->generateExtraContextInfo();
52+
$context = array_merge($context, $info);
53+
54+
parent::writeLog($level, $message, $context);
55+
}
56+
57+
protected function generateExtraContextInfo()
58+
{
59+
$info = [];
60+
5161
// attach class_path
5262
// NOTE: it's hardcoded, should find a better way to get caller class
53-
$caller = debug_backtrace();
54-
$caller = $caller[4];
55-
$context['class_path'] = $caller['class'];
63+
$stack = debug_backtrace();
64+
$caller = $stack[2];
65+
66+
if ($caller['class'] === 'Illuminate\Log\LogManager') {
67+
// It means log from channel
68+
$caller = $stack[4];
69+
}
70+
71+
$info['class_path'] = $caller['class'];
5672

5773
// attach tracking_id
58-
$context['tracking_id'] = $this->debugId;
74+
$info['tracking_id'] = $this->debugId;
5975

60-
parent::writeLog($level, $message, $context);
76+
return $info;
6177
}
6278
}

tests/Unit/LoggerTest.php

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@
22

33
namespace Onramplab\LaravelLogEnhancement\Tests\Unit\Concerns;
44

5-
use Illuminate\Events\Dispatcher;
6-
use Illuminate\Foundation\Application;
7-
use Illuminate\Support\Facades\Log;
85
use Mockery;
96
use Onramplab\LaravelLogEnhancement\Tests\TestCase;
107
use Onramplab\LaravelLogEnhancement\Logger;
11-
use Psr\Log\LoggerInterface;
8+
use Monolog\Logger as Monolog;
129

1310
class LoggerTest extends TestCase
1411
{
@@ -19,20 +16,15 @@ class LoggerTest extends TestCase
1916
*/
2017
public function log_should_include_class_path_and_uuid_in_context()
2118
{
22-
$this->app->instance(Logger::class, Mockery::mock(Logger::class));
19+
$monolog = Mockery::mock(Monolog::class);
20+
$logger = new Logger($monolog);
2321

24-
$logger = app()
25-
->make(Logger::class)
26-
->makePartial();
22+
$monolog->shouldReceive('info')->withArgs(function ($message, $context) {
23+
return $message === '123'
24+
&& isSet($context['class_path'])
25+
&& isSet($context['tracking_id']);
26+
})->once();
2727

28-
$logger->shouldReceive('log', function ($logLevel, $message, $context) {
29-
return $logLevel === 'info'
30-
&& $message === '123'
31-
&& isSet($context['class_path'])
32-
&& isSet($context['tracking_id']);
33-
})
34-
->once();
35-
36-
$logger->info('123');
28+
$logger->info('123');
3729
}
3830
}

0 commit comments

Comments
 (0)