예제 #1
0
def django_sending_elasticapm_client(request, validating_httpserver):
    validating_httpserver.serve_content(
        code=202, content="", headers={"Location": "http://example.com/foo"})
    client_config = getattr(request, "param", {})
    client_config.setdefault("server_url", validating_httpserver.url)
    client_config.setdefault("service_name", "app")
    client_config.setdefault("secret_token", "secret")
    client_config.setdefault("transport_class",
                             "elasticapm.transport.http.Transport")
    client_config.setdefault("span_frames_min_duration", -1)
    app = apps.get_app_config("elasticapm.contrib.django")
    old_client = app.client
    client = DjangoClient(**client_config)
    register_handlers(client)
    instrument(client)
    app.client = client
    client.httpserver = validating_httpserver
    yield client
    client.close()

    app.client = old_client

    if old_client:
        register_handlers(old_client)
        instrument(old_client)
def django_sending_elasticapm_client(request, validating_httpserver):
    validating_httpserver.serve_content(
        code=202, content='', headers={'Location': 'http://example.com/foo'})
    client_config = getattr(request, 'param', {})
    client_config.setdefault('server_url', validating_httpserver.url)
    client_config.setdefault('service_name', 'app')
    client_config.setdefault('secret_token', 'secret')
    client_config.setdefault('transport_class',
                             'elasticapm.transport.http.Transport')
    client_config.setdefault('span_frames_min_duration_ms', -1)
    app = apps.get_app_config('elasticapm.contrib.django')
    old_client = app.client
    client = DjangoClient(**client_config)
    register_handlers(client)
    instrument(client)
    app.client = client
    client.httpserver = validating_httpserver
    yield client
    client.close()

    app.client = old_client

    if old_client:
        register_handlers(old_client)
        instrument(old_client)
    def handle_test(self, command, **options):
        """Send a test error to APM Server"""
        config = {}
        # can't be async for testing
        config['async_mode'] = False
        for key in ('service_name', 'secret_token'):
            if options.get(key):
                config[key] = options[key]
        client = DjangoClient(**config)
        client.error_logger = ColoredLogger(self.stderr)
        client.logger = ColoredLogger(self.stderr)
        client.state.logger = client.logger
        client.state.error_logger = client.error_logger
        self.write(
            "Trying to send a test error to APM Server using these settings:\n\n"
            "SERVICE_NAME:\t%s\n"
            "SECRET_TOKEN:\t%s\n"
            "SERVER:\t\t%s\n\n" % (
                client.config.service_name,
                client.config.secret_token,
                client.config.server_url,
            ))

        try:
            raise TestException('Hi there!')
        except TestException:
            client.capture_exception()
            if not client.error_logger.errors:
                self.write(
                    'Success! We tracked the error successfully! You should be'
                    ' able to see it in a few seconds at the above URL')
        finally:
            client.close()
예제 #4
0
    def handle_test(self, command, **options):
        """Send a test error to APM Server"""
        # can't be async for testing
        config = {"async_mode": False}
        for key in ("service_name", "secret_token"):
            if options.get(key):
                config[key] = options[key]
        client = DjangoClient(**config)
        client.error_logger = ColoredLogger(self.stderr)
        client.logger = ColoredLogger(self.stderr)
        self.write(
            "Trying to send a test error to APM Server using these settings:\n\n"
            "SERVICE_NAME:\t%s\n"
            "SECRET_TOKEN:\t%s\n"
            "SERVER:\t\t%s\n\n" %
            (client.config.service_name, client.config.secret_token,
             client.config.server_url))

        try:
            raise TestException("Hi there!")
        except TestException:
            client.capture_exception()
            if not client.error_logger.errors:
                self.write(
                    "Success! We tracked the error successfully! \n"
                    "You should see it in the APM app in Kibana momentarily. \n"
                    'Look for "TestException: Hi there!" in the Errors tab of the %s app'
                    % client.config.service_name)
        finally:
            client.close()
