File: File.php

package info (click to toggle)
simplesamlphp 1.13.1-2%2Bdeb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 11,304 kB
  • sloc: php: 65,124; xml: 629; python: 376; sh: 193; perl: 185; makefile: 43
file content (97 lines) | stat: -rw-r--r-- 2,041 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php

/**
 * Statistics logger that writes to a set of log files
 *
 * @package simpleSAMLphp
 */
class sspmod_core_Stats_Output_File extends SimpleSAML_Stats_Output {

	/**
	 * The log directory.
	 * @var string
	 */
	private $logDir;


	/**
	 * The file handle for the current file.
	 * @var resource
	 */
	private $file = NULL;

	/**
	 * The current file date.
	 * @var string
	 */
	private $fileDate = NULL;


	/**
	 * Initialize the output.
	 *
	 * @param SimpleSAML_Configuration $config  The configuration for this output.
	 */
	public function __construct(SimpleSAML_Configuration $config) {

		$this->logDir = $config->getPathValue('directory');
		if ($this->logDir === NULL) {
			throw new Exception('Missing "directory" option for core:File');
		}
		if (!is_dir($this->logDir)) {
			throw new Exception('Could not find log directory: ' . var_export($this->logDir, TRUE));
		}

	}


	/**
	 * Open a log file.
	 *
	 * @param string $date  The date for the log file.
	 */
	private function openLog($date) {
		assert('is_string($date)');

		if ($this->file !== NULL && $this->file !== FALSE) {
			fclose($this->file);
			$this->file = NULL;
		}

		$fileName = $this->logDir . '/' . $date . '.log';
		$this->file = @fopen($fileName, 'a');
		if ($this->file === FALSE) {
			throw new SimpleSAML_Error_Exception('Error opening log file: ' . var_export($fileName, TRUE));
		}

		/* Disable output buffering. */
		stream_set_write_buffer($this->file, 0);

		$this->fileDate = $date;
	}


	/**
	 * Write a stats event.
	 *
	 * @param array $data  The event.
	 */
	public function emit(array $data) {
		assert('isset($data["time"])');

		$time = $data['time'];
		$milliseconds = (int)(($time - (int)$time) * 1000);

		$timestamp = gmdate('Y-m-d\TH:i:s', $time) . sprintf('.%03dZ', $milliseconds);

		$outDate = substr($timestamp, 0, 10); /* The date-part of the timstamp. */

		if ($outDate !== $this->fileDate) {
			$this->openLog($outDate);
		}

		$line = $timestamp . ' ' . json_encode($data) . "\n";
		fwrite($this->file, $line);
	}

}