FileLog.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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::setConfig('custom', [
  27. 'className' => 'File',
  28. 'path' => LOGS,
  29. 'levels' => [],
  30. 'scopes' => ['custom'],
  31. 'file' => $filename,
  32. ]);
  33. static::$_debugConfig = CoreLog::getConfig('debug');
  34. CoreLog::drop('debug');
  35. }
  36. /**
  37. * Log data into custom file
  38. *
  39. * @param \ArrayObject|array|string $data Data to store
  40. * @param string|null $filename Filename of log file
  41. * @param bool $traceKey Add trace string key into log data
  42. * @return bool Success
  43. */
  44. public static function write($data, $filename = null, $traceKey = false): bool {
  45. static::_init($filename);
  46. // Pretty print array or object
  47. if (is_array($data) || is_object($data)) {
  48. if ($traceKey) {
  49. try {
  50. throw new Exception('Trace string', 1);
  51. } catch (Throwable $t) {
  52. $data['trace_string'] = $t->getTraceAsString();
  53. }
  54. }
  55. $data = print_r($data, true);
  56. }
  57. $logged = CoreLog::write('debug', $data, ['scope' => 'custom']);
  58. static::_cleanUp();
  59. return $logged;
  60. }
  61. /**
  62. * Drop custom log config, set default `debug` config in log registry.
  63. *
  64. * @return void
  65. */
  66. protected static function _cleanUp(): void {
  67. CoreLog::drop('custom');
  68. CoreLog::setConfig('debug', static::$_debugConfig);
  69. }
  70. }