LogTarget.php 2.04 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8
namespace yii\debug;
Qiang Xue committed
9 10

use Yii;
Qiang Xue committed
11
use yii\log\Target;
Qiang Xue committed
12 13 14 15 16

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
17
class LogTarget extends Target
Qiang Xue committed
18
{
Qiang Xue committed
19 20 21 22
	/**
	 * @var Module
	 */
	public $module;
Qiang Xue committed
23
	public $tag;
Qiang Xue committed
24

Qiang Xue committed
25 26 27 28
	/**
	 * @param \yii\debug\Module $module
	 * @param array $config
	 */
Qiang Xue committed
29 30 31 32
	public function __construct($module, $config = array())
	{
		parent::__construct($config);
		$this->module = $module;
Qiang Xue committed
33
		$this->tag = uniqid();
Qiang Xue committed
34 35
	}

Qiang Xue committed
36 37 38 39
	/**
	 * Exports log messages to a specific destination.
	 * Child classes must implement this method.
	 */
Qiang Xue committed
40
	public function export()
Qiang Xue committed
41
	{
Qiang Xue committed
42
		$path = $this->module->dataPath;
Qiang Xue committed
43 44 45
		if (!is_dir($path)) {
			mkdir($path);
		}
Qiang Xue committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
		$indexFile = "$path/index.json";
		if (!is_file($indexFile)) {
			$manifest = array();
		} else {
			$manifest = json_decode(file_get_contents($indexFile), true);
		}
		$request = Yii::$app->getRequest();
		$manifest[$this->tag] = array(
			'url' => $request->getAbsoluteUrl(),
			'ajax' => $request->getIsAjax(),
			'method' => $request->getMethod(),
			'ip' => $request->getUserIP(),
			'time' => time(),
		);

		$dataFile = "$path/{$this->tag}.json";
Qiang Xue committed
62
		$data = array();
Qiang Xue committed
63 64
		foreach ($this->module->panels as $id => $panel) {
			$data[$id] = $panel->save();
Qiang Xue committed
65
		}
Qiang Xue committed
66 67
		file_put_contents($dataFile, json_encode($data));
		file_put_contents($indexFile, json_encode($manifest));
Qiang Xue committed
68 69 70 71 72 73 74 75 76 77 78 79
	}

	/**
	 * Processes the given log messages.
	 * This method will filter the given messages with [[levels]] and [[categories]].
	 * And if requested, it will also export the filtering result to specific medium (e.g. email).
	 * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
	 * of each message.
	 * @param boolean $final whether this method is called at the end of the current application
	 */
	public function collect($messages, $final)
	{
Qiang Xue committed
80
		$this->messages = array_merge($this->messages, $messages);
Qiang Xue committed
81
		if ($final) {
Qiang Xue committed
82 83 84 85
			$this->export($this->messages);
		}
	}
}