log_cache.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package nginx_log
  2. import (
  3. "sync"
  4. )
  5. // NginxLogCache represents a cached log entry from nginx configuration
  6. type NginxLogCache struct {
  7. Path string `json:"path"` // Path to the log file
  8. Type string `json:"type"` // Type of log: "access" or "error"
  9. Name string `json:"name"` // Name of the log file
  10. ConfigFile string `json:"config_file"` // Path to the configuration file that contains this log directive
  11. }
  12. var (
  13. // logCache is the map to store all found log files
  14. logCache = make(map[string]*NginxLogCache)
  15. cacheMutex sync.RWMutex
  16. )
  17. // AddLogPath adds a log path to the log cache with the source config file
  18. func AddLogPath(path, logType, name, configFile string) {
  19. cacheMutex.Lock()
  20. defer cacheMutex.Unlock()
  21. logCache[path] = &NginxLogCache{
  22. Path: path,
  23. Type: logType,
  24. Name: name,
  25. ConfigFile: configFile,
  26. }
  27. }
  28. // RemoveLogPathsFromConfig removes all log paths that come from a specific config file
  29. func RemoveLogPathsFromConfig(configFile string) {
  30. cacheMutex.Lock()
  31. defer cacheMutex.Unlock()
  32. for path, cache := range logCache {
  33. if cache.ConfigFile == configFile {
  34. delete(logCache, path)
  35. }
  36. }
  37. }
  38. // GetAllLogPaths returns all cached log paths
  39. func GetAllLogPaths(filters ...func(*NginxLogCache) bool) []*NginxLogCache {
  40. cacheMutex.RLock()
  41. defer cacheMutex.RUnlock()
  42. result := make([]*NginxLogCache, 0, len(logCache))
  43. for _, cache := range logCache {
  44. flag := true
  45. if len(filters) > 0 {
  46. for _, filter := range filters {
  47. if !filter(cache) {
  48. flag = false
  49. break
  50. }
  51. }
  52. }
  53. if flag {
  54. result = append(result, cache)
  55. }
  56. }
  57. return result
  58. }
  59. // ClearLogCache clears all entries in the log cache
  60. func ClearLogCache() {
  61. cacheMutex.Lock()
  62. defer cacheMutex.Unlock()
  63. // Clear the cache
  64. logCache = make(map[string]*NginxLogCache)
  65. }