reader.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package gonx
  2. import (
  3. "io"
  4. )
  5. // Reader is a log file reader. Use specific constructors to create it.
  6. type Reader struct {
  7. file io.Reader
  8. parser StringParser
  9. entries chan *Entry
  10. }
  11. // NewReader creates a reader for a custom log format.
  12. func NewReader(logFile io.Reader, format string) *Reader {
  13. return NewParserReader(logFile, NewParser(format))
  14. }
  15. // NewParserReader creates a reader with the given parser
  16. func NewParserReader(logFile io.Reader, parser StringParser) *Reader {
  17. return &Reader{
  18. file: logFile,
  19. parser: parser,
  20. }
  21. }
  22. // NewNginxReader creates a reader for the nginx log format. Nginx config parser will be used
  23. // to get particular format from the conf file.
  24. func NewNginxReader(logFile io.Reader, nginxConf io.Reader, formatName string) (reader *Reader, err error) {
  25. parser, err := NewNginxParser(nginxConf, formatName)
  26. if err != nil {
  27. return nil, err
  28. }
  29. reader = &Reader{
  30. file: logFile,
  31. parser: parser,
  32. }
  33. return
  34. }
  35. // Read next parsed Entry from the log file. Return EOF if there are no Entries to read.
  36. func (r *Reader) Read() (entry *Entry, err error) {
  37. if r.entries == nil {
  38. r.entries = MapReduce(r.file, r.parser, new(ReadAll))
  39. }
  40. entry, ok := <-r.entries
  41. if !ok {
  42. err = io.EOF
  43. }
  44. return
  45. }