logsystem.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package logger
  17. import (
  18. "io"
  19. "log"
  20. "sync/atomic"
  21. )
  22. // LogSystem is implemented by log output devices.
  23. // All methods can be called concurrently from multiple goroutines.
  24. type LogSystem interface {
  25. LogPrint(LogMsg)
  26. }
  27. // NewStdLogSystem creates a LogSystem that prints to the given writer.
  28. // The flag values are defined package log.
  29. func NewStdLogSystem(writer io.Writer, flags int, level LogLevel) *StdLogSystem {
  30. logger := log.New(writer, "", flags)
  31. return &StdLogSystem{logger, uint32(level)}
  32. }
  33. type StdLogSystem struct {
  34. logger *log.Logger
  35. level uint32
  36. }
  37. func (t *StdLogSystem) LogPrint(msg LogMsg) {
  38. stdmsg, ok := msg.(stdMsg)
  39. if ok {
  40. if t.GetLogLevel() >= stdmsg.Level() {
  41. t.logger.Print(stdmsg.String())
  42. }
  43. }
  44. }
  45. func (t *StdLogSystem) SetLogLevel(i LogLevel) {
  46. atomic.StoreUint32(&t.level, uint32(i))
  47. }
  48. func (t *StdLogSystem) GetLogLevel() LogLevel {
  49. return LogLevel(atomic.LoadUint32(&t.level))
  50. }
  51. // NewJSONLogSystem creates a LogSystem that prints to the given writer without
  52. // adding extra information irrespective of loglevel only if message is JSON type
  53. func NewJsonLogSystem(writer io.Writer) LogSystem {
  54. logger := log.New(writer, "", 0)
  55. return &jsonLogSystem{logger}
  56. }
  57. type jsonLogSystem struct {
  58. logger *log.Logger
  59. }
  60. func (t *jsonLogSystem) LogPrint(msg LogMsg) {
  61. jsonmsg, ok := msg.(jsonMsg)
  62. if ok {
  63. t.logger.Print(jsonmsg.String())
  64. }
  65. }