logger.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (C) 2014 Space Monkey, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package spacelog
  15. import (
  16. "sync"
  17. "sync/atomic"
  18. )
  19. // Logger is the basic type that allows for logging. A logger has an associated
  20. // name, given to it during construction, either through a logger collection,
  21. // GetLogger, GetLoggerNamed, or another Logger's Scope method. A logger also
  22. // has an associated level and handler, typically configured through the logger
  23. // collection to which it belongs.
  24. type Logger struct {
  25. level LogLevel
  26. name string
  27. collection *LoggerCollection
  28. handler_mtx sync.RWMutex
  29. handler Handler
  30. }
  31. // Scope returns a new Logger with the same level and handler, using the
  32. // receiver Logger's name as a prefix.
  33. func (l *Logger) Scope(name string) *Logger {
  34. return l.collection.getLogger(l.name+"."+name, l.getLevel(),
  35. l.getHandler())
  36. }
  37. func (l *Logger) setLevel(level LogLevel) {
  38. atomic.StoreInt32((*int32)(&l.level), int32(level))
  39. }
  40. func (l *Logger) getLevel() LogLevel {
  41. return LogLevel(atomic.LoadInt32((*int32)(&l.level)))
  42. }
  43. func (l *Logger) setHandler(handler Handler) {
  44. l.handler_mtx.Lock()
  45. defer l.handler_mtx.Unlock()
  46. l.handler = handler
  47. }
  48. func (l *Logger) getHandler() Handler {
  49. l.handler_mtx.RLock()
  50. defer l.handler_mtx.RUnlock()
  51. return l.handler
  52. }