log.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program 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
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. '''Qubes logging routines
  22. See also: :py:attr:`qubes.vm.qubesvm.QubesVM.log`
  23. '''
  24. import logging
  25. import os
  26. import sys
  27. import fcntl
  28. import dbus
  29. FORMAT_CONSOLE = '%(message)s'
  30. FORMAT_LOG = '%(asctime)s %(message)s'
  31. FORMAT_DEBUG = '%(asctime)s ' \
  32. '[%(processName)s %(module)s.%(funcName)s:%(lineno)d] %(name)s: %(message)s'
  33. LOGPATH = '/var/log/qubes'
  34. LOGFILE = os.path.join(LOGPATH, 'qubes.log')
  35. formatter_console = logging.Formatter(FORMAT_CONSOLE)
  36. formatter_log = logging.Formatter(FORMAT_LOG)
  37. formatter_debug = logging.Formatter(FORMAT_DEBUG)
  38. class DBusHandler(logging.Handler):
  39. '''Handler which displays records as DBus notifications'''
  40. #: mapping of loglevels to icons
  41. app_icons = {
  42. logging.ERROR: 'dialog-error',
  43. logging.WARNING: 'dialog-warning',
  44. logging.NOTSET: 'dialog-information',
  45. }
  46. def __init__(self, *args, **kwargs):
  47. super(DBusHandler, self).__init__(*args, **kwargs)
  48. self._notify_object = dbus.SessionBus().get_object(
  49. 'org.freedesktop.Notifications', '/org/freedesktop/Notifications')
  50. def emit(self, record):
  51. app_icon = self.app_icons[
  52. max(level for level in self.app_icons if level <= record.levelno)]
  53. try:
  54. # https://developer.gnome.org/notification-spec/#command-notify
  55. self._notify_object.Notify(
  56. 'Qubes', # STRING app_name
  57. 0, # UINT32 replaces_id
  58. app_icon, # STRING app_icon
  59. record.msg, # STRING summary
  60. '', # STRING body
  61. (), # ARRAY actions
  62. {}, # DICT hints
  63. 0, # INT32 timeout
  64. dbus_interface='org.freedesktop.Notifications')
  65. except dbus.DBusException:
  66. pass
  67. def enable():
  68. '''Enable global logging
  69. Use :py:mod:`logging` module from standard library to log messages.
  70. >>> import qubes.log
  71. >>> qubes.log.enable() # doctest: +SKIP
  72. >>> import logging
  73. >>> logging.warning('Foobar') # doctest: +SKIP
  74. '''
  75. if logging.root.handlers:
  76. return
  77. handler_console = logging.StreamHandler(sys.stderr)
  78. handler_console.setFormatter(formatter_console)
  79. logging.root.addHandler(handler_console)
  80. if os.path.exists('/var/log/qubes'):
  81. log_path = '/var/log/qubes/qubes.log'
  82. else:
  83. # for tests, travis etc
  84. log_path = '/tmp/qubes.log'
  85. old_umask = os.umask(0o007)
  86. try:
  87. handler_log = logging.FileHandler(log_path, 'a', encoding='utf-8')
  88. fcntl.fcntl(handler_log.stream.fileno(),
  89. fcntl.F_SETFD, fcntl.FD_CLOEXEC)
  90. finally:
  91. os.umask(old_umask)
  92. handler_log.setFormatter(formatter_log)
  93. logging.root.addHandler(handler_log)
  94. logging.root.setLevel(logging.INFO)
  95. def enable_debug():
  96. '''Enable debug logging
  97. Enable more messages and additional info to message format.
  98. '''
  99. enable()
  100. logging.root.setLevel(logging.DEBUG)
  101. for handler in logging.root.handlers:
  102. handler.setFormatter(formatter_debug)
  103. def get_vm_logger(vmname):
  104. '''Initialise logging for particular VM name
  105. :param str vmname: VM's name
  106. :rtype: :py:class:`logging.Logger`
  107. '''
  108. logger = logging.getLogger('vm.' + vmname)
  109. if logger.handlers:
  110. return logger
  111. old_umask = os.umask(0o007)
  112. try:
  113. handler = logging.FileHandler(
  114. os.path.join(LOGPATH, 'vm-{}.log'.format(vmname)))
  115. fcntl.fcntl(handler.stream.fileno(),
  116. fcntl.F_SETFD, fcntl.FD_CLOEXEC)
  117. finally:
  118. os.umask(old_umask)
  119. handler.setFormatter(formatter_log)
  120. logger.addHandler(handler)
  121. return logger