def init_request_instrument(app=None,
                            custom_formatter=None,
                            exclude_url_patterns=[]):
    """
    Configure the request instrumentation logging configuration for given web app. Must be called after init method

    If **custom_formatter** is passed, it will use this formatter over the default.

    :param app: current web application instance
    :param custom_formatter: formatter to override default JSONRequestLogFormatter.
    """

    if _current_framework is None or _current_framework == '-':
        raise RuntimeError(
            "please init the logging first, call init(framework_name) first")

    if custom_formatter:
        if not issubclass(custom_formatter, logging.Formatter):
            raise ValueError(
                'custom_formatter is not subclass of logging.Formatter',
                custom_formatter)

    configurator = _current_framework[
        'app_request_instrumentation_configurator']()
    configurator.config(app, exclude_url_patterns=exclude_url_patterns)

    formatter = custom_formatter if custom_formatter else JSONRequestLogFormatter
    request_logger = configurator.request_logger
    request_logger.setLevel(logging.DEBUG)
    request_logger.addHandler(logging.StreamHandler(sys.stdout))
    util.update_formatter_for_loggers([request_logger], formatter)
    request_logger.parent = None
Exemple #2
0
def config_root_logger():
    """
        You must call this if you are using root logger.
        Make all root logger' handlers produce JSON format
        & remove duplicate handlers for request instrumentation logging
    """
    if ENABLE_JSON_LOGGING:
        _logger.debug("Update root logger to using JSONLogFormatter")
        if len(logging.root.handlers) > 0:
            if _current_framework is not None or _current_framework != '-':
                util.update_formatter_for_loggers([logging.root],
                                                  JSONLogWebFormatter)
            else:
                util.update_formatter_for_loggers([logging.root],
                                                  JSONLogFormatter)
            # remove all handlers for request logging
            request_logger = _current_framework[
                'app_request_instrumentation_configurator'](
                ).get_request_logger()
            if request_logger:
                for handler in request_logger.handlers:
                    request_logger.removeHandler(handler)
        else:
            _logger.error(
                "No logging handlers found for root logger. Please made sure that you call this after you called "
                "logging.basicConfig() or logging.getLogger('root')")
def __init(framework_name=None, custom_formatter=None):
    """
    Initialize JSON logging support, if no **framework_name** passed, logging will be initialized in non-web context.
    This is supposed to be called only one time.

    If **custom_formatter** is passed, it will (in non-web context) use this formatter over the default.

    :param framework_name: type of framework logging should support.
    :param custom_formatter: formatter to override default JSONLogFormatter.
    """

    global _current_framework
    if _current_framework is not None:
        raise RuntimeError("Can not call init more than once")

    if custom_formatter:
        if not issubclass(custom_formatter, logging.Formatter):
            raise ValueError(
                'custom_formatter is not subclass of logging.Formatter',
                custom_formatter)

    ENABLE_JSON_LOGGING_DEBUG and _logger.info("init framework " +
                                               str(framework_name))

    if framework_name:
        framework_name = framework_name.lower()
        if framework_name not in _framework_support_map.keys():
            raise RuntimeError(framework_name +
                               " is not a supported framework")

        _current_framework = _framework_support_map[framework_name]
        global _request_util
        _request_util = util.RequestUtil(
            request_adapter_class=_current_framework['request_adapter_class'],
            response_adapter_class=_current_framework['response_adapter_class']
        )

        if ENABLE_JSON_LOGGING and _current_framework[
                'app_configurator'] is not None:
            _current_framework['app_configurator']().config()

        formatter = custom_formatter if custom_formatter else JSONLogWebFormatter
    else:
        formatter = custom_formatter if custom_formatter else JSONLogFormatter

    if not ENABLE_JSON_LOGGING:
        _logger.warning(
            "JSON format is not enable, normal log will be in plain text but request logging still in JSON format! "
            "To enable set ENABLE_JSON_LOGGING env var to either one of following values: ['true', '1', 'y', 'yes']"
        )
    else:
        logging._defaultFormatter = formatter()

    # go to all the initialized logger and update it to use JSON formatter
    ENABLE_JSON_LOGGING_DEBUG and _logger.debug(
        "Update all existing logger to using JSONLogFormatter")
    existing_loggers = list(
        map(logging.getLogger, logging.Logger.manager.loggerDict))
    util.update_formatter_for_loggers(existing_loggers, formatter)
def config_root_logger():
    """
        You must call this if you are using root logger.
        Make all root logger' handlers produce JSON format
        & remove duplicate handlers for request instrumentation logging.
        Please made sure that you call this after you called "logging.basicConfig() or logging.getLogger('root')
    """
    global _default_formatter

    if len(logging.root.handlers) > 0:
        _logger.error(
            "No logging handlers found for root logger. Please made sure that you call this after you called "
            "logging.basicConfig() or logging.getLogger('root')")

    if ENABLE_JSON_LOGGING:
        ENABLE_JSON_LOGGING_DEBUG and _logger.debug(
            "Update root logger to using JSONLogFormatter")

        util.update_formatter_for_loggers([logging.root], _default_formatter)