Browse Source

Add FileLog.php file

Ishan Vyas 5 years ago
parent
commit
b854e8b55c
2 changed files with 272 additions and 0 deletions
  1. 86 0
      src/Utility/FileLog.php
  2. 186 0
      tests/TestCase/Utility/FileLogTest.php

+ 86 - 0
src/Utility/FileLog.php

@@ -0,0 +1,86 @@
+<?php
+
+namespace Tools\Utility;
+
+use Cake\Log\Log as CoreLog;
+use Exception;
+
+/**
+ * Wrapper class to log data into custom file(s).
+ */
+class FileLog {
+
+	/**
+	 * Debug configuration.
+	 *
+	 * @var mixed|null
+	 */
+	protected static $_debugConfig;
+
+	/**
+	 * Initialize configurations.
+	 *
+	 * @param string $filename Filename to log.
+	 * @return void
+	 */
+	protected static function _init($filename) {
+		if ($filename === null) {
+			$filename = 'custom_log';
+		}
+
+		CoreLog::setConfig('custom', [
+			'className' => 'File',
+			'path' => LOGS,
+			'levels' => [],
+			'scopes' => ['custom'],
+			'file' => $filename,
+		]);
+
+		static::$_debugConfig = CoreLog::getConfig('debug');
+
+		CoreLog::drop('debug');
+	}
+
+	/**
+	 * Log data into custom file
+	 *
+	 * @param array|string $data Data to store
+	 * @param string|null $filename Filename of log file
+	 * @param bool $traceKey Add trace string key into log data
+	 * @return bool Success
+	 */
+	public static function write($data, $filename = null, $traceKey = false) {
+		static::_init($filename);
+
+		// Pretty print array or object
+		if (is_array($data) || is_object($data)) {
+			if ($traceKey) {
+				try {
+					throw new Exception('Trace string', 1);
+				} catch (\Throwable $t) {
+					$data['trace_string'] = $t->getTraceAsString();
+				}
+			}
+
+			$data = print_r($data, true);
+		}
+
+		$logged = CoreLog::write('debug', $data, ['scope' => 'custom']);
+
+		static::_cleanUp();
+
+		return $logged;
+	}
+
+	/**
+	 * Drop custom log config, set default `debug` config in log registry.
+	 *
+	 * @return void
+	 */
+	protected static function _cleanUp() {
+		CoreLog::drop('custom');
+
+		CoreLog::setConfig('debug', static::$_debugConfig);
+	}
+
+}

+ 186 - 0
tests/TestCase/Utility/FileLogTest.php

