logger.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # Copyright (c) 2017–2018 crocoite contributors
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. # THE SOFTWARE.
  20. """
  21. Simple logger inspired by structlog.
  22. It is usually used like this: Classes are passed a logger instance. They bind
  23. context to their name, so identifying the source of messages is easier. Every
  24. log message carries a unique id (uuid) for automated identification as well as
  25. a short human-readable message (msg) and arbitrary payload.
  26. """
  27. import sys, json
  28. from datetime import datetime
  29. from functools import partial
  30. from enum import IntEnum
  31. from pytz import utc
  32. from .util import StrJsonEncoder
  33. class Level(IntEnum):
  34. DEBUG = 0
  35. INFO = 1
  36. WARNING = 2
  37. ERROR = 3
  38. class Logger:
  39. def __init__ (self, consumer=None, bindings=None):
  40. self.bindings = bindings or {}
  41. self.consumer = consumer or []
  42. def __call__ (self, level, *args, **kwargs):
  43. if not isinstance (level, Level):
  44. level = Level[level.upper ()]
  45. kwargs['level'] = level
  46. if args:
  47. if len (args) == 1:
  48. args, = args
  49. kwargs['msg'] = args
  50. # do not overwrite arguments
  51. for k, v in self.bindings.items ():
  52. if k not in kwargs:
  53. kwargs[k] = v
  54. for c in self.consumer:
  55. kwargs = c (**kwargs)
  56. return kwargs
  57. def __getattr__ (self, k):
  58. """ Bind all method names to level, so Logger.info, Logger.warning, … work """
  59. return partial (self.__call__, k)
  60. def bind (self, **kwargs):
  61. d = self.bindings.copy ()
  62. d.update (kwargs)
  63. # consumer is not a copy intentionally, so attaching to the parent
  64. # logger will attach to all children as well
  65. return self.__class__ (consumer=self.consumer, bindings=d)
  66. def unbind (self, **kwargs):
  67. d = self.bindings.copy ()
  68. for k in kwargs.keys ():
  69. del d[k]
  70. return self.__class__ (consumer=self.consumer, bindings=d)
  71. def connect (self, consumer):
  72. self.consumer.append (consumer)
  73. def disconnect (self, consumer):
  74. self.consumer.remove (consumer)
  75. class Consumer:
  76. def __call__ (self, **kwargs): # pragma: no cover
  77. raise NotImplementedError ()
  78. class NullConsumer (Consumer):
  79. def __call__ (self, **kwargs):
  80. return kwargs
  81. class PrintConsumer (Consumer):
  82. """
  83. Simple printing consumer
  84. """
  85. def __call__ (self, **kwargs):
  86. sys.stderr.write (str (kwargs))
  87. sys.stderr.write ('\n')
  88. sys.stderr.flush ()
  89. return kwargs
  90. class JsonPrintConsumer (Consumer):
  91. def __init__ (self, minLevel=Level.DEBUG):
  92. self.minLevel = minLevel
  93. def __call__ (self, **kwargs):
  94. if kwargs['level'] >= self.minLevel:
  95. json.dump (kwargs, sys.stdout, cls=StrJsonEncoder)
  96. sys.stdout.write ('\n')
  97. sys.stdout.flush ()
  98. return kwargs
  99. class DatetimeConsumer (Consumer):
  100. def __call__ (self, **kwargs):
  101. kwargs['date'] = datetime.utcnow ().replace (tzinfo=utc)
  102. return kwargs
  103. class WarcHandlerConsumer (Consumer):
  104. def __init__ (self, warc, minLevel=Level.DEBUG):
  105. self.warc = warc
  106. self.minLevel = minLevel
  107. def __call__ (self, **kwargs):
  108. if kwargs['level'] >= self.minLevel:
  109. self.warc._writeLog (json.dumps (kwargs, cls=StrJsonEncoder))
  110. return kwargs