aboutsummaryrefslogtreecommitdiff
path: root/voctocore/lib/loghandler.py
blob: 6efb89059c43b0265f6bec3eee8ccc0513ed7270 (plain)
  1. import logging
  2. import time
  3. class LogFormatter(logging.Formatter):
  4. def __init__(self, docolor, timestamps=False):
  5. super().__init__()
  6. self.docolor = docolor
  7. self.timestamps = timestamps
  8. def formatMessage(self, record):
  9. if self.docolor:
  10. c_lvl = 33
  11. c_mod = 32
  12. c_msg = 0
  13. if record.levelno == logging.WARNING:
  14. c_lvl = 31
  15. # c_mod = 33
  16. c_msg = 33
  17. elif record.levelno > logging.WARNING:
  18. c_lvl = 31
  19. c_mod = 31
  20. c_msg = 31
  21. fmt = ''.join([
  22. '\x1b[%dm' % c_lvl, # set levelname color
  23. '%(levelname)8s', # print levelname
  24. '\x1b[0m', # reset formatting
  25. '\x1b[%dm' % c_mod, # set name color
  26. ' %(name)s', # print name
  27. '\x1b[%dm' % c_msg, # set message color
  28. ': %(message)s', # print message
  29. '\x1b[0m' # reset formatting
  30. ])
  31. else:
  32. fmt = '%(levelname)8s %(name)s: %(message)s'
  33. if self.timestamps:
  34. fmt = '%(asctime)s ' + fmt
  35. if 'asctime' not in record.__dict__:
  36. record.__dict__['asctime'] = time.strftime(
  37. "%Y-%m-%d %H:%M:%S",
  38. time.localtime(record.__dict__['created'])
  39. )
  40. return fmt % record.__dict__
  41. class LogHandler(logging.StreamHandler):
  42. def __init__(self, docolor, timestamps):
  43. super().__init__()
  44. self.setFormatter(LogFormatter(docolor, timestamps))