暫無描述
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.3KB

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