Completed
Pull Request — master (#9293)
by Blizzz
47:51 queued 22:22
created
lib/private/Log/IFileBased.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 namespace OC\Log;
25 25
 
26 26
 interface IFileBased {
27
-	public function getLogFilePath();
27
+    public function getLogFilePath();
28 28
 
29
-	public function getEntries($limit=50, $offset=0);
29
+    public function getEntries($limit=50, $offset=0);
30 30
 }
Please login to merge, or discard this patch.
settings/Controller/LogSettingsController.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -39,28 +39,28 @@
 block discarded – undo
39 39
  */
40 40
 class LogSettingsController extends Controller {
41 41
 
42
-	/** @var Log */
43
-	private $log;
42
+    /** @var Log */
43
+    private $log;
44 44
 
45
-	public function __construct(string $appName, IRequest $request, ILogger $logger) {
46
-		parent::__construct($appName, $request);
47
-		$this->log = $logger;
48
-	}
45
+    public function __construct(string $appName, IRequest $request, ILogger $logger) {
46
+        parent::__construct($appName, $request);
47
+        $this->log = $logger;
48
+    }
49 49
 
50
-	/**
51
-	 * download logfile
52
-	 *
53
-	 * @NoCSRFRequired
54
-	 *
55
-	 * @return StreamResponse
56
-	 */
57
-	public function download() {
58
-		if(!$this->log instanceof Log) {
59
-			throw new \UnexpectedValueException('Log file not available');
60
-		}
61
-		$resp = new StreamResponse($this->log->getLogPath());
62
-		$resp->addHeader('Content-Type', 'application/octet-stream');
63
-		$resp->addHeader('Content-Disposition', 'attachment; filename="nextcloud.log"');
64
-		return $resp;
65
-	}
50
+    /**
51
+     * download logfile
52
+     *
53
+     * @NoCSRFRequired
54
+     *
55
+     * @return StreamResponse
56
+     */
57
+    public function download() {
58
+        if(!$this->log instanceof Log) {
59
+            throw new \UnexpectedValueException('Log file not available');
60
+        }
61
+        $resp = new StreamResponse($this->log->getLogPath());
62
+        $resp->addHeader('Content-Type', 'application/octet-stream');
63
+        $resp->addHeader('Content-Disposition', 'attachment; filename="nextcloud.log"');
64
+        return $resp;
65
+    }
66 66
 }
Please login to merge, or discard this patch.
lib/private/Log.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -36,7 +36,6 @@
 block discarded – undo
36 36
 namespace OC;
37 37
 
38 38
 use InterfaSys\LogNormalizer\Normalizer;
39
-
40 39
 use OC\Log\ExceptionSerializer;
41 40
 use OC\Log\IFileBased;
42 41
 use OCP\IConfig;
Please login to merge, or discard this patch.
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -56,271 +56,271 @@
 block discarded – undo
56 56
  */
57 57
 class Log implements ILogger {
58 58
 
59
-	/** @var IWriter */
60
-	private $logger;
61
-
62
-	/** @var IConfig */
63
-	private $config;
64
-
65
-	/** @var boolean|null cache the result of the log condition check for the request */
66
-	private $logConditionSatisfied = null;
67
-
68
-	/** @var Normalizer */
69
-	private $normalizer;
70
-
71
-	/** @var IRegistry */
72
-	private $crashReporters;
73
-
74
-	/**
75
-	 * @param IWriter $logger The logger that should be used
76
-	 * @param IConfig $config the system config object
77
-	 * @param Normalizer|null $normalizer
78
-	 * @param IRegistry|null $registry
79
-	 */
80
-	public function __construct(IWriter $logger, IConfig $config = null, $normalizer = null, IRegistry $registry = null) {
81
-		// FIXME: Add this for backwards compatibility, should be fixed at some point probably
82
-		if ($config === null) {
83
-			$config = \OC::$server->getConfig();
84
-		}
85
-
86
-		$this->config = $config;
87
-		$this->logger = $logger;
88
-		if ($normalizer === null) {
89
-			$this->normalizer = new Normalizer();
90
-		} else {
91
-			$this->normalizer = $normalizer;
92
-		}
93
-		$this->crashReporters = $registry;
94
-	}
95
-
96
-	/**
97
-	 * System is unusable.
98
-	 *
99
-	 * @param string $message
100
-	 * @param array $context
101
-	 * @return void
102
-	 */
103
-	public function emergency(string $message, array $context = []) {
104
-		$this->log(Util::FATAL, $message, $context);
105
-	}
106
-
107
-	/**
108
-	 * Action must be taken immediately.
109
-	 *
110
-	 * Example: Entire website down, database unavailable, etc. This should
111
-	 * trigger the SMS alerts and wake you up.
112
-	 *
113
-	 * @param string $message
114
-	 * @param array $context
115
-	 * @return void
116
-	 */
117
-	public function alert(string $message, array $context = []) {
118
-		$this->log(Util::ERROR, $message, $context);
119
-	}
120
-
121
-	/**
122
-	 * Critical conditions.
123
-	 *
124
-	 * Example: Application component unavailable, unexpected exception.
125
-	 *
126
-	 * @param string $message
127
-	 * @param array $context
128
-	 * @return void
129
-	 */
130
-	public function critical(string $message, array $context = []) {
131
-		$this->log(Util::ERROR, $message, $context);
132
-	}
133
-
134
-	/**
135
-	 * Runtime errors that do not require immediate action but should typically
136
-	 * be logged and monitored.
137
-	 *
138
-	 * @param string $message
139
-	 * @param array $context
140
-	 * @return void
141
-	 */
142
-	public function error(string $message, array $context = []) {
143
-		$this->log(Util::ERROR, $message, $context);
144
-	}
145
-
146
-	/**
147
-	 * Exceptional occurrences that are not errors.
148
-	 *
149
-	 * Example: Use of deprecated APIs, poor use of an API, undesirable things
150
-	 * that are not necessarily wrong.
151
-	 *
152
-	 * @param string $message
153
-	 * @param array $context
154
-	 * @return void
155
-	 */
156
-	public function warning(string $message, array $context = []) {
157
-		$this->log(Util::WARN, $message, $context);
158
-	}
159
-
160
-	/**
161
-	 * Normal but significant events.
162
-	 *
163
-	 * @param string $message
164
-	 * @param array $context
165
-	 * @return void
166
-	 */
167
-	public function notice(string $message, array $context = []) {
168
-		$this->log(Util::INFO, $message, $context);
169
-	}
170
-
171
-	/**
172
-	 * Interesting events.
173
-	 *
174
-	 * Example: User logs in, SQL logs.
175
-	 *
176
-	 * @param string $message
177
-	 * @param array $context
178
-	 * @return void
179
-	 */
180
-	public function info(string $message, array $context = []) {
181
-		$this->log(Util::INFO, $message, $context);
182
-	}
183
-
184
-	/**
185
-	 * Detailed debug information.
186
-	 *
187
-	 * @param string $message
188
-	 * @param array $context
189
-	 * @return void
190
-	 */
191
-	public function debug(string $message, array $context = []) {
192
-		$this->log(Util::DEBUG, $message, $context);
193
-	}
194
-
195
-
196
-	/**
197
-	 * Logs with an arbitrary level.
198
-	 *
199
-	 * @param int $level
200
-	 * @param string $message
201
-	 * @param array $context
202
-	 * @return void
203
-	 */
204
-	public function log(int $level, string $message, array $context = []) {
205
-		$minLevel = $this->getLogLevel($context);
206
-
207
-		array_walk($context, [$this->normalizer, 'format']);
208
-
209
-		$app = $context['app'] ?? 'no app in context';
210
-
211
-		// interpolate $message as defined in PSR-3
212
-		$replace = [];
213
-		foreach ($context as $key => $val) {
214
-			$replace['{' . $key . '}'] = $val;
215
-		}
216
-		$message = strtr($message, $replace);
217
-
218
-		if ($level >= $minLevel) {
219
-			$this->writeLog($app, $message, $level);
220
-		}
221
-	}
222
-
223
-	private function getLogLevel($context) {
224
-		/**
225
-		 * check for a special log condition - this enables an increased log on
226
-		 * a per request/user base
227
-		 */
228
-		if ($this->logConditionSatisfied === null) {
229
-			// default to false to just process this once per request
230
-			$this->logConditionSatisfied = false;
231
-			if (!empty($logCondition)) {
232
-
233
-				// check for secret token in the request
234
-				if (isset($logCondition['shared_secret'])) {
235
-					$request = \OC::$server->getRequest();
236
-
237
-					// if token is found in the request change set the log condition to satisfied
238
-					if ($request && hash_equals($logCondition['shared_secret'], $request->getParam('log_secret', ''))) {
239
-						$this->logConditionSatisfied = true;
240
-					}
241
-				}
242
-
243
-				// check for user
244
-				if (isset($logCondition['users'])) {
245
-					$user = \OC::$server->getUserSession()->getUser();
246
-
247
-					// if the user matches set the log condition to satisfied
248
-					if ($user !== null && in_array($user->getUID(), $logCondition['users'], true)) {
249
-						$this->logConditionSatisfied = true;
250
-					}
251
-				}
252
-			}
253
-		}
254
-
255
-		// if log condition is satisfied change the required log level to DEBUG
256
-		if ($this->logConditionSatisfied) {
257
-			return Util::DEBUG;
258
-		}
259
-
260
-		if (isset($context['app'])) {
261
-			$logCondition = $this->config->getSystemValue('log.condition', []);
262
-			$app = $context['app'];
263
-
264
-			/**
265
-			 * check log condition based on the context of each log message
266
-			 * once this is met -> change the required log level to debug
267
-			 */
268
-			if (!empty($logCondition)
269
-				&& isset($logCondition['apps'])
270
-				&& in_array($app, $logCondition['apps'], true)) {
271
-				return Util::DEBUG;
272
-			}
273
-		}
274
-
275
-		return min($this->config->getSystemValue('loglevel', Util::WARN), Util::FATAL);
276
-	}
277
-
278
-	/**
279
-	 * Logs an exception very detailed
280
-	 *
281
-	 * @param \Exception|\Throwable $exception
282
-	 * @param array $context
283
-	 * @return void
284
-	 * @since 8.2.0
285
-	 */
286
-	public function logException(\Throwable $exception, array $context = []) {
287
-		$app = $context['app'] ?? 'no app in context';
288
-		$level = $context['level'] ?? Util::ERROR;
289
-
290
-		$serializer = new ExceptionSerializer();
291
-		$data = $serializer->serializeException($exception);
292
-		$data['CustomMessage'] = $context['message'] ?? '--';
293
-
294
-		$minLevel = $this->getLogLevel($context);
295
-
296
-		array_walk($context, [$this->normalizer, 'format']);
297
-
298
-		if ($level >= $minLevel) {
299
-			if (!$this->logger instanceof IFileBased) {
300
-				$data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);
301
-			}
302
-			$this->writeLog($app, $data, $level);
303
-		}
304
-
305
-		$context['level'] = $level;
306
-		if (!is_null($this->crashReporters)) {
307
-			$this->crashReporters->delegateReport($exception, $context);
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * @param string $app
313
-	 * @param string|array $entry
314
-	 * @param int $level
315
-	 */
316
-	protected function writeLog(string $app, $entry, int $level) {
317
-		$this->logger->write($app, $entry, $level);
318
-	}
319
-
320
-	public function getLogPath():string {
321
-		if($this->logger instanceof IFileBased) {
322
-			return $this->logger->getLogFilePath();
323
-		}
324
-		throw new \RuntimeException('Log implementation has no path');
325
-	}
59
+    /** @var IWriter */
60
+    private $logger;
61
+
62
+    /** @var IConfig */
63
+    private $config;
64
+
65
+    /** @var boolean|null cache the result of the log condition check for the request */
66
+    private $logConditionSatisfied = null;
67
+
68
+    /** @var Normalizer */
69
+    private $normalizer;
70
+
71
+    /** @var IRegistry */
72
+    private $crashReporters;
73
+
74
+    /**
75
+     * @param IWriter $logger The logger that should be used
76
+     * @param IConfig $config the system config object
77
+     * @param Normalizer|null $normalizer
78
+     * @param IRegistry|null $registry
79
+     */
80
+    public function __construct(IWriter $logger, IConfig $config = null, $normalizer = null, IRegistry $registry = null) {
81
+        // FIXME: Add this for backwards compatibility, should be fixed at some point probably
82
+        if ($config === null) {
83
+            $config = \OC::$server->getConfig();
84
+        }
85
+
86
+        $this->config = $config;
87
+        $this->logger = $logger;
88
+        if ($normalizer === null) {
89
+            $this->normalizer = new Normalizer();
90
+        } else {
91
+            $this->normalizer = $normalizer;
92
+        }
93
+        $this->crashReporters = $registry;
94
+    }
95
+
96
+    /**
97
+     * System is unusable.
98
+     *
99
+     * @param string $message
100
+     * @param array $context
101
+     * @return void
102
+     */
103
+    public function emergency(string $message, array $context = []) {
104
+        $this->log(Util::FATAL, $message, $context);
105
+    }
106
+
107
+    /**
108
+     * Action must be taken immediately.
109
+     *
110
+     * Example: Entire website down, database unavailable, etc. This should
111
+     * trigger the SMS alerts and wake you up.
112
+     *
113
+     * @param string $message
114
+     * @param array $context
115
+     * @return void
116
+     */
117
+    public function alert(string $message, array $context = []) {
118
+        $this->log(Util::ERROR, $message, $context);
119
+    }
120
+
121
+    /**
122
+     * Critical conditions.
123
+     *
124
+     * Example: Application component unavailable, unexpected exception.
125
+     *
126
+     * @param string $message
127
+     * @param array $context
128
+     * @return void
129
+     */
130
+    public function critical(string $message, array $context = []) {
131
+        $this->log(Util::ERROR, $message, $context);
132
+    }
133
+
134
+    /**
135
+     * Runtime errors that do not require immediate action but should typically
136
+     * be logged and monitored.
137
+     *
138
+     * @param string $message
139
+     * @param array $context
140
+     * @return void
141
+     */
142
+    public function error(string $message, array $context = []) {
143
+        $this->log(Util::ERROR, $message, $context);
144
+    }
145
+
146
+    /**
147
+     * Exceptional occurrences that are not errors.
148
+     *
149
+     * Example: Use of deprecated APIs, poor use of an API, undesirable things
150
+     * that are not necessarily wrong.
151
+     *
152
+     * @param string $message
153
+     * @param array $context
154
+     * @return void
155
+     */
156
+    public function warning(string $message, array $context = []) {
157
+        $this->log(Util::WARN, $message, $context);
158
+    }
159
+
160
+    /**
161
+     * Normal but significant events.
162
+     *
163
+     * @param string $message
164
+     * @param array $context
165
+     * @return void
166
+     */
167
+    public function notice(string $message, array $context = []) {
168
+        $this->log(Util::INFO, $message, $context);
169
+    }
170
+
171
+    /**
172
+     * Interesting events.
173
+     *
174
+     * Example: User logs in, SQL logs.
175
+     *
176
+     * @param string $message
177
+     * @param array $context
178
+     * @return void
179
+     */
180
+    public function info(string $message, array $context = []) {
181
+        $this->log(Util::INFO, $message, $context);
182
+    }
183
+
184
+    /**
185
+     * Detailed debug information.
186
+     *
187
+     * @param string $message
188
+     * @param array $context
189
+     * @return void
190
+     */
191
+    public function debug(string $message, array $context = []) {
192
+        $this->log(Util::DEBUG, $message, $context);
193
+    }
194
+
195
+
196
+    /**
197
+     * Logs with an arbitrary level.
198
+     *
199
+     * @param int $level
200
+     * @param string $message
201
+     * @param array $context
202
+     * @return void
203
+     */
204
+    public function log(int $level, string $message, array $context = []) {
205
+        $minLevel = $this->getLogLevel($context);
206
+
207
+        array_walk($context, [$this->normalizer, 'format']);
208
+
209
+        $app = $context['app'] ?? 'no app in context';
210
+
211
+        // interpolate $message as defined in PSR-3
212
+        $replace = [];
213
+        foreach ($context as $key => $val) {
214
+            $replace['{' . $key . '}'] = $val;
215
+        }
216
+        $message = strtr($message, $replace);
217
+
218
+        if ($level >= $minLevel) {
219
+            $this->writeLog($app, $message, $level);
220
+        }
221
+    }
222
+
223
+    private function getLogLevel($context) {
224
+        /**
225
+         * check for a special log condition - this enables an increased log on
226
+         * a per request/user base
227
+         */
228
+        if ($this->logConditionSatisfied === null) {
229
+            // default to false to just process this once per request
230
+            $this->logConditionSatisfied = false;
231
+            if (!empty($logCondition)) {
232
+
233
+                // check for secret token in the request
234
+                if (isset($logCondition['shared_secret'])) {
235
+                    $request = \OC::$server->getRequest();
236
+
237
+                    // if token is found in the request change set the log condition to satisfied
238
+                    if ($request && hash_equals($logCondition['shared_secret'], $request->getParam('log_secret', ''))) {
239
+                        $this->logConditionSatisfied = true;
240
+                    }
241
+                }
242
+
243
+                // check for user
244
+                if (isset($logCondition['users'])) {
245
+                    $user = \OC::$server->getUserSession()->getUser();
246
+
247
+                    // if the user matches set the log condition to satisfied
248
+                    if ($user !== null && in_array($user->getUID(), $logCondition['users'], true)) {
249
+                        $this->logConditionSatisfied = true;
250
+                    }
251
+                }
252
+            }
253
+        }
254
+
255
+        // if log condition is satisfied change the required log level to DEBUG
256
+        if ($this->logConditionSatisfied) {
257
+            return Util::DEBUG;
258
+        }
259
+
260
+        if (isset($context['app'])) {
261
+            $logCondition = $this->config->getSystemValue('log.condition', []);
262
+            $app = $context['app'];
263
+
264
+            /**
265
+             * check log condition based on the context of each log message
266
+             * once this is met -> change the required log level to debug
267
+             */
268
+            if (!empty($logCondition)
269
+                && isset($logCondition['apps'])
270
+                && in_array($app, $logCondition['apps'], true)) {
271
+                return Util::DEBUG;
272
+            }
273
+        }
274
+
275
+        return min($this->config->getSystemValue('loglevel', Util::WARN), Util::FATAL);
276
+    }
277
+
278
+    /**
279
+     * Logs an exception very detailed
280
+     *
281
+     * @param \Exception|\Throwable $exception
282
+     * @param array $context
283
+     * @return void
284
+     * @since 8.2.0
285
+     */
286
+    public function logException(\Throwable $exception, array $context = []) {
287
+        $app = $context['app'] ?? 'no app in context';
288
+        $level = $context['level'] ?? Util::ERROR;
289
+
290
+        $serializer = new ExceptionSerializer();
291
+        $data = $serializer->serializeException($exception);
292
+        $data['CustomMessage'] = $context['message'] ?? '--';
293
+
294
+        $minLevel = $this->getLogLevel($context);
295
+
296
+        array_walk($context, [$this->normalizer, 'format']);
297
+
298
+        if ($level >= $minLevel) {
299
+            if (!$this->logger instanceof IFileBased) {
300
+                $data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);
301
+            }
302
+            $this->writeLog($app, $data, $level);
303
+        }
304
+
305
+        $context['level'] = $level;
306
+        if (!is_null($this->crashReporters)) {
307
+            $this->crashReporters->delegateReport($exception, $context);
308
+        }
309
+    }
310
+
311
+    /**
312
+     * @param string $app
313
+     * @param string|array $entry
314
+     * @param int $level
315
+     */
316
+    protected function writeLog(string $app, $entry, int $level) {
317
+        $this->logger->write($app, $entry, $level);
318
+    }
319
+
320
+    public function getLogPath():string {
321
+        if($this->logger instanceof IFileBased) {
322
+            return $this->logger->getLogFilePath();
323
+        }
324
+        throw new \RuntimeException('Log implementation has no path');
325
+    }
326 326
 }
Please login to merge, or discard this patch.
lib/private/Log/Syslog.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -29,27 +29,27 @@
 block discarded – undo
29 29
 use OCP\Log\IWriter;
30 30
 
31 31
 class Syslog implements IWriter {
32
-	static protected $levels = [
33
-		\OCP\Util::DEBUG => LOG_DEBUG,
34
-		\OCP\Util::INFO => LOG_INFO,
35
-		\OCP\Util::WARN => LOG_WARNING,
36
-		\OCP\Util::ERROR => LOG_ERR,
37
-		\OCP\Util::FATAL => LOG_CRIT,
38
-	];
32
+    static protected $levels = [
33
+        \OCP\Util::DEBUG => LOG_DEBUG,
34
+        \OCP\Util::INFO => LOG_INFO,
35
+        \OCP\Util::WARN => LOG_WARNING,
36
+        \OCP\Util::ERROR => LOG_ERR,
37
+        \OCP\Util::FATAL => LOG_CRIT,
38
+    ];
39 39
 
40
-	public function __construct(IConfig $config) {
41
-		openlog($config->getSystemValue('syslog_tag', 'ownCloud'), LOG_PID | LOG_CONS, LOG_USER);
42
-		register_shutdown_function('closelog');
43
-	}
40
+    public function __construct(IConfig $config) {
41
+        openlog($config->getSystemValue('syslog_tag', 'ownCloud'), LOG_PID | LOG_CONS, LOG_USER);
42
+        register_shutdown_function('closelog');
43
+    }
44 44
 
45
-	/**
46
-	 * write a message in the log
47
-	 * @param string $app
48
-	 * @param string $message
49
-	 * @param int $level
50
-	 */
51
-	public function write(string $app, $message, int $level) {
52
-		$syslog_level = self::$levels[$level];
53
-		syslog($syslog_level, '{'.$app.'} '.$message);
54
-	}
45
+    /**
46
+     * write a message in the log
47
+     * @param string $app
48
+     * @param string $message
49
+     * @param int $level
50
+     */
51
+    public function write(string $app, $message, int $level) {
52
+        $syslog_level = self::$levels[$level];
53
+        syslog($syslog_level, '{'.$app.'} '.$message);
54
+    }
55 55
 }
Please login to merge, or discard this patch.
lib/private/Log/Errorlog.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -29,14 +29,14 @@
 block discarded – undo
29 29
 
30 30
 class Errorlog implements IWriter {
31 31
 
32
-	/**
33
-	 * write a message in the log
34
-	 * @param string $app
35
-	 * @param string $message
36
-	 * @param int $level
37
-	 */
38
-	public function write(string $app, $message, int $level) {
39
-		error_log('[owncloud]['.$app.']['.$level.'] '.$message);
40
-	}
32
+    /**
33
+     * write a message in the log
34
+     * @param string $app
35
+     * @param string $message
36
+     * @param int $level
37
+     */
38
+    public function write(string $app, $message, int $level) {
39
+        error_log('[owncloud]['.$app.']['.$level.'] '.$message);
40
+    }
41 41
 }
42 42
 
Please login to merge, or discard this patch.
lib/private/Log/File.php 1 patch
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -46,159 +46,159 @@
 block discarded – undo
46 46
  */
47 47
 
48 48
 class File implements IWriter, IFileBased {
49
-	/** @var string */
50
-	protected $logFile;
51
-	/** @var IConfig */
52
-	private $config;
49
+    /** @var string */
50
+    protected $logFile;
51
+    /** @var IConfig */
52
+    private $config;
53 53
 
54
-	public function __construct(string $path, string $fallbackPath = '', IConfig $config) {
55
-		$this->logFile = $path;
56
-		if (!file_exists($this->logFile)) {
57
-			if(
58
-				(
59
-					!is_writable(dirname($this->logFile))
60
-					|| !touch($this->logFile)
61
-				)
62
-				&& $fallbackPath !== ''
63
-			) {
64
-				$this->logFile = $fallbackPath;
65
-			}
66
-		}
67
-		$this->config = $config;
68
-	}
54
+    public function __construct(string $path, string $fallbackPath = '', IConfig $config) {
55
+        $this->logFile = $path;
56
+        if (!file_exists($this->logFile)) {
57
+            if(
58
+                (
59
+                    !is_writable(dirname($this->logFile))
60
+                    || !touch($this->logFile)
61
+                )
62
+                && $fallbackPath !== ''
63
+            ) {
64
+                $this->logFile = $fallbackPath;
65
+            }
66
+        }
67
+        $this->config = $config;
68
+    }
69 69
 
70
-	/**
71
-	 * write a message in the log
72
-	 * @param string $app
73
-	 * @param string|array $message
74
-	 * @param int $level
75
-	 */
76
-	public function write(string $app, $message, int $level) {
77
-		// default to ISO8601
78
-		$format = $this->config->getSystemValue('logdateformat', \DateTime::ATOM);
79
-		$logTimeZone = $this->config->getSystemValue('logtimezone', 'UTC');
80
-		try {
81
-			$timezone = new \DateTimeZone($logTimeZone);
82
-		} catch (\Exception $e) {
83
-			$timezone = new \DateTimeZone('UTC');
84
-		}
85
-		$time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""));
86
-		if ($time === false) {
87
-			$time = new \DateTime(null, $timezone);
88
-		} else {
89
-			// apply timezone if $time is created from UNIX timestamp
90
-			$time->setTimezone($timezone);
91
-		}
92
-		$request = \OC::$server->getRequest();
93
-		$reqId = $request->getId();
94
-		$remoteAddr = $request->getRemoteAddress();
95
-		// remove username/passwords from URLs before writing the to the log file
96
-		$time = $time->format($format);
97
-		$url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
98
-		$method = is_string($request->getMethod()) ? $request->getMethod() : '--';
99
-		if($this->config->getSystemValue('installed', false)) {
100
-			$user = \OC_User::getUser() ? \OC_User::getUser() : '--';
101
-		} else {
102
-			$user = '--';
103
-		}
104
-		$userAgent = $request->getHeader('User-Agent');
105
-		if ($userAgent === '') {
106
-			$userAgent = '--';
107
-		}
108
-		$version = $this->config->getSystemValue('version', '');
109
-		$entry = compact(
110
-			'reqId',
111
-			'level',
112
-			'time',
113
-			'remoteAddr',
114
-			'user',
115
-			'app',
116
-			'method',
117
-			'url',
118
-			'message',
119
-			'userAgent',
120
-			'version'
121
-		);
122
-		// PHP's json_encode only accept proper UTF-8 strings, loop over all
123
-		// elements to ensure that they are properly UTF-8 compliant or convert
124
-		// them manually.
125
-		foreach($entry as $key => $value) {
126
-			if(is_string($value)) {
127
-				$testEncode = json_encode($value);
128
-				if($testEncode === false) {
129
-					$entry[$key] = utf8_encode($value);
130
-				}
131
-			}
132
-		}
133
-		$entry = json_encode($entry, JSON_PARTIAL_OUTPUT_ON_ERROR);
134
-		$handle = @fopen($this->logFile, 'a');
135
-		if ((fileperms($this->logFile) & 0777) != 0640) {
136
-			@chmod($this->logFile, 0640);
137
-		}
138
-		if ($handle) {
139
-			fwrite($handle, $entry."\n");
140
-			fclose($handle);
141
-		} else {
142
-			// Fall back to error_log
143
-			error_log($entry);
144
-		}
145
-		if (php_sapi_name() === 'cli-server') {
146
-			error_log($message, 4);
147
-		}
148
-	}
70
+    /**
71
+     * write a message in the log
72
+     * @param string $app
73
+     * @param string|array $message
74
+     * @param int $level
75
+     */
76
+    public function write(string $app, $message, int $level) {
77
+        // default to ISO8601
78
+        $format = $this->config->getSystemValue('logdateformat', \DateTime::ATOM);
79
+        $logTimeZone = $this->config->getSystemValue('logtimezone', 'UTC');
80
+        try {
81
+            $timezone = new \DateTimeZone($logTimeZone);
82
+        } catch (\Exception $e) {
83
+            $timezone = new \DateTimeZone('UTC');
84
+        }
85
+        $time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""));
86
+        if ($time === false) {
87
+            $time = new \DateTime(null, $timezone);
88
+        } else {
89
+            // apply timezone if $time is created from UNIX timestamp
90
+            $time->setTimezone($timezone);
91
+        }
92
+        $request = \OC::$server->getRequest();
93
+        $reqId = $request->getId();
94
+        $remoteAddr = $request->getRemoteAddress();
95
+        // remove username/passwords from URLs before writing the to the log file
96
+        $time = $time->format($format);
97
+        $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
98
+        $method = is_string($request->getMethod()) ? $request->getMethod() : '--';
99
+        if($this->config->getSystemValue('installed', false)) {
100
+            $user = \OC_User::getUser() ? \OC_User::getUser() : '--';
101
+        } else {
102
+            $user = '--';
103
+        }
104
+        $userAgent = $request->getHeader('User-Agent');
105
+        if ($userAgent === '') {
106
+            $userAgent = '--';
107
+        }
108
+        $version = $this->config->getSystemValue('version', '');
109
+        $entry = compact(
110
+            'reqId',
111
+            'level',
112
+            'time',
113
+            'remoteAddr',
114
+            'user',
115
+            'app',
116
+            'method',
117
+            'url',
118
+            'message',
119
+            'userAgent',
120
+            'version'
121
+        );
122
+        // PHP's json_encode only accept proper UTF-8 strings, loop over all
123
+        // elements to ensure that they are properly UTF-8 compliant or convert
124
+        // them manually.
125
+        foreach($entry as $key => $value) {
126
+            if(is_string($value)) {
127
+                $testEncode = json_encode($value);
128
+                if($testEncode === false) {
129
+                    $entry[$key] = utf8_encode($value);
130
+                }
131
+            }
132
+        }
133
+        $entry = json_encode($entry, JSON_PARTIAL_OUTPUT_ON_ERROR);
134
+        $handle = @fopen($this->logFile, 'a');
135
+        if ((fileperms($this->logFile) & 0777) != 0640) {
136
+            @chmod($this->logFile, 0640);
137
+        }
138
+        if ($handle) {
139
+            fwrite($handle, $entry."\n");
140
+            fclose($handle);
141
+        } else {
142
+            // Fall back to error_log
143
+            error_log($entry);
144
+        }
145
+        if (php_sapi_name() === 'cli-server') {
146
+            error_log($message, 4);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * get entries from the log in reverse chronological order
152
-	 * @param int $limit
153
-	 * @param int $offset
154
-	 * @return array
155
-	 */
156
-	public function getEntries($limit=50, $offset=0) {
157
-		$minLevel = $this->config->getSystemValue("loglevel", \OCP\Util::WARN);
158
-		$entries = array();
159
-		$handle = @fopen($this->logFile, 'rb');
160
-		if ($handle) {
161
-			fseek($handle, 0, SEEK_END);
162
-			$pos = ftell($handle);
163
-			$line = '';
164
-			$entriesCount = 0;
165
-			$lines = 0;
166
-			// Loop through each character of the file looking for new lines
167
-			while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
168
-				fseek($handle, $pos);
169
-				$ch = fgetc($handle);
170
-				if ($ch == "\n" || $pos == 0) {
171
-					if ($line != '') {
172
-						// Add the first character if at the start of the file,
173
-						// because it doesn't hit the else in the loop
174
-						if ($pos == 0) {
175
-							$line = $ch.$line;
176
-						}
177
-						$entry = json_decode($line);
178
-						// Add the line as an entry if it is passed the offset and is equal or above the log level
179
-						if ($entry->level >= $minLevel) {
180
-							$lines++;
181
-							if ($lines > $offset) {
182
-								$entries[] = $entry;
183
-								$entriesCount++;
184
-							}
185
-						}
186
-						$line = '';
187
-					}
188
-				} else {
189
-					$line = $ch.$line;
190
-				}
191
-				$pos--;
192
-			}
193
-			fclose($handle);
194
-		}
195
-		return $entries;
196
-	}
150
+    /**
151
+     * get entries from the log in reverse chronological order
152
+     * @param int $limit
153
+     * @param int $offset
154
+     * @return array
155
+     */
156
+    public function getEntries($limit=50, $offset=0) {
157
+        $minLevel = $this->config->getSystemValue("loglevel", \OCP\Util::WARN);
158
+        $entries = array();
159
+        $handle = @fopen($this->logFile, 'rb');
160
+        if ($handle) {
161
+            fseek($handle, 0, SEEK_END);
162
+            $pos = ftell($handle);
163
+            $line = '';
164
+            $entriesCount = 0;
165
+            $lines = 0;
166
+            // Loop through each character of the file looking for new lines
167
+            while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
168
+                fseek($handle, $pos);
169
+                $ch = fgetc($handle);
170
+                if ($ch == "\n" || $pos == 0) {
171
+                    if ($line != '') {
172
+                        // Add the first character if at the start of the file,
173
+                        // because it doesn't hit the else in the loop
174
+                        if ($pos == 0) {
175
+                            $line = $ch.$line;
176
+                        }
177
+                        $entry = json_decode($line);
178
+                        // Add the line as an entry if it is passed the offset and is equal or above the log level
179
+                        if ($entry->level >= $minLevel) {
180
+                            $lines++;
181
+                            if ($lines > $offset) {
182
+                                $entries[] = $entry;
183
+                                $entriesCount++;
184
+                            }
185
+                        }
186
+                        $line = '';
187
+                    }
188
+                } else {
189
+                    $line = $ch.$line;
190
+                }
191
+                $pos--;
192
+            }
193
+            fclose($handle);
194
+        }
195
+        return $entries;
196
+    }
197 197
 
