logger.go 909 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package main
  2. import (
  3. "encoding/csv"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. )
  9. const (
  10. dateFormat = "20060102"
  11. )
  12. func getWriter() (*csv.Writer, *os.File) {
  13. logFile := filepath.Join("log", (time.Now().Format(dateFormat) + ".log"))
  14. logOutput, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  15. if err != nil {
  16. log.Printf("Log file error: %s", err)
  17. return nil, nil
  18. }
  19. writer := csv.NewWriter(logOutput)
  20. return writer, logOutput
  21. }
  22. func writeLog(info SearchInfo) {
  23. writer, file := getWriter()
  24. if writer == nil || file == nil {
  25. return
  26. }
  27. defer func() {
  28. if err := file.Close(); err != nil {
  29. log.Printf("Error closing csv: %s", err)
  30. }
  31. }()
  32. writer.Write(info.ToArray())
  33. if err := writer.Error(); err != nil {
  34. log.Printf("Error writing csv: %s", err)
  35. return
  36. }
  37. writer.Flush()
  38. if err := writer.Error(); err != nil {
  39. log.Printf("Error flushing csv: %s", err)
  40. }
  41. }