We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`check` cmd output differs from documentation. 
Running `python manage.py elasticapm check` returns an error if no `Secret_Token` is configured. Documentation states that configuration is optional. 


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `elasticapm/contrib/django/management/commands/elasticapm.py`
Content:
```
1 from __future__ import absolute_import
2 
3 import sys
4 
5 from django.conf import settings
6 from django.core.management.base import BaseCommand
7 from django.core.management.color import color_style
8 from django.utils import termcolors
9 
10 from elasticapm.contrib.django.client import DjangoClient
11 from elasticapm.utils.compat import urlparse
12 
13 try:
14     from django.core.management.base import OutputWrapper
15 except ImportError:
16     OutputWrapper = None
17 
18 
19 blue = termcolors.make_style(opts=('bold',), fg='blue')
20 cyan = termcolors.make_style(opts=('bold',), fg='cyan')
21 green = termcolors.make_style(fg='green')
22 magenta = termcolors.make_style(opts=('bold',), fg='magenta')
23 red = termcolors.make_style(opts=('bold',), fg='red')
24 white = termcolors.make_style(opts=('bold',), fg='white')
25 yellow = termcolors.make_style(opts=('bold',), fg='yellow')
26 
27 
28 class TestException(Exception):
29     pass
30 
31 
32 class ColoredLogger(object):
33     def __init__(self, stream):
34         self.stream = stream
35         self.errors = []
36         self.color = color_style()
37 
38     def log(self, level, *args, **kwargs):
39         style = kwargs.pop('style', self.color.NOTICE)
40         msg = ' '.join((level.upper(), args[0] % args[1:], '\n'))
41         if OutputWrapper is None:
42             self.stream.write(msg)
43         else:
44             self.stream.write(msg, style_func=style)
45 
46     def error(self, *args, **kwargs):
47         kwargs['style'] = red
48         self.log('error', *args, **kwargs)
49         self.errors.append((args,))
50 
51     def warning(self, *args, **kwargs):
52         kwargs['style'] = yellow
53         self.log('warning', *args, **kwargs)
54 
55     def info(self, *args, **kwargs):
56         kwargs['style'] = green
57         self.log('info', *args, **kwargs)
58 
59 
60 CONFIG_EXAMPLE = """
61 
62 You can set it in your settings file:
63 
64     ELASTIC_APM = {
65         'SERVICE_NAME': '<YOUR-SERVICE-NAME>',
66         'SECRET_TOKEN': '<YOUR-SECRET-TOKEN>',
67     }
68 
69 or with environment variables:
70 
71     $ export ELASTIC_APM_SERVICE_NAME="<YOUR-SERVICE-NAME>"
72     $ export ELASTIC_APM_SECRET_TOKEN="<YOUR-SECRET-TOKEN>"
73     $ python manage.py elasticapm check
74 
75 """
76 
77 
78 class Command(BaseCommand):
79     arguments = (
80         (('-s', '--service-name'),
81          {'default': None, 'dest': 'service_name', 'help': 'Specifies the service name.'}),
82 
83         (('-t', '--token'),
84          {'default': None, 'dest': 'secret_token', 'help': 'Specifies the secret token.'})
85     )
86 
87     args = 'test check'
88 
89     def add_arguments(self, parser):
90         parser.add_argument('subcommand')
91         for args, kwargs in self.arguments:
92             parser.add_argument(*args, **kwargs)
93 
94     def handle(self, *args, **options):
95         if 'subcommand' in options:
96             subcommand = options['subcommand']
97         else:
98             return self.handle_command_not_found('No command specified.')
99         if subcommand not in self.dispatch:
100             self.handle_command_not_found('No such command "%s".' % subcommand)
101         else:
102             self.dispatch.get(
103                 subcommand,
104                 self.handle_command_not_found
105             )(self, subcommand, **options)
106 
107     def handle_test(self, command, **options):
108         """Send a test error to APM Server"""
109         # can't be async for testing
110         config = {'async_mode': False, }
111         for key in ('service_name', 'secret_token'):
112             if options.get(key):
113                 config[key] = options[key]
114         client = DjangoClient(**config)
115         client.error_logger = ColoredLogger(self.stderr)
116         client.logger = ColoredLogger(self.stderr)
117         client.state.logger = client.logger
118         client.state.error_logger = client.error_logger
119         self.write(
120             "Trying to send a test error to APM Server using these settings:\n\n"
121             "SERVICE_NAME:\t%s\n"
122             "SECRET_TOKEN:\t%s\n"
123             "SERVER:\t\t%s\n\n" % (
124                 client.config.service_name,
125                 client.config.secret_token,
126                 client.config.server_url,
127             )
128         )
129 
130         try:
131             raise TestException('Hi there!')
132         except TestException:
133             client.capture_exception()
134             if not client.error_logger.errors:
135                 self.write(
136                     'Success! We tracked the error successfully! You should be'
137                     ' able to see it in a few seconds at the above URL'
138                 )
139         finally:
140             client.close()
141 
142     def handle_check(self, command, **options):
143         """Check your settings for common misconfigurations"""
144         passed = True
145         client = DjangoClient()
146         # check if org/app and token are set:
147         is_set = lambda x: x and x != 'None'
148         values = [client.config.service_name, client.config.secret_token]
149         if all(map(is_set, values)):
150             self.write(
151                 'Service name and secret token are set, good job!',
152                 green
153             )
154         else:
155             passed = False
156             self.write(
157                 'Configuration errors detected!', red, ending='\n\n'
158             )
159             if not is_set(client.config.service_name):
160                 self.write("  * SERVICE_NAME not set! ", red, ending='\n')
161             if not is_set(client.config.secret_token):
162                 self.write("  * SECRET_TOKEN not set!", red, ending='\n')
163             self.write(CONFIG_EXAMPLE)
164         self.write('')
165 
166         server_url = client.config.server_url
167         if server_url:
168             parsed_url = urlparse.urlparse(server_url)
169             if parsed_url.scheme.lower() in ('http', 'https', ):
170                 # parse netloc, making sure people did not supply basic auth
171                 if '@' in parsed_url.netloc:
172                     credentials, _, path = parsed_url.netloc.rpartition('@')
173                     passed = False
174                     self.write(
175                         'Configuration errors detected!', red, ending='\n\n'
176                     )
177                     if ':' in credentials:
178                         self.write('  * SERVER_URL cannot contain authentication '
179                                    'credentials', red, ending='\n')
180                     else:
181                         self.write('  * SERVER_URL contains an unexpected at-sign!'
182                                    ' This is usually used for basic authentication, '
183                                    'but the colon is left out', red, ending='\n')
184                 else:
185                     self.write('SERVER_URL {0} looks fine'.format(server_url, ), green)
186             else:
187                 self.write('  * SERVER_URL has scheme {0} and we require '
188                            'http or https!'.format(parsed_url.scheme, ), red, ending='\n')
189                 passed = False
190         else:
191             self.write(
192                 'Configuration errors detected!', red, ending='\n\n'
193             )
194             self.write("  * SERVER_URL appears to be empty", red, ending='\n')
195             passed = False
196         self.write('')
197 
198         # check if we're disabled due to DEBUG:
199         if settings.DEBUG:
200             if getattr(settings, 'ELASTIC_APM', {}).get('DEBUG'):
201                 self.write(
202                     'Note: even though you are running in DEBUG mode, we will '
203                     'send data to the APM Server, because you set ELASTIC_APM["DEBUG"] to '
204                     'True. You can disable ElasticAPM while in DEBUG mode like this'
205                     '\n\n',
206                     yellow
207                 )
208                 self.write(
209                     '   ELASTIC_APM = {\n'
210                     '       "DEBUG": False,\n'
211                     '       # your other ELASTIC_APM settings\n'
212                     '   }'
213 
214                 )
215             else:
216                 self.write(
217                     'Looks like you\'re running in DEBUG mode. ElasticAPM will NOT '
218                     'gather any data while DEBUG is set to True.\n\n',
219                     red,
220                 )
221                 self.write(
222                     'If you want to test ElasticAPM while DEBUG is set to True, you'
223                     ' can force ElasticAPM to gather data by setting'
224                     ' ELASTIC_APM["DEBUG"] to True, like this\n\n'
225                     '   ELASTIC_APM = {\n'
226                     '       "DEBUG": True,\n'
227                     '       # your other ELASTIC_APM settings\n'
228                     '   }'
229                 )
230                 passed = False
231         else:
232             self.write(
233                 'DEBUG mode is disabled! Looking good!',
234                 green
235             )
236         self.write('')
237 
238         # check if middleware is set, and if it is at the first position
239         middleware_attr = 'MIDDLEWARE' if getattr(settings, 'MIDDLEWARE', None) is not None else 'MIDDLEWARE_CLASSES'
240         middleware = list(getattr(settings, middleware_attr))
241         try:
242             pos = middleware.index('elasticapm.contrib.django.middleware.TracingMiddleware')
243             if pos == 0:
244                 self.write('Tracing middleware is configured! Awesome!', green)
245             else:
246                 self.write('Tracing middleware is configured, but not at the first position\n', yellow)
247                 self.write('ElasticAPM works best if you add it at the top of your %s setting' % middleware_attr)
248         except ValueError:
249             self.write('Tracing middleware not configured!', red)
250             self.write(
251                 '\n'
252                 'Add it to your %(name)s setting like this:\n\n'
253                 '    %(name)s = (\n'
254                 '        "elasticapm.contrib.django.middleware.TracingMiddleware",\n'
255                 '        # your other middleware classes\n'
256                 '    )\n' % {'name': middleware_attr}
257             )
258         self.write('')
259         if passed:
260             self.write('Looks like everything should be ready!', green)
261         else:
262             self.write(
263                 'Please fix the above errors.',
264                 red
265             )
266         self.write('')
267         return passed
268 
269     def handle_command_not_found(self, message):
270         self.write(message, red, ending='')
271         self.write(
272             ' Please use one of the following commands:\n\n',
273             red
274         )
275         self.write(
276             ''.join(
277                 ' * %s\t%s\n' % (k.ljust(8), v.__doc__)
278                 for k, v in self.dispatch.items()
279             )
280         )
281         self.write('\n')
282         argv = self._get_argv()
283         self.write(
284             'Usage:\n\t%s elasticapm <command>' % (
285                 ' '.join(argv[:argv.index('elasticapm')])
286             )
287         )
288 
289     def write(self, msg, style_func=None, ending=None, stream=None):
290         """
291         wrapper around self.stdout/stderr to ensure Django 1.4 compatibility
292         """
293         if stream is None:
294             stream = self.stdout
295         if OutputWrapper is None:
296             ending = '\n' if ending is None else ending
297             msg += ending
298             stream.write(msg)
299         else:
300             stream.write(msg, style_func=style_func, ending=ending)
301 
302     def _get_argv(self):
303         """allow cleaner mocking of sys.argv"""
304         return sys.argv
305 
306     dispatch = {
307         'test': handle_test,
308         'check': handle_check,
309     }
310
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/elasticapm/contrib/django/management/commands/elasticapm.py b/elasticapm/contrib/django/management/commands/elasticapm.py
--- a/elasticapm/contrib/django/management/commands/elasticapm.py
+++ b/elasticapm/contrib/django/management/commands/elasticapm.py
@@ -143,12 +143,14 @@
         """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)):
+
+        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 and secret token are set, good job!',
+                'Service name is set, good job!',
                 green
             )
         else:
@@ -156,11 +158,12 @@
             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("  * 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
@@ -183,6 +186,9 @@
                                    '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')

{"golden_diff": "diff --git a/elasticapm/contrib/django/management/commands/elasticapm.py b/elasticapm/contrib/django/management/commands/elasticapm.py\n--- a/elasticapm/contrib/django/management/commands/elasticapm.py\n+++ b/elasticapm/contrib/django/management/commands/elasticapm.py\n@@ -143,12 +143,14 @@\n         \"\"\"Check your settings for common misconfigurations\"\"\"\n         passed = True\n         client = DjangoClient()\n-        # check if org/app and token are set:\n-        is_set = lambda x: x and x != 'None'\n-        values = [client.config.service_name, client.config.secret_token]\n-        if all(map(is_set, values)):\n+\n+        def is_set(x):\n+            return x and x != 'None'\n+\n+        # check if org/app is set:\n+        if is_set(client.config.service_name):\n             self.write(\n-                'Service name and secret token are set, good job!',\n+                'Service name is set, good job!',\n                 green\n             )\n         else:\n@@ -156,11 +158,12 @@\n             self.write(\n                 'Configuration errors detected!', red, ending='\\n\\n'\n             )\n-            if not is_set(client.config.service_name):\n-                self.write(\"  * SERVICE_NAME not set! \", red, ending='\\n')\n-            if not is_set(client.config.secret_token):\n-                self.write(\"  * SECRET_TOKEN not set!\", red, ending='\\n')\n+            self.write(\"  * SERVICE_NAME not set! \", red, ending='\\n')\n             self.write(CONFIG_EXAMPLE)\n+\n+        # secret token is optional but recommended\n+        if not is_set(client.config.secret_token):\n+            self.write(\"  * optional SECRET_TOKEN not set\", yellow, ending='\\n')\n         self.write('')\n \n         server_url = client.config.server_url\n@@ -183,6 +186,9 @@\n                                    'but the colon is left out', red, ending='\\n')\n                 else:\n                     self.write('SERVER_URL {0} looks fine'.format(server_url, ), green)\n+                # secret token in the clear not recommended\n+                if is_set(client.config.secret_token) and parsed_url.scheme.lower() == 'http':\n+                    self.write(\"  * SECRET_TOKEN set but server not using https\", yellow, ending='\\n')\n             else:\n                 self.write('  * SERVER_URL has scheme {0} and we require '\n                            'http or https!'.format(parsed_url.scheme, ), red, ending='\\n')\n", "issue": "`check` cmd output differs from documentation. \nRunning `python manage.py elasticapm check` returns an error if no `Secret_Token` is configured. Documentation states that configuration is optional. \r\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport sys\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.core.management.color import color_style\nfrom django.utils import termcolors\n\nfrom elasticapm.contrib.django.client import DjangoClient\nfrom elasticapm.utils.compat import urlparse\n\ntry:\n    from django.core.management.base import OutputWrapper\nexcept ImportError:\n    OutputWrapper = None\n\n\nblue = termcolors.make_style(opts=('bold',), fg='blue')\ncyan = termcolors.make_style(opts=('bold',), fg='cyan')\ngreen = termcolors.make_style(fg='green')\nmagenta = termcolors.make_style(opts=('bold',), fg='magenta')\nred = termcolors.make_style(opts=('bold',), fg='red')\nwhite = termcolors.make_style(opts=('bold',), fg='white')\nyellow = termcolors.make_style(opts=('bold',), fg='yellow')\n\n\nclass TestException(Exception):\n    pass\n\n\nclass ColoredLogger(object):\n    def __init__(self, stream):\n        self.stream = stream\n        self.errors = []\n        self.color = color_style()\n\n    def log(self, level, *args, **kwargs):\n        style = kwargs.pop('style', self.color.NOTICE)\n        msg = ' '.join((level.upper(), args[0] % args[1:], '\\n'))\n        if OutputWrapper is None:\n            self.stream.write(msg)\n        else:\n            self.stream.write(msg, style_func=style)\n\n    def error(self, *args, **kwargs):\n        kwargs['style'] = red\n        self.log('error', *args, **kwargs)\n        self.errors.append((args,))\n\n    def warning(self, *args, **kwargs):\n        kwargs['style'] = yellow\n        self.log('warning', *args, **kwargs)\n\n    def info(self, *args, **kwargs):\n        kwargs['style'] = green\n        self.log('info', *args, **kwargs)\n\n\nCONFIG_EXAMPLE = \"\"\"\n\nYou can set it in your settings file:\n\n    ELASTIC_APM = {\n        'SERVICE_NAME': '<YOUR-SERVICE-NAME>',\n        'SECRET_TOKEN': '<YOUR-SECRET-TOKEN>',\n    }\n\nor with environment variables:\n\n    $ export ELASTIC_APM_SERVICE_NAME=\"<YOUR-SERVICE-NAME>\"\n    $ export ELASTIC_APM_SECRET_TOKEN=\"<YOUR-SECRET-TOKEN>\"\n    $ python manage.py elasticapm check\n\n\"\"\"\n\n\nclass Command(BaseCommand):\n    arguments = (\n        (('-s', '--service-name'),\n         {'default': None, 'dest': 'service_name', 'help': 'Specifies the service name.'}),\n\n        (('-t', '--token'),\n         {'default': None, 'dest': 'secret_token', 'help': 'Specifies the secret token.'})\n    )\n\n    args = 'test check'\n\n    def add_arguments(self, parser):\n        parser.add_argument('subcommand')\n        for args, kwargs in self.arguments:\n            parser.add_argument(*args, **kwargs)\n\n    def handle(self, *args, **options):\n        if 'subcommand' in options:\n            subcommand = options['subcommand']\n        else:\n            return self.handle_command_not_found('No command specified.')\n        if subcommand not in self.dispatch:\n            self.handle_command_not_found('No such command \"%s\".' % subcommand)\n        else:\n            self.dispatch.get(\n                subcommand,\n                self.handle_command_not_found\n            )(self, subcommand, **options)\n\n    def handle_test(self, command, **options):\n        \"\"\"Send a test error to APM Server\"\"\"\n        # can't be async for testing\n        config = {'async_mode': False, }\n        for key in ('service_name', 'secret_token'):\n            if options.get(key):\n                config[key] = options[key]\n        client = DjangoClient(**config)\n        client.error_logger = ColoredLogger(self.stderr)\n        client.logger = ColoredLogger(self.stderr)\n        client.state.logger = client.logger\n        client.state.error_logger = client.error_logger\n        self.write(\n            \"Trying to send a test error to APM Server using these settings:\\n\\n\"\n            \"SERVICE_NAME:\\t%s\\n\"\n            \"SECRET_TOKEN:\\t%s\\n\"\n            \"SERVER:\\t\\t%s\\n\\n\" % (\n                client.config.service_name,\n                client.config.secret_token,\n                client.config.server_url,\n            )\n        )\n\n        try:\n            raise TestException('Hi there!')\n        except TestException:\n            client.capture_exception()\n            if not client.error_logger.errors:\n                self.write(\n                    'Success! We tracked the error successfully! You should be'\n                    ' able to see it in a few seconds at the above URL'\n                )\n        finally:\n            client.close()\n\n    def handle_check(self, command, **options):\n        \"\"\"Check your settings for common misconfigurations\"\"\"\n        passed = True\n        client = DjangoClient()\n        # check if org/app and token are set:\n        is_set = lambda x: x and x != 'None'\n        values = [client.config.service_name, client.config.secret_token]\n        if all(map(is_set, values)):\n            self.write(\n                'Service name and secret token are set, good job!',\n                green\n            )\n        else:\n            passed = False\n            self.write(\n                'Configuration errors detected!', red, ending='\\n\\n'\n            )\n            if not is_set(client.config.service_name):\n                self.write(\"  * SERVICE_NAME not set! \", red, ending='\\n')\n            if not is_set(client.config.secret_token):\n                self.write(\"  * SECRET_TOKEN not set!\", red, ending='\\n')\n            self.write(CONFIG_EXAMPLE)\n        self.write('')\n\n        server_url = client.config.server_url\n        if server_url:\n            parsed_url = urlparse.urlparse(server_url)\n            if parsed_url.scheme.lower() in ('http', 'https', ):\n                # parse netloc, making sure people did not supply basic auth\n                if '@' in parsed_url.netloc:\n                    credentials, _, path = parsed_url.netloc.rpartition('@')\n                    passed = False\n                    self.write(\n                        'Configuration errors detected!', red, ending='\\n\\n'\n                    )\n                    if ':' in credentials:\n                        self.write('  * SERVER_URL cannot contain authentication '\n                                   'credentials', red, ending='\\n')\n                    else:\n                        self.write('  * SERVER_URL contains an unexpected at-sign!'\n                                   ' This is usually used for basic authentication, '\n                                   'but the colon is left out', red, ending='\\n')\n                else:\n                    self.write('SERVER_URL {0} looks fine'.format(server_url, ), green)\n            else:\n                self.write('  * SERVER_URL has scheme {0} and we require '\n                           'http or https!'.format(parsed_url.scheme, ), red, ending='\\n')\n                passed = False\n        else:\n            self.write(\n                'Configuration errors detected!', red, ending='\\n\\n'\n            )\n            self.write(\"  * SERVER_URL appears to be empty\", red, ending='\\n')\n            passed = False\n        self.write('')\n\n        # check if we're disabled due to DEBUG:\n        if settings.DEBUG:\n            if getattr(settings, 'ELASTIC_APM', {}).get('DEBUG'):\n                self.write(\n                    'Note: even though you are running in DEBUG mode, we will '\n                    'send data to the APM Server, because you set ELASTIC_APM[\"DEBUG\"] to '\n                    'True. You can disable ElasticAPM while in DEBUG mode like this'\n                    '\\n\\n',\n                    yellow\n                )\n                self.write(\n                    '   ELASTIC_APM = {\\n'\n                    '       \"DEBUG\": False,\\n'\n                    '       # your other ELASTIC_APM settings\\n'\n                    '   }'\n\n                )\n            else:\n                self.write(\n                    'Looks like you\\'re running in DEBUG mode. ElasticAPM will NOT '\n                    'gather any data while DEBUG is set to True.\\n\\n',\n                    red,\n                )\n                self.write(\n                    'If you want to test ElasticAPM while DEBUG is set to True, you'\n                    ' can force ElasticAPM to gather data by setting'\n                    ' ELASTIC_APM[\"DEBUG\"] to True, like this\\n\\n'\n                    '   ELASTIC_APM = {\\n'\n                    '       \"DEBUG\": True,\\n'\n                    '       # your other ELASTIC_APM settings\\n'\n                    '   }'\n                )\n                passed = False\n        else:\n            self.write(\n                'DEBUG mode is disabled! Looking good!',\n                green\n            )\n        self.write('')\n\n        # check if middleware is set, and if it is at the first position\n        middleware_attr = 'MIDDLEWARE' if getattr(settings, 'MIDDLEWARE', None) is not None else 'MIDDLEWARE_CLASSES'\n        middleware = list(getattr(settings, middleware_attr))\n        try:\n            pos = middleware.index('elasticapm.contrib.django.middleware.TracingMiddleware')\n            if pos == 0:\n                self.write('Tracing middleware is configured! Awesome!', green)\n            else:\n                self.write('Tracing middleware is configured, but not at the first position\\n', yellow)\n                self.write('ElasticAPM works best if you add it at the top of your %s setting' % middleware_attr)\n        except ValueError:\n            self.write('Tracing middleware not configured!', red)\n            self.write(\n                '\\n'\n                'Add it to your %(name)s setting like this:\\n\\n'\n                '    %(name)s = (\\n'\n                '        \"elasticapm.contrib.django.middleware.TracingMiddleware\",\\n'\n                '        # your other middleware classes\\n'\n                '    )\\n' % {'name': middleware_attr}\n            )\n        self.write('')\n        if passed:\n            self.write('Looks like everything should be ready!', green)\n        else:\n            self.write(\n                'Please fix the above errors.',\n                red\n            )\n        self.write('')\n        return passed\n\n    def handle_command_not_found(self, message):\n        self.write(message, red, ending='')\n        self.write(\n            ' Please use one of the following commands:\\n\\n',\n            red\n        )\n        self.write(\n            ''.join(\n                ' * %s\\t%s\\n' % (k.ljust(8), v.__doc__)\n                for k, v in self.dispatch.items()\n            )\n        )\n        self.write('\\n')\n        argv = self._get_argv()\n        self.write(\n            'Usage:\\n\\t%s elasticapm <command>' % (\n                ' '.join(argv[:argv.index('elasticapm')])\n            )\n        )\n\n    def write(self, msg, style_func=None, ending=None, stream=None):\n        \"\"\"\n        wrapper around self.stdout/stderr to ensure Django 1.4 compatibility\n        \"\"\"\n        if stream is None:\n            stream = self.stdout\n        if OutputWrapper is None:\n            ending = '\\n' if ending is None else ending\n            msg += ending\n            stream.write(msg)\n        else:\n            stream.write(msg, style_func=style_func, ending=ending)\n\n    def _get_argv(self):\n        \"\"\"allow cleaner mocking of sys.argv\"\"\"\n        return sys.argv\n\n    dispatch = {\n        'test': handle_test,\n        'check': handle_check,\n    }\n", "path": "elasticapm/contrib/django/management/commands/elasticapm.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport sys\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.core.management.color import color_style\nfrom django.utils import termcolors\n\nfrom elasticapm.contrib.django.client import DjangoClient\nfrom elasticapm.utils.compat import urlparse\n\ntry:\n    from django.core.management.base import OutputWrapper\nexcept ImportError:\n    OutputWrapper = None\n\n\nblue = termcolors.make_style(opts=('bold',), fg='blue')\ncyan = termcolors.make_style(opts=('bold',), fg='cyan')\ngreen = termcolors.make_style(fg='green')\nmagenta = termcolors.make_style(opts=('bold',), fg='magenta')\nred = termcolors.make_style(opts=('bold',), fg='red')\nwhite = termcolors.make_style(opts=('bold',), fg='white')\nyellow = termcolors.make_style(opts=('bold',), fg='yellow')\n\n\nclass TestException(Exception):\n    pass\n\n\nclass ColoredLogger(object):\n    def __init__(self, stream):\n        self.stream = stream\n        self.errors = []\n        self.color = color_style()\n\n    def log(self, level, *args, **kwargs):\n        style = kwargs.pop('style', self.color.NOTICE)\n        msg = ' '.join((level.upper(), args[0] % args[1:], '\\n'))\n        if OutputWrapper is None:\n            self.stream.write(msg)\n        else:\n            self.stream.write(msg, style_func=style)\n\n    def error(self, *args, **kwargs):\n        kwargs['style'] = red\n        self.log('error', *args, **kwargs)\n        self.errors.append((args,))\n\n    def warning(self, *args, **kwargs):\n        kwargs['style'] = yellow\n        self.log('warning', *args, **kwargs)\n\n    def info(self, *args, **kwargs):\n        kwargs['style'] = green\n        self.log('info', *args, **kwargs)\n\n\nCONFIG_EXAMPLE = \"\"\"\n\nYou can set it in your settings file:\n\n    ELASTIC_APM = {\n        'SERVICE_NAME': '<YOUR-SERVICE-NAME>',\n        'SECRET_TOKEN': '<YOUR-SECRET-TOKEN>',\n    }\n\nor with environment variables:\n\n    $ export ELASTIC_APM_SERVICE_NAME=\"<YOUR-SERVICE-NAME>\"\n    $ export ELASTIC_APM_SECRET_TOKEN=\"<YOUR-SECRET-TOKEN>\"\n    $ python manage.py elasticapm check\n\n\"\"\"\n\n\nclass Command(BaseCommand):\n    arguments = (\n        (('-s', '--service-name'),\n         {'default': None, 'dest': 'service_name', 'help': 'Specifies the service name.'}),\n\n        (('-t', '--token'),\n         {'default': None, 'dest': 'secret_token', 'help': 'Specifies the secret token.'})\n    )\n\n    args = 'test check'\n\n    def add_arguments(self, parser):\n        parser.add_argument('subcommand')\n        for args, kwargs in self.arguments:\n            parser.add_argument(*args, **kwargs)\n\n    def handle(self, *args, **options):\n        if 'subcommand' in options:\n            subcommand = options['subcommand']\n        else:\n            return self.handle_command_not_found('No command specified.')\n        if subcommand not in self.dispatch:\n            self.handle_command_not_found('No such command \"%s\".' % subcommand)\n        else:\n            self.dispatch.get(\n                subcommand,\n                self.handle_command_not_found\n            )(self, subcommand, **options)\n\n    def handle_test(self, command, **options):\n        \"\"\"Send a test error to APM Server\"\"\"\n        # can't be async for testing\n        config = {'async_mode': False, }\n        for key in ('service_name', 'secret_token'):\n            if options.get(key):\n                config[key] = options[key]\n        client = DjangoClient(**config)\n        client.error_logger = ColoredLogger(self.stderr)\n        client.logger = ColoredLogger(self.stderr)\n        client.state.logger = client.logger\n        client.state.error_logger = client.error_logger\n        self.write(\n            \"Trying to send a test error to APM Server using these settings:\\n\\n\"\n            \"SERVICE_NAME:\\t%s\\n\"\n            \"SECRET_TOKEN:\\t%s\\n\"\n            \"SERVER:\\t\\t%s\\n\\n\" % (\n                client.config.service_name,\n                client.config.secret_token,\n                client.config.server_url,\n            )\n        )\n\n        try:\n            raise TestException('Hi there!')\n        except TestException:\n            client.capture_exception()\n            if not client.error_logger.errors:\n                self.write(\n                    'Success! We tracked the error successfully! You should be'\n                    ' able to see it in a few seconds at the above URL'\n                )\n        finally:\n            client.close()\n\n    def handle_check(self, command, **options):\n        \"\"\"Check your settings for common misconfigurations\"\"\"\n        passed = True\n        client = DjangoClient()\n\n        def is_set(x):\n            return x and x != 'None'\n\n        # check if org/app is set:\n        if is_set(client.config.service_name):\n            self.write(\n                'Service name is set, good job!',\n                green\n            )\n        else:\n            passed = False\n            self.write(\n                'Configuration errors detected!', red, ending='\\n\\n'\n            )\n            self.write(\"  * SERVICE_NAME not set! \", red, ending='\\n')\n            self.write(CONFIG_EXAMPLE)\n\n        # secret token is optional but recommended\n        if not is_set(client.config.secret_token):\n            self.write(\"  * optional SECRET_TOKEN not set\", yellow, ending='\\n')\n        self.write('')\n\n        server_url = client.config.server_url\n        if server_url:\n            parsed_url = urlparse.urlparse(server_url)\n            if parsed_url.scheme.lower() in ('http', 'https', ):\n                # parse netloc, making sure people did not supply basic auth\n                if '@' in parsed_url.netloc:\n                    credentials, _, path = parsed_url.netloc.rpartition('@')\n                    passed = False\n                    self.write(\n                        'Configuration errors detected!', red, ending='\\n\\n'\n                    )\n                    if ':' in credentials:\n                        self.write('  * SERVER_URL cannot contain authentication '\n                                   'credentials', red, ending='\\n')\n                    else:\n                        self.write('  * SERVER_URL contains an unexpected at-sign!'\n                                   ' This is usually used for basic authentication, '\n                                   'but the colon is left out', red, ending='\\n')\n                else:\n                    self.write('SERVER_URL {0} looks fine'.format(server_url, ), green)\n                # secret token in the clear not recommended\n                if is_set(client.config.secret_token) and parsed_url.scheme.lower() == 'http':\n                    self.write(\"  * SECRET_TOKEN set but server not using https\", yellow, ending='\\n')\n            else:\n                self.write('  * SERVER_URL has scheme {0} and we require '\n                           'http or https!'.format(parsed_url.scheme, ), red, ending='\\n')\n                passed = False\n        else:\n            self.write(\n                'Configuration errors detected!', red, ending='\\n\\n'\n            )\n            self.write(\"  * SERVER_URL appears to be empty\", red, ending='\\n')\n            passed = False\n        self.write('')\n\n        # check if we're disabled due to DEBUG:\n        if settings.DEBUG:\n            if getattr(settings, 'ELASTIC_APM', {}).get('DEBUG'):\n                self.write(\n                    'Note: even though you are running in DEBUG mode, we will '\n                    'send data to the APM Server, because you set ELASTIC_APM[\"DEBUG\"] to '\n                    'True. You can disable ElasticAPM while in DEBUG mode like this'\n                    '\\n\\n',\n                    yellow\n                )\n                self.write(\n                    '   ELASTIC_APM = {\\n'\n                    '       \"DEBUG\": False,\\n'\n                    '       # your other ELASTIC_APM settings\\n'\n                    '   }'\n\n                )\n            else:\n                self.write(\n                    'Looks like you\\'re running in DEBUG mode. ElasticAPM will NOT '\n                    'gather any data while DEBUG is set to True.\\n\\n',\n                    red,\n                )\n                self.write(\n                    'If you want to test ElasticAPM while DEBUG is set to True, you'\n                    ' can force ElasticAPM to gather data by setting'\n                    ' ELASTIC_APM[\"DEBUG\"] to True, like this\\n\\n'\n                    '   ELASTIC_APM = {\\n'\n                    '       \"DEBUG\": True,\\n'\n                    '       # your other ELASTIC_APM settings\\n'\n                    '   }'\n                )\n                passed = False\n        else:\n            self.write(\n                'DEBUG mode is disabled! Looking good!',\n                green\n            )\n        self.write('')\n\n        # check if middleware is set, and if it is at the first position\n        middleware_attr = 'MIDDLEWARE' if getattr(settings, 'MIDDLEWARE', None) is not None else 'MIDDLEWARE_CLASSES'\n        middleware = list(getattr(settings, middleware_attr))\n        try:\n            pos = middleware.index('elasticapm.contrib.django.middleware.TracingMiddleware')\n            if pos == 0:\n                self.write('Tracing middleware is configured! Awesome!', green)\n            else:\n                self.write('Tracing middleware is configured, but not at the first position\\n', yellow)\n                self.write('ElasticAPM works best if you add it at the top of your %s setting' % middleware_attr)\n        except ValueError:\n            self.write('Tracing middleware not configured!', red)\n            self.write(\n                '\\n'\n                'Add it to your %(name)s setting like this:\\n\\n'\n                '    %(name)s = (\\n'\n                '        \"elasticapm.contrib.django.middleware.TracingMiddleware\",\\n'\n                '        # your other middleware classes\\n'\n                '    )\\n' % {'name': middleware_attr}\n            )\n        self.write('')\n        if passed:\n            self.write('Looks like everything should be ready!', green)\n        else:\n            self.write(\n                'Please fix the above errors.',\n                red\n            )\n        self.write('')\n        return passed\n\n    def handle_command_not_found(self, message):\n        self.write(message, red, ending='')\n        self.write(\n            ' Please use one of the following commands:\\n\\n',\n            red\n        )\n        self.write(\n            ''.join(\n                ' * %s\\t%s\\n' % (k.ljust(8), v.__doc__)\n                for k, v in self.dispatch.items()\n            )\n        )\n        self.write('\\n')\n        argv = self._get_argv()\n        self.write(\n            'Usage:\\n\\t%s elasticapm <command>' % (\n                ' '.join(argv[:argv.index('elasticapm')])\n            )\n        )\n\n    def write(self, msg, style_func=None, ending=None, stream=None):\n        \"\"\"\n        wrapper around self.stdout/stderr to ensure Django 1.4 compatibility\n        \"\"\"\n        if stream is None:\n            stream = self.stdout\n        if OutputWrapper is None:\n            ending = '\\n' if ending is None else ending\n            msg += ending\n            stream.write(msg)\n        else:\n            stream.write(msg, style_func=style_func, ending=ending)\n\n    def _get_argv(self):\n        \"\"\"allow cleaner mocking of sys.argv\"\"\"\n        return sys.argv\n\n    dispatch = {\n        'test': handle_test,\n        'check': handle_check,\n    }\n", "path": "elasticapm/contrib/django/management/commands/elasticapm.py"}]}