socklog.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2010, Kyle Lemons <kyle@kylelemons.net>. All rights reserved.
  2. package log4go
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "os"
  8. )
  9. // This log writer sends output to a socket
  10. type SocketLogWriter chan *LogRecord
  11. // This is the SocketLogWriter's output method
  12. func (w SocketLogWriter) LogWrite(rec *LogRecord) {
  13. w <- rec
  14. }
  15. func (w SocketLogWriter) Close() {
  16. close(w)
  17. }
  18. func NewSocketLogWriter(proto, hostport string) SocketLogWriter {
  19. sock, err := net.Dial(proto, hostport)
  20. if err != nil {
  21. fmt.Fprintf(os.Stderr, "NewSocketLogWriter(%q): %s\n", hostport, err)
  22. return nil
  23. }
  24. w := SocketLogWriter(make(chan *LogRecord, LogBufferLength))
  25. go func() {
  26. defer func() {
  27. if sock != nil && proto == "tcp" {
  28. sock.Close()
  29. }
  30. }()
  31. for rec := range w {
  32. // Marshall into JSON
  33. js, err := json.Marshal(rec)
  34. if err != nil {
  35. fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
  36. return
  37. }
  38. _, err = sock.Write(js)
  39. if err != nil {
  40. fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
  41. return
  42. }
  43. }
  44. }()
  45. return w
  46. }