198
-	/**
199
-	 * @return string
200
-	 */
201
-	public function getLogFilePath() {
202
-		return $this->logFile;
203
-	}
198
+    /**
199
+     * @return string
200
+     */
201
+    public function getLogFilePath() {
202
+        return $this->logFile;
203
+    }
204 204
 }
Please login to merge, or discard this patch.
lib/private/Log/LogFactory.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -30,48 +30,48 @@
 block discarded – undo
30 30
 use OCP\Log\IWriter;
31 31
 
32 32
 class LogFactory implements ILogFactory {
33
-	/** @var IServerContainer */
34
-	private $c;
33
+    /** @var IServerContainer */
34
+    private $c;
35 35
 
36
-	public function __construct(IServerContainer $c) {
37
-		$this->c = $c;
38
-	}
36
+    public function __construct(IServerContainer $c) {
37
+        $this->c = $c;
38
+    }
39 39
 
40
-	/**
41
-	 * @param $type
42
-	 * @return \OC\Log\Errorlog|File|\stdClass
43
-	 * @throws \OCP\AppFramework\QueryException
44
-	 */
45
-	public function get(string $type):IWriter {
46
-		switch (strtolower($type)) {
47
-			case 'errorlog':
48
-				return new Errorlog();
49
-			case 'syslog':
50
-				return $this->c->resolve(Syslog::class);
51
-			case 'file':
52
-				return $this->buildLogFile();
40
+    /**
41
+     * @param $type
42
+     * @return \OC\Log\Errorlog|File|\stdClass
43
+     * @throws \OCP\AppFramework\QueryException
44
+     */
45
+    public function get(string $type):IWriter {
46
+        switch (strtolower($type)) {
47
+            case 'errorlog':
48
+                return new Errorlog();
49
+            case 'syslog':
50
+                return $this->c->resolve(Syslog::class);
51
+            case 'file':
52
+                return $this->buildLogFile();
53 53
 
54
-			// Backwards compatibility for old and fallback for unknown log types
55
-			case 'owncloud':
56
-			case 'nextcloud':
57
-			default:
58
-				return $this->buildLogFile();
59
-		}
60
-	}
54
+            // Backwards compatibility for old and fallback for unknown log types
55
+            case 'owncloud':
56
+            case 'nextcloud':
57
+            default:
58
+                return $this->buildLogFile();
59
+        }
60
+    }
61 61
 
62
-	public function getCustomLogger(string $path):ILogger {
63
-		$log = $this->buildLogFile($path);
64
-		return new Log($log, $this->c->getConfig());
65
-	}
62
+    public function getCustomLogger(string $path):ILogger {
63
+        $log = $this->buildLogFile($path);
64
+        return new Log($log, $this->c->getConfig());
65
+    }
66 66
 
67
-	protected function buildLogFile(string $logFile = ''):File {
68
-		$config = $this->c->getConfig();
69
-		$defaultLogFile = $config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log';
70
-		if($logFile === '') {
71
-			$logFile = $config->getSystemValue('logfile', $defaultLogFile);
72
-		}
73
-		$fallback = $defaultLogFile !== $logFile ? $defaultLogFile : '';
67
+    protected function buildLogFile(string $logFile = ''):File {
68
+        $config = $this->c->getConfig();
69
+        $defaultLogFile = $config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log';
70
+        if($logFile === '') {
71
+            $logFile = $config->getSystemValue('logfile', $defaultLogFile);
72
+        }
73
+        $fallback = $defaultLogFile !== $logFile ? $defaultLogFile : '';
74 74
 
75
-		return new File($logFile, $fallback, $config);
76
-	}
75
+        return new File($logFile, $fallback, $config);
76
+    }
77 77
 }