예제 #5
0
    def handle_test(self, command, **options):
        """Send a test error to APM Server"""

        # can't be async for testing

        class LogCaptureHandler(logging.Handler):
            def __init__(self, level=logging.NOTSET):
                self.logs = []
                super(LogCaptureHandler, self).__init__(level)

            def handle(self, record):
                self.logs.append(record)

        handler = LogCaptureHandler()
        logger = logging.getLogger("elasticapm.transport")
        logger.addHandler(handler)

        config = {"async_mode": False}
        for key in ("service_name", "secret_token"):
            if options.get(key):
                config[key] = options[key]
        client = DjangoClient(**config)
        client.error_logger = ColoredLogger(self.stderr)
        client.logger = ColoredLogger(self.stderr)
        self.write(
            "Trying to send a test error to APM Server using these settings:\n\n"
            "SERVICE_NAME:\t%s\n"
            "SECRET_TOKEN:\t%s\n"
            "SERVER:\t\t%s\n\n" %
            (client.config.service_name, client.config.secret_token,
             client.config.server_url))

        try:
            raise TestException("Hi there!")
        except TestException:
            client.capture_exception()
        client.close()
        if not handler.logs:
            self.write(
                "Success! We tracked the error successfully! \n"
                "You should see it in the APM app in Kibana momentarily. \n"
                'Look for "TestException: Hi there!" in the Errors tab of the %s app'
                % client.config.service_name)
        else:
            self.write(
                "Oops. That didn't work. The following error occured: \n\n",
                red)
            for entry in handler.logs:
                self.write(entry.getMessage(), red)
    def handle_check(self, command, **options):
        """Check your settings for common misconfigurations"""
        passed = True
        client = DjangoClient()
        # check if org/app and token are set:
        is_set = lambda x: x and x != 'None'
        values = [client.config.service_name, client.config.secret_token]
        if all(map(is_set, values)):
            self.write('Service name and secret token are set, good job!',
                       green)
        else:
            passed = False
            self.write('Configuration errors detected!', red, ending='\n\n')
            if not is_set(client.config.service_name):
                self.write("  * SERVICE_NAME not set! ", red, ending='\n')
            if not is_set(client.config.secret_token):
                self.write("  * SECRET_TOKEN not set!", red, ending='\n')
            self.write(CONFIG_EXAMPLE)
        self.write('')

        # check if we're disabled due to DEBUG:
        if settings.DEBUG:
            if getattr(settings, 'ELASTIC_APM', {}).get('DEBUG'):
                self.write(
                    'Note: even though you are running in DEBUG mode, we will '
                    'send data to the APM Server, because you set ELASTIC_APM["DEBUG"] to '
                    'True. You can disable ElasticAPM while in DEBUG mode like this'
                    '\n\n', yellow)
                self.write('   ELASTIC_APM = {\n'
                           '       "DEBUG": False,\n'
                           '       # your other ELASTIC_APM settings\n'
                           '   }')
            else:
                self.write(
                    'Looks like you\'re running in DEBUG mode. ElasticAPM will NOT '
                    'gather any data while DEBUG is set to True.\n\n',
                    red,
                )
                self.write(
                    'If you want to test ElasticAPM while DEBUG is set to True, you'
                    ' can force ElasticAPM to gather data by setting'
                    ' ELASTIC_APM["DEBUG"] to True, like this\n\n'
                    '   ELASTIC_APM = {\n'
                    '       "DEBUG": True,\n'
                    '       # your other ELASTIC_APM settings\n'
                    '   }')
                passed = False
        else:
            self.write('DEBUG mode is disabled! Looking good!', green)
        self.write('')

        # check if middleware is set, and if it is at the first position
        middleware_attr = 'MIDDLEWARE' if getattr(
            settings, 'MIDDLEWARE', None) is not None else 'MIDDLEWARE_CLASSES'
        middleware = list(getattr(settings, middleware_attr))
        try:
            pos = middleware.index(
                'elasticapm.contrib.django.middleware.TracingMiddleware')
            if pos == 0:
                self.write('Tracing middleware is configured! Awesome!', green)
            else:
                self.write(
                    'Tracing middleware is configured, but not at the first position\n',
                    yellow)
                self.write(
                    'ElasticAPM works best if you add it at the top of your %s setting'
                    % middleware_attr)
        except ValueError:
            self.write('Tracing middleware not configured!', red)
            self.write(
                '\n'
                'Add it to your %(name)s setting like this:\n\n'
                '    %(name)s = (\n'
                '        "elasticapm.contrib.django.middleware.TracingMiddleware",\n'
                '        # your other middleware classes\n'
                '    )\n' % {'name': middleware_attr})
        self.write('')
        if passed:
            self.write('Looks like everything should be ready!', green)
        else:
            self.write('Please fix the above errors.', red)
        self.write('')
        return passed
