Skip to content

Commit 57b9eee

Browse files
authored
Merge pull request #8 from OnrampLab/issue-7-feat-log-facade-should-be-compatible-with-laravel-default-one
LogFacade should be compatible with laravel default one Close #7
2 parents ce7d019 + e9dcb77 commit 57b9eee

File tree

11 files changed

+184
-176
lines changed

11 files changed

+184
-176
lines changed

.editorconfig

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
root = true
2+
3+
[*]
4+
charset = utf-8
5+
end_of_line = lf
6+
insert_final_newline = true
7+
indent_style = space
8+
indent_size = 2
9+
trim_trailing_whitespace = true
10+
11+
[composer.json]
12+
indent_size = 4
13+
14+
[*.md]
15+
trim_trailing_whitespace = false
16+
17+
[*.yml]
18+
indent_size = 2
19+
20+
[*.php]
21+
indent_size = 4

README.md

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ A library with logging enhancement. Including:
88

99
- `LoggerFacade` facade
1010
- It extends default Laravel `Log` facade with logging adding class path and tracking id into context.
11-
- `LogWithClassPath` trait (*deprecated*)
12-
- It adds convinient methods for logging to add class path and tracking id into context.
1311
- `LogglyHandler` class
1412
- It extends monolog's LogglyHandler with tags support
1513

