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
|
|
|
* {@inheritDoc} |
14
|
|
|
* @see \Zend\ServiceManager\Factory\FactoryInterface::__invoke() |
15
|
|
|
*/ |
16
|
|
|
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) |
17
|
|
|
{ |
18
|
|
|
$config = $container->get('config'); |
19
|
|
|
$losConfig = array_key_exists('loslog', $config) ? $config['loslog'] : []; |
20
|
|
|
|
21
|
|
|
$logDir = array_key_exists('log_dir', $losConfig) ? $losConfig['log_dir'] : 'data/logs'; |
22
|
|
|
$logFile = array_key_exists('error_logger_file', $losConfig) ? $losConfig['error_logger_file'] : 'error.log'; |
23
|
|
|
|
24
|
|
|
$fileName = $this->validateLogFile($logFile, $logDir); |
25
|
|
|
$zendLogLogger = new Logger(); |
26
|
|
|
$zendLogLogger->addWriter(new Stream($fileName)); |
27
|
|
|
|
28
|
|
|
return new PsrLoggerAdapter($zendLogLogger); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
View Code Duplication |
public static function validateLogFile($logFile, $logDir) |
|
|
|
|
32
|
|
|
{ |
33
|
|
|
// Is logFile a stream url? |
34
|
|
|
if (strpos($logFile, '://') !== false) { |
35
|
|
|
return $logFile; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if (!file_exists($logDir) || !is_writable($logDir)) { |
39
|
|
|
throw new Exception\InvalidArgumentException("Log dir {$logDir} must exist and be writable!"); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$fileName = $logDir.DIRECTORY_SEPARATOR.$logFile; |
43
|
|
|
|
44
|
|
|
if (file_exists($fileName) && !is_writable($fileName)) { |
45
|
|
|
throw new Exception\InvalidArgumentException("Log file {$fileName} must be writable!"); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return $fileName; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
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.