event_log.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
  2. // Use of this source code is governed by the MIT-license that can be
  3. // found in the LICENSE file.
  4. package main
  5. import (
  6. "encoding/json"
  7. "net"
  8. "os"
  9. "time"
  10. )
  11. type EventLogger struct {
  12. file *os.File
  13. enc *json.Encoder
  14. }
  15. func NewEventLogger(path string) (*EventLogger, error) {
  16. file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
  17. return &EventLogger{file, json.NewEncoder(file)}, err
  18. }
  19. func (l *EventLogger) Close() error { return l.file.Close() }
  20. func (l *EventLogger) Log(what string, event map[string]interface{}) {
  21. event["log_time"] = time.Now()
  22. event["what"] = what
  23. if err := l.enc.Encode(event); err != nil {
  24. panic(err)
  25. }
  26. }
  27. func (l *EventLogger) LogConn(op string, freq Frequency, conn net.Conn, err error) {
  28. e := map[string]interface{}{"success": err == nil}
  29. if err != nil {
  30. e["error"] = err.Error()
  31. } else {
  32. if remote := conn.RemoteAddr(); remote != nil {
  33. e["remote_addr"] = remote.String()
  34. e["network"] = conn.RemoteAddr().Network()
  35. }
  36. if local := conn.LocalAddr(); local != nil {
  37. e["local_addr"] = local.String()
  38. }
  39. }
  40. if freq > 0 {
  41. e["freq"] = freq
  42. }
  43. e["operation"] = op
  44. l.Log("connect", e)
  45. }