logger.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package log
  2. import (
  3. log "code.google.com/p/log4go"
  4. "fmt"
  5. )
  6. const (
  7. logfile string = "ngrok.log"
  8. )
  9. func init() {
  10. // log4go automatically sets the global logger to write to stdout
  11. // and we don't want that by default
  12. delete(log.Global, "stdout")
  13. }
  14. func LogToConsole() {
  15. log.Global.AddFilter("log", log.DEBUG, log.NewConsoleLogWriter())
  16. }
  17. func LogToFile() {
  18. log.Global.AddFilter("log", log.DEBUG, log.NewFileLogWriter(logfile, true))
  19. }
  20. type Logger interface {
  21. AddLogPrefix(string)
  22. Debug(string, ...interface{})
  23. Info(string, ...interface{})
  24. Warn(string, ...interface{}) error
  25. Error(string, ...interface{}) error
  26. }
  27. type PrefixLogger struct {
  28. *log.Logger
  29. prefix string
  30. }
  31. func NewPrefixLogger() Logger {
  32. return &PrefixLogger{Logger: &log.Global}
  33. }
  34. func (pl *PrefixLogger) pfx(fmtstr string) interface{} {
  35. return fmt.Sprintf("%s %s", pl.prefix, fmtstr)
  36. }
  37. func (pl *PrefixLogger) Debug(arg0 string, args ...interface{}) {
  38. pl.Logger.Debug(pl.pfx(arg0), args...)
  39. }
  40. func (pl *PrefixLogger) Info(arg0 string, args ...interface{}) {
  41. pl.Logger.Info(pl.pfx(arg0), args...)
  42. }
  43. func (pl *PrefixLogger) Warn(arg0 string, args ...interface{}) error {
  44. return pl.Logger.Warn(pl.pfx(arg0), args...)
  45. }
  46. func (pl *PrefixLogger) Error(arg0 string, args ...interface{}) error {
  47. return pl.Logger.Error(pl.pfx(arg0), args...)
  48. }
  49. func (pl *PrefixLogger) AddLogPrefix(prefix string) {
  50. if len(pl.prefix) > 0 {
  51. pl.prefix += " "
  52. }
  53. pl.prefix += "[" + prefix + "]"
  54. }