예제 #7
0
    def handle_check(self, command, **options):
        """Check your settings for common misconfigurations"""
        passed = True
        client = DjangoClient(metrics_interval="0ms")

        def is_set(x):
            return x and x != "None"

        # check if org/app is set:
        if is_set(client.config.service_name):
            self.write("Service name is set, good job!", green)
        else:
            passed = False
            self.write("Configuration errors detected!", red, ending="\n\n")
            self.write("  * SERVICE_NAME not set! ", red, ending="\n")
            self.write(CONFIG_EXAMPLE)

        # secret token is optional but recommended
        if not is_set(client.config.secret_token):
            self.write("  * optional SECRET_TOKEN not set",
                       yellow,
                       ending="\n")
        self.write("")

        server_url = client.config.server_url
        if server_url:
            parsed_url = urlparse.urlparse(server_url)
            if parsed_url.scheme.lower() in ("http", "https"):
                # parse netloc, making sure people did not supply basic auth
                if "@" in parsed_url.netloc:
                    credentials, _, path = parsed_url.netloc.rpartition("@")
                    passed = False
                    self.write("Configuration errors detected!",
                               red,
                               ending="\n\n")
                    if ":" in credentials:
                        self.write(
                            "  * SERVER_URL cannot contain authentication "
                            "credentials",
                            red,
                            ending="\n")
                    else:
                        self.write(
                            "  * SERVER_URL contains an unexpected at-sign!"
                            " This is usually used for basic authentication, "
                            "but the colon is left out",
                            red,
                            ending="\n",
                        )
                else:
                    self.write("SERVER_URL {0} looks fine".format(server_url),
                               green)
                # secret token in the clear not recommended
                if is_set(client.config.secret_token
                          ) and parsed_url.scheme.lower() == "http":
                    self.write(
                        "  * SECRET_TOKEN set but server not using https",
                        yellow,
                        ending="\n")
            else:
                self.write(
                    "  * SERVER_URL has scheme {0} and we require "
                    "http or https!".format(parsed_url.scheme),
                    red,
                    ending="\n",
                )
                passed = False
        else:
            self.write("Configuration errors detected!", red, ending="\n\n")
            self.write("  * SERVER_URL appears to be empty", red, ending="\n")
            passed = False
        self.write("")

        # check if we're disabled due to DEBUG:
        if settings.DEBUG:
            if getattr(settings, "ELASTIC_APM", {}).get("DEBUG"):
                self.write(
                    "Note: even though you are running in DEBUG mode, we will "
                    'send data to the APM Server, because you set ELASTIC_APM["DEBUG"] to '
                    "True. You can disable ElasticAPM while in DEBUG mode like this"
                    "\n\n",
                    yellow,
                )
                self.write("   ELASTIC_APM = {\n"
                           '       "DEBUG": False,\n'
                           "       # your other ELASTIC_APM settings\n"
                           "   }")
            else:
                self.write(
                    "Looks like you're running in DEBUG mode. ElasticAPM will NOT "
                    "gather any data while DEBUG is set to True.\n\n",
                    red,
                )
                self.write(
                    "If you want to test ElasticAPM while DEBUG is set to True, you"
                    " can force ElasticAPM to gather data by setting"
                    ' ELASTIC_APM["DEBUG"] to True, like this\n\n'
                    "   ELASTIC_APM = {\n"
                    '       "DEBUG": True,\n'
                    "       # your other ELASTIC_APM settings\n"
                    "   }")
                passed = False
        else:
            self.write("DEBUG mode is disabled! Looking good!", green)
        self.write("")

        # check if middleware is set, and if it is at the first position
        middleware_attr = "MIDDLEWARE" if getattr(
            settings, "MIDDLEWARE", None) is not None else "MIDDLEWARE_CLASSES"
        middleware = list(getattr(settings, middleware_attr))
        try:
            pos = middleware.index(
                "elasticapm.contrib.django.middleware.TracingMiddleware")
            if pos == 0:
                self.write("Tracing middleware is configured! Awesome!", green)
            else:
                self.write(
                    "Tracing middleware is configured, but not at the first position\n",
                    yellow)
                self.write(
                    "ElasticAPM works best if you add it at the top of your %s setting"
                    % middleware_attr)
        except ValueError:
            self.write("Tracing middleware not configured!", red)
            self.write(
                "\n"
                "Add it to your %(name)s setting like this:\n\n"
                "    %(name)s = (\n"
                '        "elasticapm.contrib.django.middleware.TracingMiddleware",\n'
                "        # your other middleware classes\n"
                "    )\n" % {"name": middleware_attr})
        self.write("")
        if passed:
            self.write("Looks like everything should be ready!", green)
        else:
            self.write("Please fix the above errors.", red)
        self.write("")
        client.close()
        return passed
