termlog.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (C) 2010, Kyle Lemons <kyle@kylelemons.net>. All rights reserved.
  2. package log4go
  3. import (
  4. "fmt"
  5. "io"
  6. "os"
  7. "time"
  8. )
  9. var stdout io.Writer = os.Stdout
  10. // This is the standard writer that prints to standard output.
  11. type ConsoleLogWriter struct {
  12. format string
  13. w chan *LogRecord
  14. }
  15. // This creates a new ConsoleLogWriter
  16. func NewConsoleLogWriter() *ConsoleLogWriter {
  17. consoleWriter := &ConsoleLogWriter{
  18. format: "[%T %D] [%L] (%S) %M",
  19. w: make(chan *LogRecord, LogBufferLength),
  20. }
  21. go consoleWriter.run(stdout)
  22. return consoleWriter
  23. }
  24. func (c *ConsoleLogWriter) SetFormat(format string) {
  25. c.format = format
  26. }
  27. func (c *ConsoleLogWriter) run(out io.Writer) {
  28. for rec := range c.w {
  29. fmt.Fprint(out, FormatLogRecord(c.format, rec))
  30. }
  31. }
  32. // This is the ConsoleLogWriter's output method. This will block if the output
  33. // buffer is full.
  34. func (c *ConsoleLogWriter) LogWrite(rec *LogRecord) {
  35. c.w <- rec
  36. }
  37. // Close stops the logger from sending messages to standard output. Attempts to
  38. // send log messages to this logger after a Close have undefined behavior.
  39. func (c *ConsoleLogWriter) Close() {
  40. close(c.w)
  41. time.Sleep(50 * time.Millisecond) // Try to give console I/O time to complete
  42. }