Bez popisu
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 4.6KB

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