1
|
|
|
<?php |
2
|
|
|
namespace LosMiddleware\LosLog; |
3
|
|
|
|
4
|
|
|
use Interop\Container\ContainerInterface; |
5
|
|
|
use Zend\Log\Logger; |
6
|
|
|
use Zend\Log\PsrLoggerAdapter; |
7
|
|
|
use Zend\Log\Writer\Stream; |
8
|
|
|
use Zend\ServiceManager\Factory\FactoryInterface; |
9
|
|
|
|
10
|
|
|
class LoggerFactory implements FactoryInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param ContainerInterface $container |
14
|
|
|
* @param string $requestedName |
15
|
|
|
* @param array|null $options |
16
|
|
|
* @return object|PsrLoggerAdapter |
17
|
|
|
* @throws Exception\InvalidArgumentException |
18
|
|
|
* @throws \Psr\Container\ContainerExceptionInterface |
19
|
|
|
* @throws \Psr\Container\NotFoundExceptionInterface |
20
|
|
|
*/ |
21
|
|
|
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) |
22
|
|
|
{ |
23
|
|
|
$config = $container->get('config'); |
24
|
|
|
$losConfig = array_key_exists('loslog', $config) ? $config['loslog'] : []; |
25
|
|
|
|
26
|
|
|
$logDir = array_key_exists('log_dir', $losConfig) ? $losConfig['log_dir'] : 'data/logs'; |
27
|
|
|
$logFile = array_key_exists('error_logger_file', $losConfig) ? $losConfig['error_logger_file'] : 'error.log'; |
28
|
|
|
|
29
|
|
|
$fileName = $this->validateLogFile($logFile, $logDir); |
30
|
|
|
$zendLogLogger = new Logger(); |
31
|
|
|
$zendLogLogger->addWriter(new Stream($fileName)); |
32
|
|
|
|
33
|
|
|
return new PsrLoggerAdapter($zendLogLogger); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param string $logFile |
38
|
|
|
* @param string $logDir |
39
|
|
|
* @return string |
40
|
|
|
* @throws Exception\InvalidArgumentException |
41
|
|
|
*/ |
42
|
|
View Code Duplication |
public static function validateLogFile($logFile, $logDir) |
|
|
|
|
43
|
|
|
{ |
44
|
|
|
// Is logFile a stream url? |
45
|
|
|
if (strpos($logFile, '://') !== false) { |
46
|
|
|
return $logFile; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (! file_exists($logDir) || ! is_writable($logDir)) { |
50
|
|
|
throw new Exception\InvalidArgumentException("Log dir {$logDir} must exist and be writable!"); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$fileName = $logDir.DIRECTORY_SEPARATOR.$logFile; |
54
|
|
|
|
55
|
|
|
if (file_exists($fileName) && ! is_writable($fileName)) { |
56
|
|
|
throw new Exception\InvalidArgumentException("Log file {$fileName} must be writable!"); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $fileName; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.