FileLog.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Tools\Utility;
  3. use Cake\Log\Log as CoreLog;
  4. use Exception;
  5. use Throwable;
  6. /**
  7. * Wrapper class to log data into custom file(s).
  8. */
  9. class FileLog {
  10. /**
  11. * Debug configuration.
  12. *
  13. * @var mixed|null
  14. */
  15. protected static $_debugConfig;
  16. /**
  17. * Initialize configurations.
  18. *
  19. * @param string|null $filename Filename to log.
  20. * @return void
  21. */
  22. protected static function _init($filename): void {
  23. if ($filename === null) {
  24. $filename = 'custom_log';
  25. }
  26. CoreLog::drop('custom');
  27. CoreLog::setConfig('custom', [
  28. 'className' => 'File',
  29. 'path' => LOGS,
  30. 'levels' => [],
  31. 'scopes' => ['custom'],
  32. 'file' => $filename,
  33. ]);
  34. static::$_debugConfig = CoreLog::getConfig('debug');
  35. CoreLog::drop('debug');
  36. }
  37. /**
  38. * Log data into custom file
  39. *
  40. * @param \ArrayObject|array|string $data Data to store
  41. * @param string|null $filename Filename of log file
  42. * @param bool $traceKey Add trace string key into log data
  43. * @return bool Success
  44. */
  45. public static function write($data, $filename = null, $traceKey = false): bool {
  46. static::_init($filename);
  47. // Pretty print array or object
  48. if (is_array($data) || is_object($data)) {
  49. if ($traceKey) {
  50. try {
  51. throw new Exception('Trace string', 1);
  52. } catch (Throwable $t) {
  53. $data['trace_string'] = $t->getTraceAsString();
  54. }
  55. }
  56. $data = print_r($data, true);
  57. }
  58. $logged = CoreLog::write('debug', $data, ['scope' => 'custom']);
  59. static::_cleanUp();
  60. return $logged;
  61. }
  62. /**
  63. * Drop custom log config, set default `debug` config in log registry.
  64. *
  65. * @return void
  66. */
  67. protected static function _cleanUp(): void {
  68. CoreLog::drop('custom');
  69. CoreLog::setConfig('debug', static::$_debugConfig);
  70. }
  71. }