@@ -46,42 +44,6 @@ The log json will look like this:
4644
}
4745
```
4846

49-
### LogWithClassPath Trait (*deprecated*)
50-
51-
Use `LogWithClassPath` trait to let it automatically put class path into log context. You can refer to following code example.
52-
53-
```php
54-
namespace App;
55-
56-
use Onramplab\LaravelLogEnhancement\Concerns\LogWithClassPath;
57-
58-
class Fake {
59-
use LogWithClassPath;
60-
61-
public function run()
62-
{
63-
$this->info('Test');
64-
}
65-
}
66-
```
67-
68-
The log json will look like this:
69-
70-
```json
71-
{
72-
"message": "Test",
73-
"context": {
74-
"class_path": "App\\Fake",
75-
"tracking_id": "652c3456-1a17-42b8-9fa7-9bee65e655eb"
76-
},
77-
"level": 200,
78-
"level_name": "INFO",
79-
"channel": "local",
80-
"extra": {},
81-
"timestamp": "2021-01-04T22:47:56.598608-0800"
82-
}
83-
```
84-
8547
### LogglyHandler
8648

8749
You can adding following block into `config/logging.php`.

composer.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
},
1919
"require-dev": {
2020
"fzaninotto/faker": "^1.9@dev",
21+
"illuminate/contracts": "^7.0",
22+
"illuminate/log": "^7.0",
2123
"illuminate/support": "^7.0",
2224
"mockery/mockery": "^1.3.2",
2325
"orchestra/database": "^5.0",

src/Concerns/LogWithClassPath.php

Lines changed: 0 additions & 63 deletions
This file was deleted.

src/LaravelLogEnhancementServiceProvider.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ public function register()
6666
return new Logger($app->make(LoggerInterface::class));
6767
});
6868

69-
$this->app->bind('laravel-log-enhancement-logger',function(){
70-
return app()->make(Logger::class);
69+
$this->app->singleton('laravel-log-enhancement-logger', function ($app) {
70+
return new LogManager($app);
7171
});
7272
}
7373

src/LogManager.php

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php
2+
3+
namespace Onramplab\LaravelLogEnhancement;
4+
5+
use Illuminate\Log\LogManager as IlluminateLoggerManager;
6+
use Monolog\Handler\StreamHandler;
7+
use Monolog\Logger as Monolog;
8+
use Psr\Log\LoggerInterface;
9+
use Throwable;
10+
11+
/**
12+
* Replace with our custom Logger
13+
*/
14+
class LogManager extends IlluminateLoggerManager
15+
{
16+
/**
17+
* Create an emergency log handler to avoid white screens of death.
18+
*
19+
* @return \Psr\Log\LoggerInterface
20+
*/
21+
protected function createEmergencyLogger()
22+
{
23+
$config = $this->configurationFor('emergency');
24+
25+
$handler = new StreamHandler(
26+
$config['path'] ?? $this->app->storagePath().'/logs/laravel.log',
27+
$this->level(['level' => 'debug'])
28+
);
29+
30+
return new Logger(
31+
new Monolog('laravel', $this->prepareHandlers([$handler])),
32+
$this->app['events']
33+
);
34+
}
35+
36+
/**
37+
* Create a new, on-demand aggregate logger instance.
38+
*
39+
* @param array $channels
40+
* @param string|null $channel
41+
* @return \Psr\Log\LoggerInterface
42+
*/
43+
public function stack(array $channels, $channel = null)
44+
{
45+
return new Logger(
46+
$this->createStackDriver(compact('channels', 'channel')),
47+
$this->app['events']
48+
);
49+
}
50+
51+
/**
52+
* Attempt to get the log from the local cache.
53+
*
54+
* @param string $name
55+
* @return \Psr\Log\LoggerInterface
56+
*/
57+
protected function get($name)
58+
{
59+
try {
60+
return $this->channels[$name] ?? with($this->resolve($name), function ($logger) use ($name) {
61+
return $this->channels[$name] = $this->tap($name, new Logger($logger, $this->app['events']));
62+
});
63+
} catch (Throwable $e) {
64+
return tap($this->createEmergencyLogger(), function ($logger) use ($e) {
65+
$logger->emergency('Unable to create configured logger. Using emergency logger.', [
66+
'exception' => $e,
67+
]);
68+
});
69+
}
70+
}
71+
}

src/Logger.php

Lines changed: 51 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,44 +2,77 @@
22

33
namespace Onramplab\LaravelLogEnhancement;
44

5+
use Illuminate\Contracts\Events\Dispatcher;
6+
use Illuminate\Log\Logger as IlluminateLogger;
57
use Psr\Log\LoggerInterface;
68
use Ramsey\Uuid\Uuid;
79

8-
class Logger
10+
class Logger extends IlluminateLogger
911
{
12+
/**
13+
* @var string
14+
*/
1015
protected $debugId;
16+
17+
/**
18+
* LoggerInterface
19+
*/
1120
protected $logger;
1221

1322
/**
14-
* Create an instance of the QueryLogger class
23+
* @var string
24+
*/
25+
protected $channelName;
26+
27+
/**
28+
* Create a new log writer instance.
1529
*
16-
* @param \Psr\Log\LoggerInterface $logger
30+
* @param \Psr\Log\LoggerInterface $logger
31+
* @param \Illuminate\Contracts\Events\Dispatcher|null $dispatcher
1732
* @return void
18-
*
19-
* @throws \Ramsey\Uuid\Exception\UnsatisfiedDependencyException
20-
* @throws \InvalidArgumentException
21-
* @throws \Exception
2233
*/
23-
public function __construct(LoggerInterface $logger)
34+
public function __construct(LoggerInterface $logger, Dispatcher $dispatcher = null)
2435
{
2536
$this->logger = $logger;
37+
$this->dispatcher = $dispatcher;
2638
$this->debugId = Uuid::uuid4()->toString();
27-
//
2839
}
2940

30-
public function __call($name, $arguments)
41+
/**
42+
* Write a message to the log.
43+
*
44+
* @param string $level
45+
* @param string $message
46+
* @param array $context
47+
* @return void
48+
*/
49+
protected function writeLog($level, $message, $context)
3150
{
32-
$message = $arguments[0];
33-
$context = $arguments[1] ?? [];
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+
61+
// attach class_path
62+
// NOTE: it's hardcoded, should find a better way to get 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+
}
3470

35-
// attach caller class
36-
$caller = debug_backtrace();
37-
$caller = $caller[2];
38-
$context['class_path'] = $caller['class'];
71+
$info['class_path'] = $caller['class'];
3972

4073
// attach tracking_id
41-
$context['tracking_id'] = $this->debugId;
74+
$info['tracking_id'] = $this->debugId;
4275

43-
$this->logger->log($name, $message, $context);
76+
return $info;
4477
}
4578
}

tests/Unit/Concerns/LogWithClassPathTest.php

Lines changed: 0 additions & 40 deletions
This file was deleted.

tests/Unit/Handlers/LogglyHandlerTest.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ class LogglyHandlerTest extends TestCase
1515
*/
1616
public function constructor_should_support_tags()
1717
{
18-
$this->handler = Mockery::mock(LogglyHandler::class)->makePartial();
18+
$this->handler = Mockery::mock(LogglyHandler::class)->makePartial();
1919

20-
$this->handler->shouldReceive('setTag')->with(['tag1', 'tag2'])->once();
20+
$this->handler->shouldReceive('setTag')->with(['tag1', 'tag2'])->once();
2121

22-
$this->handler->__construct('test', 'tag1,tag2');
22+
$this->handler->__construct('test', 'tag1,tag2');
2323
}
2424
}

0 commit comments

Comments
 (0)