1
0
mirror of synced 2024-11-22 21:36:10 +03:00
bitrix-module/intaro.retailcrm/classes/general/Logger.php

111 lines
2.6 KiB
PHP
Raw Normal View History

2015-11-09 17:46:32 +03:00
<?php
2020-04-24 13:18:18 +03:00
/**
* Class Logger
*/
2015-11-09 17:46:32 +03:00
class Logger
{
2020-04-24 13:18:18 +03:00
/** @var self $instance */
private static $instance;
/** @var string $logPath */
2015-11-09 17:46:32 +03:00
private $logPath;
2020-04-24 13:18:18 +03:00
/** @var int $files */
2015-11-09 17:46:32 +03:00
private $files;
2020-04-24 13:18:18 +03:00
/**
* Get logger instance or re-initialize it with new parameters
*
* @param string $logPath
* @param int $files
*
* @return \Logger
*/
public static function getInstance($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3)
{
if (empty(self::$instance)
|| (self::$instance instanceof self
&& (self::$instance->logPath !== $logPath || self::$instance->files !== $files))
2020-04-24 13:18:18 +03:00
) {
self::$instance = new Logger($logPath, $files);
}
return self::$instance;
}
/**
* Logger constructor.
*
* @param string $logPath
* @param int $files
*/
public function __construct($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3)
2015-11-09 17:46:32 +03:00
{
$this->logPath = $logPath;
$this->files = $files;
}
2015-11-09 17:46:32 +03:00
public function write($dump, $file = 'info')
{
$rsSites = CSite::GetList($by, $sort, array('DEFAULT' => 'Y'));
2016-09-15 16:42:10 +03:00
$ar = $rsSites->Fetch();
2016-10-04 17:57:39 +03:00
if (!is_dir($ar['ABS_DOC_ROOT'] . $this->logPath . '/')) {
2016-09-15 16:42:10 +03:00
mkdir($ar['ABS_DOC_ROOT'] . $this->logPath . '/');
}
$file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log';
2016-09-15 16:42:10 +03:00
2015-11-09 17:46:32 +03:00
$data['TIME'] = date('Y-m-d H:i:s');
$data['DATA'] = $dump;
$f = fopen($file, "a+");
2016-10-04 17:57:39 +03:00
fwrite($f, print_r($data, true));
fclose($f);
2015-11-09 17:46:32 +03:00
// if filesize more than 5 Mb rotate it
if (filesize($file) > 5242880) {
$this->rotate($file);
}
2015-11-09 17:46:32 +03:00
}
private function rotate($file)
{
$path = pathinfo($file);
$rotate = implode('', array(
$path['dirname'],
'/',
$path['filename'],
2016-09-15 16:42:10 +03:00
'_',
date('Y-m-d_H:i:s'),
2015-11-09 17:46:32 +03:00
'.',
$path['extension']
));
copy($file, $rotate);
$this->clean($file);
2016-09-15 16:42:10 +03:00
$files = glob($path['dirname'] . '/' . $path['filename'] . "*" . ".log");
2015-11-09 17:46:32 +03:00
if (0 === $this->files) {
return;
}
if (count($files) > $this->files) {
natsort($files);
2016-09-15 16:42:10 +03:00
$files = array_reverse($files);
2015-11-09 17:46:32 +03:00
foreach (array_slice($files, $this->files) as $log) {
if (is_writable($log)) {
unlink($log);
}
}
}
}
private function clean($file)
{
file_put_contents($file, '');
}
}