log.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. '''Qubes logging routines
  21. See also: :py:attr:`qubes.vm.qubesvm.QubesVM.log`
  22. '''
  23. import logging
  24. import sys
  25. class Formatter(logging.Formatter):
  26. def __init__(self, *args, debug=False, **kwargs):
  27. super().__init__(*args, **kwargs)
  28. self.debug = debug
  29. def formatMessage(self, record):
  30. fmt = ''
  31. if self.debug:
  32. fmt += '[%(processName)s %(module)s.%(funcName)s:%(lineno)d] '
  33. if self.debug or record.name.startswith('vm.'):
  34. fmt += '%(name)s: '
  35. fmt += '%(message)s'
  36. return fmt % record.__dict__
  37. def enable():
  38. '''Enable global logging
  39. Use :py:mod:`logging` module from standard library to log messages.
  40. >>> import qubes.log
  41. >>> qubes.log.enable() # doctest: +SKIP
  42. >>> import logging
  43. >>> logging.warning('Foobar') # doctest: +SKIP
  44. '''
  45. if logging.root.handlers:
  46. return
  47. handler_console = logging.StreamHandler(sys.stderr)
  48. handler_console.setFormatter(Formatter())
  49. logging.root.addHandler(handler_console)
  50. logging.root.setLevel(logging.INFO)
  51. def enable_debug():
  52. '''Enable debug logging
  53. Enable more messages and additional info to message format.
  54. '''
  55. enable()
  56. for handler in logging.root.handlers:
  57. handler.setFormatter(Formatter(debug=True))
  58. logging.root.setLevel(logging.DEBUG)
  59. def get_vm_logger(vmname):
  60. '''Initialise logging for particular VM name
  61. :param str vmname: VM's name
  62. :rtype: :py:class:`logging.Logger`
  63. '''
  64. return logging.getLogger('vm.' + vmname)