Логер, с созданием архивов за прошедший день

  1. class loger {
  2.  
  3. private static $user;    
  4. private static $dir;    
  5. private static $logdir = 'logs';
  6. private static $archdir = 'archive';
  7.  
  8. public function __construct($user) {
  9. if (!is_dir(self::$logdir . DIRECTORY_SEPARATOR . date('Y-m-d'))) {
  10. if (!mkdir(self::$logdir . DIRECTORY_SEPARATOR . date('Y-m-d'), 0777, true)) {
  11. #throw new Exception('WTF, log dir not created');    
  12. }
  13. }
  14. if (!is_dir(self::$archdir)) {
  15. if (!mkdir(self::$archdir, 0777, true)) {
  16. #throw new Exception('WTF, archive dir not created');    
  17. }
  18. }
  19. self::$dir = self::$logdir . DIRECTORY_SEPARATOR . date('Y-m-d');
  20. self::$user = $user;
  21. }
  22.  
  23. public static function writelog($text) {
  24. if (self::$dir === null) {
  25. #throw new Exception('WTF, dir not initialiting');
  26. } else {
  27. $file = self::$dir . DIRECTORY_SEPARATOR . self::$user . '.txt';
  28. file_put_contents($file, $text . PHP_EOL, FILE_APPEND | LOCK_EX);
  29. }
  30. self::logrotate();    
  31. }
  32.  
  33. public static function logrotate() {
  34. $sda = array_diff(scandir(self::$logdir), array('.', '..'));
  35. if (sizeof($sda)>0) {
  36. foreach ($sda as $dir) {
  37. if ($dir != date('Y-m-d')) {
  38. $zip = new ZipArchive;
  39. if ($zip->open(self::$archdir . DIRECTORY_SEPARATOR . $dir . '.zip', ZipArchive::CREATE) === TRUE) {
  40. $zip->addEmptyDir($dir);
  41. $sdf = array_diff(scandir(self::$logdir . DIRECTORY_SEPARATOR . $dir), array('.', '..'));    
  42. foreach ($sdf as $file) {
  43. $zip->addFile(self::$logdir . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $file, $dir . DIRECTORY_SEPARATOR . $file);    
  44. }
  45. $zip->close();
  46. } else {
  47. #throw new Exception('WTF, archive not created');
  48. }
  49. if (is_file(self::$archdir . DIRECTORY_SEPARATOR . $dir . '.zip')) {
  50. self::deldir(self::$logdir . DIRECTORY_SEPARATOR . $dir);    
  51. }
  52. }
  53. }
  54. }
  55. }
  56.  
  57. public static function deldir($dir) {
  58. $dirarr = array_diff(scandir($dir), array('.', '..'));
  59. if (sizeof($dirarr)>0) {    
  60. foreach ($dirarr as $file) {
  61. unlink($dir . DIRECTORY_SEPARATOR . $file);
  62. }
  63. }
  64. rmdir($dir);
  65. }
  66.  
  67. }
пользоваться так
  1. include('koelog.php');    
  2. new loger($user_name);
  3. loger::writelog('test1');
  4. loger::writelog('test2');
  5. loger::writelog('test3');
  6. loger::writelog('test4');

Реклама

Мы в соцсетях

tw tg yt gt