Açıklama Yok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

logger.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. #-*- coding: utf-8 -*-
  2. import copy
  3. import logging, logging.handlers
  4. import os.path
  5. # Variables & constants definitions
  6. default_format = '%(asctime)-15s %(levelname)s %(_pathname)s:%(_lineno)s:%(_funcName)s() : %(message)s'
  7. simple_format = '%(asctime)-15s %(levelname)s : %(message)s'
  8. SECURITY_LOGLEVEL = 35
  9. logging.addLevelName(SECURITY_LOGLEVEL, 'SECURITY')
  10. handlers = dict() # Handlers list (generated from settings)
  11. ##@brief Stores sent messages until module is able to be initialized
  12. msg_buffer = []
  13. # Fetching logger for current context
  14. from lodel.context import LodelContext
  15. logger = logging.getLogger(LodelContext.get_name())
  16. ##@brief Module initialisation from settings
  17. #@return True if inited else False
  18. def __init_from_settings():
  19. from lodel.context import LodelContext
  20. try:
  21. LodelContext.expose_modules(globals(), {
  22. 'lodel.settings': ['Settings']})
  23. except Exception:
  24. return False
  25. LodelContext.expose_modules(globals(), {
  26. 'lodel.settings.settings': [('Settings', 'Lodel2Settings')]})
  27. if not Lodel2Settings.started():
  28. return False
  29. # capture warning disabled, because the custom format raises error (unable
  30. # to give the _ preffixed arguments to logger resulting into a KeyError
  31. # exception )
  32. #logging.captureWarnings(True) # Log warnings
  33. logger.setLevel(logging.DEBUG)
  34. for name in Settings.logging._fields:
  35. add_handler(name, getattr(Settings.logging, name))
  36. return True
  37. ##@brief Add an handler, identified by a name, to a given logger
  38. #
  39. # logging_opt is a dict with logger option. Allowed keys are :
  40. # - filename : take a filepath as value and cause the use of a logging.handlers.RotatingFileHandler
  41. # - level : the minimum logging level for a logger, takes values [ 'DEBUG', 'INFO', 'WARNING', 'SECURITY', 'ERROR', 'CRITICAL' ]
  42. # - format : DONT USE THIS OPTION (or if you use it be sure to includes %(_pathname)s %(_lineno)s %(_funcName)s format variables in format string
  43. # - context : boolean, if True include the context (module:lineno:function_name) in the log format
  44. # @todo Move the logging_opt documentation somewhere related with settings
  45. #
  46. # @param name str : The handler name
  47. # @param logging_opt dict : dict containing options ( see above )
  48. def add_handler(name, logging_opt):
  49. logger = logging.getLogger(LodelContext.get_name())
  50. if name in handlers:
  51. raise KeyError("A handler named '%s' allready exists")
  52. logging_opt = logging_opt._asdict()
  53. if 'filename' in logging_opt and logging_opt['filename'] is not None:
  54. maxBytes = (1024 * 10) if 'maxbytes' not in logging_opt else logging_opt['maxbytes']
  55. backupCount = 10 if 'backupcount' not in logging_opt else logging_opt['backupcount']
  56. handler = logging.handlers.RotatingFileHandler(
  57. logging_opt['filename'],
  58. maxBytes = maxBytes,
  59. backupCount = backupCount,
  60. encoding = 'utf-8')
  61. else:
  62. handler = logging.StreamHandler()
  63. if 'level' in logging_opt:
  64. handler.setLevel(getattr(logging, logging_opt['level'].upper()))
  65. if 'format' in logging_opt:
  66. formatter = logging.Formatter(logging_opt['format'])
  67. else:
  68. if 'context' in logging_opt and not logging_opt['context']:
  69. formatter = logging.Formatter(simple_format)
  70. else:
  71. formatter = logging.Formatter(default_format)
  72. handler.setFormatter(formatter)
  73. handlers[name] = handler
  74. logger.addHandler(handler)
  75. ##@brief Remove an handler generated from configuration (runtime logger configuration)
  76. # @param name str : handler name
  77. def remove_handler(name):
  78. if name in handlers:
  79. logger.removeHandler(handlers[name])
  80. # else: can we do anything ?
  81. ##@brief Utility function that disable unconditionnaly handlers that implies console output
  82. # @note In fact, this function disables handlers generated from settings wich are instances of logging.StreamHandler
  83. def remove_console_handlers():
  84. for name, handler in handlers.items():
  85. if isinstance(handler, logging.StreamHandler):
  86. remove_handler(name)
  87. #####################
  88. # Utility functions #
  89. #####################
  90. ##@brief Generic logging function
  91. # @param lvl int : Log severity
  92. # @param msg str : log message
  93. # @param *args : additional positionnal arguments
  94. # @param **kwargs : additional named arguments
  95. def log(lvl, msg, *args, **kwargs):
  96. if len(handlers) == 0: #late initialisation
  97. if not __init_from_settings():
  98. s_kwargs = copy.copy(kwargs)
  99. s_kwargs.update({'lvl': lvl, 'msg':msg})
  100. msg_buffer.append((s_kwargs, args))
  101. return
  102. else:
  103. for s_kwargs, args in msg_buffer:
  104. log(*args, **s_kwargs)
  105. from lodel.context import LodelContext
  106. if LodelContext.multisite():
  107. msg = "CTX(%s) %s" % (LodelContext.get_name(), msg)
  108. caller = logger.findCaller() # Opti warning : small overhead
  109. extra = {
  110. '_pathname': os.path.abspath(caller[0]),
  111. '_lineno': caller[1],
  112. '_funcName': caller[2],
  113. }
  114. logger.log(lvl, msg, extra = extra, *args, **kwargs)
  115. def debug(msg, *args, **kwargs): log(logging.DEBUG, msg, *args, **kwargs)
  116. def info(msg, *args, **kwargs): log(logging.INFO, msg, *args, **kwargs)
  117. def warning(msg, *args, **kwargs): log(logging.WARNING, msg, *args, **kwargs)
  118. def security(msg, *args, **kwargs): log(SECURITY_LOGLEVEL, msg, *args, **kwargs)
  119. def error(msg, *args, **kwargs): log(logging.ERROR, msg, *args, **kwargs)
  120. def critical(msg, *args, **kwargs): log(logging.CRITICAL, msg, *args, **kwargs)