Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Logger
- {
- private $logPath;
- private $files;
- public function __construct($relativeLogPath = '/logs', $files = 10)
- {
- if (class_exists('\Bitrix\Main\Application')) {
- $this->logPath = \Bitrix\Main\Application::getDocumentRoot() . $relativeLogPath;
- } elseif ($_SERVER['DOCUMENT_ROOT']) {
- $this->logPath = $_SERVER['DOCUMENT_ROOT'] . $relativeLogPath;
- } else {
- $this->logPath = __DIR__ . $relativeLogPath;
- }
- $this->files = $files;
- }
- public function write($dump, $file = 'info', $message = '')
- {
- if (!is_dir($this->logPath . '/')) {
- mkdir($this->logPath . '/');
- }
- $file = $this->logPath . '/' . $file . '.log';
- if (!is_string($dump)) {
- $dump = var_export($dump, true);
- }
- ignore_user_abort(true);
- if ($fp = @fopen($file, "ab")) {
- if (flock($fp, LOCK_EX)) {
- @fwrite($fp, "Date: " . date("Y-m-d H:i:s") . "\n");
- if ($message) {
- @fwrite($fp, "Message: " . $message . "\n");
- }
- @fwrite($fp, "Dump: " . $dump . "\n");
- @fwrite($fp, str_repeat('-', 30) . "\n\n");
- @fflush($fp);
- @flock($fp, LOCK_UN);
- @fclose($fp);
- }
- }
- ignore_user_abort(false);
- // if filesize more than 10 Mb rotate it
- if (filesize($file) > 10485760) {
- $this->rotate($file);
- }
- }
- private function rotate($file)
- {
- $path = pathinfo($file);
- $rotate = implode('', array(
- $path['dirname'],
- '/',
- $path['filename'],
- '_',
- date('Y-m-d_H:i:s'),
- '.',
- $path['extension']
- ));
- copy($file, $rotate);
- $this->clean($file);
- $files = glob($path['dirname'] . '/' . $path['filename'] . "*" . ".log");
- if (0 === $this->files) {
- return;
- }
- if (count($files) > $this->files) {
- natsort($files);
- $files = array_reverse($files);
- foreach (array_slice($files, $this->files) as $log) {
- if (is_writable($log)) {
- unlink($log);
- }
- }
- }
- }
- private function clean($file)
- {
- file_put_contents($file, '');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement