logger.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package main
  2. import (
  3. "log"
  4. "net"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. )
  10. // GetInfoFromRequest reads information from given request and returns them as tuple.
  11. func GetInfoFromRequest(r *http.Request) (string, string, string) {
  12. host, _, _ := net.SplitHostPort(r.RemoteAddr)
  13. searchPhrase := r.URL.Query().Get("phrase")
  14. language := r.URL.Query().Get("lang")
  15. if language == "" {
  16. language = "All languages"
  17. } else {
  18. language = app.Languages[language]
  19. }
  20. return host, searchPhrase, language
  21. }
  22. // GetLogger returns new logger
  23. func GetLogger() *log.Logger {
  24. logFile := filepath.Join("log", (time.Now().Format("20060102") + ".log"))
  25. logOutput, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  26. if err != nil {
  27. log.Fatalf("Error creating log file: %v", err)
  28. }
  29. logger := log.New(logOutput, "", log.Ldate|log.Ltime)
  30. return logger
  31. }
  32. // Logger main function, saves event to the log.
  33. func Logger(r *http.Request, resultsServed int) {
  34. host, searchPhrase, language := GetInfoFromRequest(r)
  35. logger := GetLogger()
  36. if searchPhrase != "" {
  37. logger.Printf(",%v,\"%v\",\"%v\",%v\n", host, searchPhrase, language, resultsServed)
  38. } else {
  39. logger.Printf(",%v,TMS,\"%v\",%v\n", host, language, resultsServed)
  40. }
  41. }