date_patterns.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package nginx_log
  2. import (
  3. "regexp"
  4. "strings"
  5. )
  6. // LogRotationDatePatterns defines common log rotation date patterns
  7. var LogRotationDatePatterns = []string{
  8. `^\d{8}$`, // YYYYMMDD
  9. `^\d{4}-\d{2}-\d{2}$`, // YYYY-MM-DD
  10. `^\d{4}\.\d{2}\.\d{2}$`, // YYYY.MM.DD
  11. `^\d{4}_\d{2}_\d{2}$`, // YYYY_MM_DD
  12. `^\d{10}$`, // YYYYMMDDHH
  13. `^\d{12}$`, // YYYYMMDDHHMI
  14. `^\d{4}-\d{2}-\d{2}_\d{2}$`, // YYYY-MM-DD_HH
  15. }
  16. // isDatePattern checks if a string matches any date pattern
  17. func isDatePattern(s string) bool {
  18. for _, pattern := range LogRotationDatePatterns {
  19. if matched, _ := regexp.MatchString(pattern, s); matched {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. // isCompressedDatePattern checks if a string is a compressed date pattern (e.g., "20231201.gz")
  26. func isCompressedDatePattern(s string) bool {
  27. if !strings.HasSuffix(s, ".gz") {
  28. return false
  29. }
  30. datePart := strings.TrimSuffix(s, ".gz")
  31. return isDatePattern(datePart)
  32. }
  33. // isNumberPattern checks if a string is a numeric rotation pattern (e.g., "1", "2", "10")
  34. func isNumberPattern(s string) bool {
  35. matched, _ := regexp.MatchString(`^\d+$`, s)
  36. return matched
  37. }
  38. // isCompressedNumberPattern checks if a string is a compressed numeric pattern (e.g., "1.gz", "2.gz")
  39. func isCompressedNumberPattern(s string) bool {
  40. if !strings.HasSuffix(s, ".gz") {
  41. return false
  42. }
  43. numberPart := strings.TrimSuffix(s, ".gz")
  44. return isNumberPattern(numberPart)
  45. }
  46. // isLogrotateFile determines if a file is a logrotate-generated file
  47. func isLogrotateFile(filename, baseLogName string) bool {
  48. // If filename equals baseLogName, it's the active log file
  49. if filename == baseLogName {
  50. return true
  51. }
  52. // Check if it starts with the base log name
  53. if !strings.HasPrefix(filename, baseLogName) {
  54. return false
  55. }
  56. // Extract the suffix after the base log name
  57. suffix := strings.TrimPrefix(filename, baseLogName)
  58. if !strings.HasPrefix(suffix, ".") {
  59. return false
  60. }
  61. suffix = strings.TrimPrefix(suffix, ".")
  62. // Check various rotation patterns
  63. return isNumberPattern(suffix) ||
  64. isCompressedNumberPattern(suffix) ||
  65. isDatePattern(suffix) ||
  66. isCompressedDatePattern(suffix)
  67. }