logger.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "encoding/csv"
  4. "log"
  5. "net"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "time"
  10. "strconv"
  11. )
  12. const (
  13. timeFormat = "2006-01-02 15:04"
  14. dateFormat = "20060102"
  15. )
  16. type searchInfo struct {
  17. Date time.Time
  18. Host, Phrase, Language string
  19. ResultsServed int
  20. }
  21. func (s *searchInfo) ToArray() []string {
  22. return []string{s.Date.Format(timeFormat), s.Host, s.Phrase, s.Language, strconv.Itoa(s.ResultsServed)}
  23. }
  24. func getInfoFromRequest(r *http.Request) searchInfo {
  25. info := searchInfo{Date: time.Now()}
  26. info.Host, _, _ = net.SplitHostPort(r.RemoteAddr)
  27. info.Phrase = r.URL.Query().Get("phrase")
  28. if info.Phrase == "" {
  29. info.Phrase = "TMS"
  30. }
  31. language := r.URL.Query().Get("lang")
  32. if language == "" {
  33. info.Language = "All languages"
  34. } else {
  35. info.Language = app.Languages[language]
  36. }
  37. return info
  38. }
  39. func getWriter() *csv.Writer {
  40. logFile := filepath.Join("log", (time.Now().Format(dateFormat) + ".log"))
  41. logOutput, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  42. if err != nil {
  43. log.Fatalf("Error creating log file: %v", err)
  44. }
  45. writer := csv.NewWriter(logOutput)
  46. return writer
  47. }
  48. // WriteLog main function, saves event to the log.
  49. func WriteLog(r *http.Request, resultsServed int) {
  50. info := getInfoFromRequest(r)
  51. info.ResultsServed = resultsServed
  52. writer := getWriter()
  53. writer.Write(info.ToArray())
  54. writer.Flush()
  55. }