Completed
Push — master ( 24a86a...771b97 )
by Aimeos
10:31
created

File::log()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 5
nop 3
dl 0
loc 18
rs 9.0444
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Metaways Infosystems GmbH, 2013
6
 * @copyright Aimeos (aimeos.org), 2015-2017
7
 * @package MW
8
 * @subpackage Logger
9
 */
10
11
12
namespace Aimeos\MW\Logger;
13
14
15
/**
16
 * Log messages.
17
 *
18
 * @package MW
19
 * @subpackage Logger
20
 */
21
class File extends \Aimeos\MW\Logger\Base implements \Aimeos\MW\Logger\Iface
22
{
23
	private $loglevel;
24
	private $filename;
25
	private $facilities;
26
27
28
	/**
29
	 * Initializes the logger object.
30
	 *
31
	 * @param string $filename Log file name
32
	 * @param integer $priority Minimum priority for logging
33
	 * @param array|null $facilities Facilities for which messages should be logged
34
	 */
35
	public function __construct( $filename, $priority = \Aimeos\MW\Logger\Base::ERR, array $facilities = null )
36
	{
37
		$this->filename = $filename;
38
		$this->loglevel = $priority;
39
		$this->facilities = $facilities;
40
	}
41
42
43
	/**
44
	 * Writes a message to the configured log facility.
45
	 *
46
	 * @param string|array|object $message Message text that should be written to the log facility
47
	 * @param integer $priority Priority of the message for filtering
48
	 * @param string $facility Facility for logging different types of messages (e.g. message, auth, user, changelog)
49
	 * @throws \Aimeos\MW\Logger\Exception If an error occurs in Zend_Log
50
	 * @see \Aimeos\MW\Logger\Base for available log level constants
51
	 */
52
	public function log( $message, $priority = \Aimeos\MW\Logger\Base::ERR, $facility = 'message' )
53
	{
54
		if( $priority <= $this->loglevel
55
			&& ( $this->facilities === null || in_array( $facility, $this->facilities ) ) )
56
		{
57
			$this->checkLogLevel( $priority );
58
59
			if( !is_scalar( $message ) ) {
60
				$message = json_encode( $message );
61
			}
62
63
			$message = '<' . $facility . '> ' . date( 'Y-m-d H:i:s' ) . ' ' . $priority . ' ' . $message . PHP_EOL;
64
65
			if( file_put_contents( $this->filename, $message, FILE_APPEND ) === false ) {
66
				throw new \Aimeos\MW\Logger\Exception( sprintf( 'Unable to write to file "%1$s', $this->filename ) );
67
			}
68
		}
69
	}
70
}
71