فهرست منبع

added DebugExecutionTime logToFile

Piotr Labudda 8 سال پیش
والد
کامیت
ffaf395ad1
1فایلهای تغییر یافته به همراه66 افزوده شده و 1 حذف شده
  1. 66 1
      SE/se-lib/DebugExecutionTime.php

+ 66 - 1
SE/se-lib/DebugExecutionTime.php

@@ -1,6 +1,6 @@
 <?php
 
-/* usage:
+/* usage 1 - log to memory and print report:
 	Lib::loadClass('DebugExecutionTime');
 	$dbgExecTime = new DebugExecutionTime();
 	$dbgExecTime->activate();
@@ -9,12 +9,22 @@
 	$dbgExecTime->log('end');
 	$dbgExecTime->printDebug();
 */
+/* usage 2 - log to file:
+	Lib::loadClass('DebugExecutionTime');
+	$dbgExecTime = new DebugExecutionTime();
+	$dbgExecTime->setLogFile('UNIQ_FILE_NAME', $format = 'csv'); // $format: 'csv', 'json'
+	$dbgExecTime->logToFile('start');
+	...
+	$dbgExecTime->logToFile('end');
+*/
 class DebugExecutionTime {
 
 	private $_log = array();
 	private $_logByGroups = array();
 	private $_isActive = false;
 	private $_lastTime = 0;
+	private $_logFile = null;
+	private $_logFormat = null;
 
 	public function __construct() {
 		$this->_log = array();
@@ -24,6 +34,61 @@ class DebugExecutionTime {
 		$this->_isActive = true;
 	}
 
+	public function setLogFile($fileName, $format = 'csv') { // @param $format = 'csv', 'json'
+		if (!file_exists($fileName)) @touch($fileName);
+		if (!file_exists($fileName)) return; // log error?
+		$this->_logFile = $fileName;
+		switch ($format) {
+			case 'json'; $this->_logFormat = 'json'; break;
+			default: $this->_logFormat = 'csv';
+		}
+	}
+
+	public function logToFile($msg) {
+		if (!$this->_logFile) return;
+		static $_idRequest = null;
+		static $_lastMicroTime = null;
+		// $timeDiff = (!$lastTime)
+		// ? ''
+		// : V::milisecondsStringDiff($dbg['date'], $lastTime); // TODO: $dbg['date'] - $lastTime;
+		$microTime = date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6);
+		$info = [
+			'date' => $microTime,
+			'diff' => ($_lastMicroTime) ? V::milisecondsStringDiff($microTime, $_lastMicroTime) : '',
+			'req' => $_idRequest,
+			'mem' => memory_get_usage(true),
+			'msg' => $msg,
+		];
+		$_lastMicroTime = $microTime;
+		if (null === $_idRequest && 'csv' === $this->_logFormat) {
+			error_log(
+				implode("\t", array_keys($info)) . "\n"
+				, 3
+				, $this->_logFile
+			);
+		}
+		if (null === $_idRequest) {
+			$_idRequest = substr(md5(date("Y-m-d") . Request::getUserIp() . V::get('REQUEST_TIME', '', $_SERVER)), 0, 6);
+			$info['req'] = $_idRequest;
+		}
+		switch ($this->_logFormat) {
+			case 'csv': {
+				error_log(
+					implode("\t", array_values($info)) . "\n"
+					, 3
+					, $this->_logFile
+				);
+			} break;
+			case 'json': {
+				error_log(
+					json_encode($info) . "\n"
+					, 3
+					, $this->_logFile
+				);
+			} break;
+		}
+	}
+
 	/*
 	 * @param $msg string or NULL (NULL to log only group stats)
 	 */