1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Autarky\Logging;
12:
13: use Autarky\Config\ConfigInterface;
14: use Autarky\Application;
15: use Autarky\ConfiguratorInterface;
16: use Monolog\Formatter\LineFormatter;
17: use Monolog\Handler\StreamHandler;
18: use Monolog\Logger;
19:
20: 21: 22: 23: 24: 25:
26: class DefaultLogConfigurator implements ConfiguratorInterface
27: {
28: const LOG_TS_FORMAT = 'Y-m-d H:i:s.u P';
29:
30: 31: 32: 33: 34:
35: protected $channelManager;
36:
37: 38: 39: 40: 41:
42: protected $config;
43:
44: 45: 46: 47: 48:
49: protected $environment;
50:
51: 52: 53: 54: 55: 56: 57:
58: public function __construct(
59: ChannelManager $channelManager,
60: Application $application,
61: ConfigInterface $config
62: ) {
63: $this->environment = $application->getEnvironment();
64: $this->channelManager = $channelManager;
65: $this->config = $config;
66: }
67:
68: 69: 70:
71: public function configure()
72: {
73: $this->channelManager->setChannel('default', $this->makeDefaultLogger());
74: }
75:
76: protected function makeDefaultLogger()
77: {
78: $logger = new Logger($this->environment);
79:
80: if ($logpath = $this->getLogPath()) {
81: $handler = new StreamHandler($logpath, Logger::DEBUG);
82: $logger->pushHandler($handler);
83: $formatter = new LineFormatter(null, static::LOG_TS_FORMAT, true);
84: $handler->setFormatter($formatter);
85: }
86:
87: return $logger;
88: }
89:
90: protected function getLogPath()
91: {
92: if (!$logdir = $this->getLogDirectory()) {
93: return null;
94: }
95:
96: if (!is_dir($logdir)) {
97: throw new \RuntimeException("Log directory $logdir does not exist or is not a directory.");
98: }
99:
100: $logpath = rtrim($logdir, '\\/').DIRECTORY_SEPARATOR.$this->getLogFilename();
101:
102: if (file_exists($logpath) && !is_writable($logpath)) {
103: throw new \RuntimeException("Log file $logpath is not writeable.");
104: }
105:
106: return $logpath;
107: }
108:
109: protected function getLogDirectory()
110: {
111: if ($this->config->has('path.logs')) {
112: return $this->config->get('path.logs');
113: }
114:
115: if ($this->config->has('path.storage')) {
116: $path = $this->config->get('path.storage').'/logs';
117:
118: if (is_dir($path)) {
119: return $path;
120: }
121: }
122:
123: return null;
124: }
125:
126: protected function getLogFilename()
127: {
128: return PHP_SAPI.'.log';
129: }
130: }
131: