A PX4 based camera pointer

elog.go 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2017 Google Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. package pipoint
  16. import (
  17. "compress/gzip"
  18. "fmt"
  19. "log"
  20. "os"
  21. "time"
  22. )
  23. // EventLogger is a async event logger.
  24. type EventLogger struct {
  25. logger *log.Logger
  26. sink *os.File
  27. zip *gzip.Writer
  28. msgs chan []byte
  29. }
  30. // NewEventLogger creates a new event logger that writes to the given
  31. // base name.
  32. func NewEventLogger(name string) *EventLogger {
  33. now := time.Now().Format(time.RFC3339)
  34. fname := fmt.Sprintf("%s-%s.txt.gz", name, now)
  35. sink, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  36. if err != nil {
  37. log.Panicln(err)
  38. }
  39. zip := gzip.NewWriter(sink)
  40. msgs := make(chan []byte, 10)
  41. el := &EventLogger{
  42. sink: sink,
  43. zip: zip,
  44. msgs: msgs,
  45. }
  46. el.logger = log.New(el, "", log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)
  47. go el.run()
  48. return el
  49. }
  50. func (el *EventLogger) run() {
  51. tick := time.Tick(3 * time.Second)
  52. for {
  53. select {
  54. case p := <-el.msgs:
  55. el.zip.Write(p)
  56. case <-tick:
  57. el.zip.Flush()
  58. break
  59. }
  60. }
  61. }
  62. func (el *EventLogger) Write(p []byte) (n int, err error) {
  63. buf := make([]byte, len(p))
  64. copy(buf, p)
  65. el.msgs <- buf
  66. return len(p), nil
  67. }