log.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/python2 -O
  2. # -*- coding: utf-8 -*-
  3. '''Qubes logging routines
  4. See also: :py:attr:`qubes.vm.qubesvm.QubesVM.logger`
  5. '''
  6. import logging
  7. import os
  8. import sys
  9. FORMAT_CONSOLE = '%(message)s'
  10. FORMAT_LOG = '%(asctime)s %(message)s'
  11. FORMAT_DEBUG = '%(asctime)s [%(processName)s %(module)s.%(funcName)s:%(lineno)d] %(name)s: %(message)s'
  12. LOGPATH = '/var/log/qubes'
  13. LOGFILE = os.path.join(LOGPATH, 'qubes.log')
  14. formatter_console = logging.Formatter(FORMAT_CONSOLE)
  15. formatter_log = logging.Formatter(FORMAT_LOG)
  16. formatter_debug = logging.Formatter(FORMAT_DEBUG)
  17. def enable():
  18. '''Enable global logging
  19. Use :py:mod:`logging` module from standard library to log messages.
  20. >>> import qubes.log
  21. >>> qubes.log.enable() # doctest: +SKIP
  22. >>> import logging
  23. >>> logging.warning('Foobar') # doctest: +SKIP
  24. '''
  25. if logging.root.handlers:
  26. return
  27. handler_console = logging.StreamHandler(sys.stderr)
  28. handler_console.setFormatter(formatter_console)
  29. logging.root.addHandler(handler_console)
  30. handler_log = logging.FileHandler('log', 'a', encoding='utf-8')
  31. handler_log.setFormatter(formatter_log)
  32. logging.root.addHandler(handler_log)
  33. logging.root.setLevel(logging.INFO)
  34. def enable_debug():
  35. '''Enable debug logging
  36. Enable more messages and additional info to message format.
  37. '''
  38. enable()
  39. logging.root.setLevel(logging.DEBUG)
  40. for handler in logging.root.handlers:
  41. handler.setFormatter(formatter_debug)
  42. def get_vm_logger(vmname):
  43. '''Initialise logging for particular VM name
  44. :param str vmname: VM's name
  45. :rtype: :py:class:`logging.Logger`
  46. '''
  47. logger = logging.getLogger('vm.' + vmname)
  48. handler = logging.FileHandler(os.path.join(LOGPATH, 'vm', vmname + '.log'))
  49. handler.setFormatter(formatter_log)
  50. logger.addHandler(handler)
  51. return logger