Log.php 1.6 KB

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