Please login to merge, or discard this patch.
lib/public/Log/ILogFactory.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -32,17 +32,17 @@
 block discarded – undo
32 32
  * @since 14.0.0
33 33
  */
34 34
 interface ILogFactory {
35
-	/**
36
-	 * @param string $type - one of: file, errorlog, syslog
37
-	 * @return IWriter
38
-	 * @since 14.0.0
39
-	 */
40
-	public function get(string $type): IWriter;
35
+    /**
36
+     * @param string $type - one of: file, errorlog, syslog
37
+     * @return IWriter
38
+     * @since 14.0.0
39
+     */
40
+    public function get(string $type): IWriter;
41 41
 
42
-	/**
43
-	 * @param string $path
44
-	 * @return ILogger
45
-	 * @since 14.0.0
46
-	 */
47
-	public function getCustomLogger(string $path): ILogger;
42
+    /**
43
+     * @param string $path
44
+     * @return ILogger
45
+     * @since 14.0.0
46
+     */
47
+    public function getCustomLogger(string $path): ILogger;
48 48
 }
Please login to merge, or discard this patch.
lib/public/Log/IWriter.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -30,8 +30,8 @@
 block discarded – undo
30 30
  * @since 14.0.0
31 31
  */
32 32
 interface IWriter {
33
-	/**
34
-	 * @since 14.0.0
35
-	 */
36
-	public function write(string $app, $message, int $level);
33
+    /**
34
+     * @since 14.0.0
35
+     */
36
+    public function write(string $app, $message, int $level);
37 37
 }
Please login to merge, or discard this patch.