prettylog.go 933 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package prettylog
  2. import (
  3. "fmt"
  4. "log"
  5. "runtime"
  6. "strings"
  7. "time"
  8. )
  9. // Writer struct that implements writer
  10. type Writer struct {
  11. lastTime time.Time
  12. counter int64
  13. }
  14. // New writer
  15. func New() *Writer {
  16. return &Writer{time.Now(), 0}
  17. }
  18. // Write writer implementation
  19. func (w *Writer) Write(b []byte) (int, error) {
  20. ptr, _, line, _ := runtime.Caller(3)
  21. tname := runtime.FuncForPC(ptr).Name()
  22. li := strings.LastIndex(tname, "/")
  23. fname := tname[li+1:]
  24. timeDiff := time.Since(w.lastTime)
  25. var fduration = float64(timeDiff.Nanoseconds()) / 1000000.0
  26. msg := fmt.Sprintf("[%d:\033[34m%s\033[0m (\033[33m%s:%d\033[0m) \033[90m+%.2f/ms\033[0m]: %s",
  27. w.counter,
  28. time.Now().Format("2006-01-02 15:04:05"),
  29. fname,
  30. line,
  31. fduration,
  32. string(b),
  33. )
  34. w.lastTime = time.Now()
  35. w.counter++
  36. return fmt.Print(msg)
  37. }
  38. //CreateLogger creates a new log.Logger
  39. func CreateLogger() *log.Logger {
  40. return log.New(New(), "", 0)
  41. }