@@ -0,0 +1,186 @@
+<?php
+
+namespace Tools\Test\Utility;
+
+use Exception;
+use Shim\TestSuite\TestCase;
+use Tools\Utility\FileLog;
+
+/**
+ * FileLogTest class
+ */
+class FileLogTest extends TestCase {
+
+	/**
+	 * Default filename with path to use in test case.
+	 *
+	 * @var string
+	 */
+	private const TEST_DEFAULT_FILENAME_STRING = 'custom_log';
+	private const TEST_DEFAULT_FILEPATH_STRING = LOGS . self::TEST_DEFAULT_FILENAME_STRING . '.log';
+
+	/**
+	 * Filename with path to use in string test case.
+	 *
+	 * @var string
+	 */
+	private const TEST_FILENAME_STRING = 'my_file';
+	private const TEST_FILEPATH_STRING = LOGS . self::TEST_FILENAME_STRING . '.log';
+
+	/**
+	 * Filename with path to use in array test case.
+	 *
+	 * @var string
+	 */
+	private const TEST_FILENAME_ARRAY1 = 'array_file1';
+	private const TEST_FILEPATH_ARRAY1 = LOGS . self::TEST_FILENAME_ARRAY1 . '.log';
+	private const TEST_FILENAME_ARRAY2 = 'array_file2';
+	private const TEST_FILEPATH_ARRAY2 = LOGS . self::TEST_FILENAME_ARRAY2 . '.log';
+
+	/**
+	 * Filename with path to use in object test case.
+	 *
+	 * @var string
+	 */
+	private const TEST_FILENAME_OBJECT = 'object';
+	private const TEST_FILEPATH_OBJECT = LOGS . self::TEST_FILENAME_OBJECT . '.log';
+
+	/**
+	 * setUp method
+	 *
+	 * @return void
+	 */
+	public function setUp(): void {
+		parent::setUp();
+	}
+
+	/**
+	 * testLogsStringData method
+	 *
+	 * @return void
+	 */
+	public function testLogsStringData(): void {
+		if (file_exists(static::TEST_FILEPATH_STRING)) {
+			unlink(static::TEST_FILEPATH_STRING);
+		}
+
+		$result = FileLog::write('It works!', static::TEST_FILENAME_STRING);
+
+		$this->assertTrue($result);
+		$this->assertFileExists(static::TEST_FILEPATH_STRING);
+		$this->assertRegExp(
+			'/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: It works!/',
+			file_get_contents(static::TEST_FILEPATH_STRING)
+		);
+
+		unlink(static::TEST_FILEPATH_STRING);
+	}
+
+	/**
+	 * testLogsArray method
+	 *
+	 * @return void
+	 */
+	public function testLogsArray(): void {
+		if (file_exists(static::TEST_FILEPATH_ARRAY1)) {
+			unlink(static::TEST_FILEPATH_ARRAY1);
+		}
+		if (file_exists(static::TEST_FILEPATH_ARRAY2)) {
+			unlink(static::TEST_FILEPATH_ARRAY2);
+		}
+
+		$result1 = FileLog::write(
+			[
+				'user' => [
+					'id' => 1,
+					'firstname' => 'John Doe',
+					'email' => 'john.doe@example.com',
+				],
+			],
+			static::TEST_FILENAME_ARRAY1
+		);
+
+		$result2 = FileLog::write(
+			[
+				'user' => [
+					'id' => 2,
+					'firstname' => 'Jane Doe',
+					'email' => 'jane.doe@example.com',
+				],
+			],
+			static::TEST_FILENAME_ARRAY2
+		);
+
+		// Assert for `TEST_FILENAME_ARRAY1`
+		$this->assertTrue($result1);
+		$this->assertFileExists(static::TEST_FILEPATH_ARRAY1);
+		$fileContents = file_get_contents(static::TEST_FILEPATH_ARRAY1);
+		$this->assertRegExp(
+			'/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Array([\s\S]*)\(([\s\S]*)[user]([\s\S]*)\[id\] => 1/',
+			$fileContents
+		);
+
+		// Assert for `TEST_FILENAME_ARRAY2`
+		$this->assertTrue($result2);
+		$this->assertFileExists(static::TEST_FILEPATH_ARRAY2);
+		$fileContents = file_get_contents(static::TEST_FILEPATH_ARRAY2);
+		$this->assertRegExp(
+			'/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Array([\s\S]*)\(([\s\S]*)[user]([\s\S]*)\[id\] => 2/',
+			$fileContents
+		);
+
+		unlink(static::TEST_FILEPATH_ARRAY1);
+		unlink(static::TEST_FILEPATH_ARRAY2);
+	}
+
+	/**
+	 * testLogsObject method
+	 *
+	 * @return void
+	 */
+	public function testLogsObject(): void {
+		if (file_exists(static::TEST_FILEPATH_OBJECT)) {
+			unlink(static::TEST_FILEPATH_OBJECT);
+		}
+
+		try {
+			throw new Exception('Test', 1);
+		} catch (Exception $exception) {
+			// Do nothing
+		}
+
+		$result = FileLog::write($exception, static::TEST_FILENAME_OBJECT);
+
+		$this->assertTrue($result);
+		$this->assertFileExists(static::TEST_FILEPATH_OBJECT);
+		$this->assertRegExp(
+			'/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Exception Object/',
+			file_get_contents(static::TEST_FILEPATH_OBJECT)
+		);
+
+		unlink(static::TEST_FILEPATH_OBJECT);
+	}
+
+	/**
+	 * testLogsIntoDefaultFile method
+	 *
+	 * @return void
+	 */
+	public function testLogsIntoDefaultFile(): void {
+		if (file_exists(static::TEST_DEFAULT_FILEPATH_STRING)) {
+			unlink(static::TEST_DEFAULT_FILEPATH_STRING);
+		}
+
+		$result = FileLog::write('It works with default too!');
+
+		$this->assertTrue($result);
+		$this->assertFileExists(static::TEST_DEFAULT_FILEPATH_STRING);
+		$this->assertRegExp(
+			'/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: It works with default too!/',
+			file_get_contents(static::TEST_DEFAULT_FILEPATH_STRING)
+		);
+
+		unlink(static::TEST_DEFAULT_FILEPATH_STRING);
+	}
+
+}