예제 #8
0
    def handle_check(self, command, **options):
        """Check your settings for common misconfigurations"""
        passed = True
        client = DjangoClient()
        # check if org/app and token are set:
        is_set = lambda x: x and x != 'None'
        values = [client.config.service_name, client.config.secret_token]
        if all(map(is_set, values)):
            self.write('Service name and secret token are set, good job!',
                       green)
        else:
            passed = False
            self.write('Configuration errors detected!', red, ending='\n\n')
            if not is_set(client.config.service_name):
                self.write("  * SERVICE_NAME not set! ", red, ending='\n')
            if not is_set(client.config.secret_token):
                self.write("  * SECRET_TOKEN not set!", red, ending='\n')
            self.write(CONFIG_EXAMPLE)
        self.write('')

        server_url = client.config.server_url
        if server_url:
            parsed_url = urlparse.urlparse(server_url)
            if parsed_url.scheme.lower() in (
                    'http',
                    'https',
            ):
                # parse netloc, making sure people did not supply basic auth
                if '@' in parsed_url.netloc:
                    credentials, _, path = parsed_url.netloc.rpartition('@')
                    passed = False
                    self.write('Configuration errors detected!',
                               red,
                               ending='\n\n')
                    if ':' in credentials:
                        self.write(
                            '  * SERVER_URL cannot contain authentication '
                            'credentials',
                            red,
                            ending='\n')
                    else:
                        self.write(
                            '  * SERVER_URL contains an unexpected at-sign!'
                            ' This is usually used for basic authentication, '
                            'but the colon is left out',
                            red,
                            ending='\n')
                else:
                    self.write(
                        'SERVER_URL {0} looks fine'.format(server_url, ),
                        green)
            else:
                self.write('  * SERVER_URL has scheme {0} and we require '
                           'http or https!'.format(parsed_url.scheme, ),
                           red,
                           ending='\n')
                passed = False
        else:
            self.write('Configuration errors detected!', red, ending='\n\n')
            self.write("  * SERVER_URL appears to be empty", red, ending='\n')
            passed = False
        self.write('')

        # check if we're disabled due to DEBUG:
        if settings.DEBUG:
            if getattr(settings, 'ELASTIC_APM', {}).get('DEBUG'):
                self.write(
                    'Note: even though you are running in DEBUG mode, we will '
                    'send data to the APM Server, because you set ELASTIC_APM["DEBUG"] to '
                    'True. You can disable ElasticAPM while in DEBUG mode like this'
                    '\n\n', yellow)
                self.write('   ELASTIC_APM = {\n'
                           '       "DEBUG": False,\n'
                           '       # your other ELASTIC_APM settings\n'
                           '   }')
            else:
                self.write(
                    'Looks like you\'re running in DEBUG mode. ElasticAPM will NOT '
                    'gather any data while DEBUG is set to True.\n\n',
                    red,
                )
                self.write(
                    'If you want to test ElasticAPM while DEBUG is set to True, you'
                    ' can force ElasticAPM to gather data by setting'
                    ' ELASTIC_APM["DEBUG"] to True, like this\n\n'
                    '   ELASTIC_APM = {\n'
                    '       "DEBUG": True,\n'
                    '       # your other ELASTIC_APM settings\n'
                    '   }')
                passed = False
        else:
            self.write('DEBUG mode is disabled! Looking good!', green)
        self.write('')

        # check if middleware is set, and if it is at the first position
        middleware_attr = 'MIDDLEWARE' if getattr(
            settings, 'MIDDLEWARE', None) is not None else 'MIDDLEWARE_CLASSES'
        middleware = list(getattr(settings, middleware_attr))
        try:
            pos = middleware.index(
                'elasticapm.contrib.django.middleware.TracingMiddleware')
            if pos == 0:
                self.write('Tracing middleware is configured! Awesome!', green)
            else:
                self.write(
                    'Tracing middleware is configured, but not at the first position\n',
                    yellow)
                self.write(
                    'ElasticAPM works best if you add it at the top of your %s setting'
                    % middleware_attr)
        except ValueError:
            self.write('Tracing middleware not configured!', red)
            self.write(
                '\n'
                'Add it to your %(name)s setting like this:\n\n'
                '    %(name)s = (\n'
                '        "elasticapm.contrib.django.middleware.TracingMiddleware",\n'
                '        # your other middleware classes\n'
                '    )\n' % {'name': middleware_attr})
        self.write('')
        if passed:
            self.write('Looks like everything should be ready!', green)
        else:
            self.write('Please fix the above errors.', red)
        self.write('')
        return passed