prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  access log format is invalid when using gunicorn worker
  It seems you have to pass in `--access-logformat='%a %l %u %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i"'` to gunicorn for logging to work, they default format from gunicorn is `"%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"` which doesn't work with aiohttp
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `aiohttp/worker.py`
  Content:
  ```
  1 """Async gunicorn worker for aiohttp.web"""
  2 
  3 import asyncio
  4 import os
  5 import signal
  6 import ssl
  7 import sys
  8 
  9 import gunicorn.workers.base as base
  10 
  11 from aiohttp.helpers import ensure_future
  12 
  13 __all__ = ('GunicornWebWorker', 'GunicornUVLoopWebWorker')
  14 
  15 
  16 class GunicornWebWorker(base.Worker):
  17 
  18     def __init__(self, *args, **kw):  # pragma: no cover
  19         super().__init__(*args, **kw)
  20 
  21         self.servers = {}
  22         self.exit_code = 0
  23 
  24     def init_process(self):
  25         # create new event_loop after fork
  26         asyncio.get_event_loop().close()
  27 
  28         self.loop = asyncio.new_event_loop()
  29         asyncio.set_event_loop(self.loop)
  30 
  31         super().init_process()
  32 
  33     def run(self):
  34         self.loop.run_until_complete(self.wsgi.startup())
  35         self._runner = ensure_future(self._run(), loop=self.loop)
  36 
  37         try:
  38             self.loop.run_until_complete(self._runner)
  39         finally:
  40             self.loop.close()
  41 
  42         sys.exit(self.exit_code)
  43 
  44     def make_handler(self, app):
  45         return app.make_handler(
  46             logger=self.log,
  47             debug=self.cfg.debug,
  48             timeout=self.cfg.timeout,
  49             keep_alive=self.cfg.keepalive,
  50             access_log=self.log.access_log,
  51             access_log_format=self.cfg.access_log_format)
  52 
  53     @asyncio.coroutine
  54     def close(self):
  55         if self.servers:
  56             servers = self.servers
  57             self.servers = None
  58 
  59             # stop accepting connections
  60             for server, handler in servers.items():
  61                 self.log.info("Stopping server: %s, connections: %s",
  62                               self.pid, len(handler.connections))
  63                 server.close()
  64                 yield from server.wait_closed()
  65 
  66             # send on_shutdown event
  67             yield from self.wsgi.shutdown()
  68 
  69             # stop alive connections
  70             tasks = [
  71                 handler.finish_connections(
  72                     timeout=self.cfg.graceful_timeout / 100 * 95)
  73                 for handler in servers.values()]
  74             yield from asyncio.gather(*tasks, loop=self.loop)
  75 
  76             # cleanup application
  77             yield from self.wsgi.cleanup()
  78 
  79     @asyncio.coroutine
  80     def _run(self):
  81 
  82         ctx = self._create_ssl_context(self.cfg) if self.cfg.is_ssl else None
  83 
  84         for sock in self.sockets:
  85             handler = self.make_handler(self.wsgi)
  86             srv = yield from self.loop.create_server(handler, sock=sock.sock,
  87                                                      ssl=ctx)
  88             self.servers[srv] = handler
  89 
  90         # If our parent changed then we shut down.
  91         pid = os.getpid()
  92         try:
  93             while self.alive:
  94                 self.notify()
  95 
  96                 cnt = sum(handler.requests_count
  97                           for handler in self.servers.values())
  98                 if self.cfg.max_requests and cnt > self.cfg.max_requests:
  99                     self.alive = False
  100                     self.log.info("Max requests, shutting down: %s", self)
  101 
  102                 elif pid == os.getpid() and self.ppid != os.getppid():
  103                     self.alive = False
  104                     self.log.info("Parent changed, shutting down: %s", self)
  105                 else:
  106                     yield from asyncio.sleep(1.0, loop=self.loop)
  107 
  108         except BaseException:
  109             pass
  110 
  111         yield from self.close()
  112 
  113     def init_signals(self):
  114         # Set up signals through the event loop API.
  115 
  116         self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit,
  117                                      signal.SIGQUIT, None)
  118 
  119         self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit,
  120                                      signal.SIGTERM, None)
  121 
  122         self.loop.add_signal_handler(signal.SIGINT, self.handle_quit,
  123                                      signal.SIGINT, None)
  124 
  125         self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch,
  126                                      signal.SIGWINCH, None)
  127 
  128         self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,
  129                                      signal.SIGUSR1, None)
  130 
  131         self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort,
  132                                      signal.SIGABRT, None)
  133 
  134         # Don't let SIGTERM and SIGUSR1 disturb active requests
  135         # by interrupting system calls
  136         signal.siginterrupt(signal.SIGTERM, False)
  137         signal.siginterrupt(signal.SIGUSR1, False)
  138 
  139     def handle_quit(self, sig, frame):
  140         self.alive = False
  141 
  142     def handle_abort(self, sig, frame):
  143         self.alive = False
  144         self.exit_code = 1
  145 
  146     @staticmethod
  147     def _create_ssl_context(cfg):
  148         """ Creates SSLContext instance for usage in asyncio.create_server.
  149 
  150         See ssl.SSLSocket.__init__ for more details.
  151         """
  152         ctx = ssl.SSLContext(cfg.ssl_version)
  153         ctx.load_cert_chain(cfg.certfile, cfg.keyfile)
  154         ctx.verify_mode = cfg.cert_reqs
  155         if cfg.ca_certs:
  156             ctx.load_verify_locations(cfg.ca_certs)
  157         if cfg.ciphers:
  158             ctx.set_ciphers(cfg.ciphers)
  159         return ctx
  160 
  161 
  162 class GunicornUVLoopWebWorker(GunicornWebWorker):
  163 
  164     def init_process(self):
  165         import uvloop
  166 
  167         # Close any existing event loop before setting a
  168         # new policy.
  169         asyncio.get_event_loop().close()
  170 
  171         # Setup uvloop policy, so that every
  172         # asyncio.get_event_loop() will create an instance
  173         # of uvloop event loop.
  174         asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  175 
  176         super().init_process()
  177
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/aiohttp/worker.py b/aiohttp/worker.py
  --- a/aiohttp/worker.py
  +++ b/aiohttp/worker.py
  @@ -2,19 +2,24 @@
   
   import asyncio
   import os
  +import re
   import signal
   import ssl
   import sys
   
   import gunicorn.workers.base as base
   
  -from aiohttp.helpers import ensure_future
  +from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat
  +from aiohttp.helpers import AccessLogger, ensure_future
   
   __all__ = ('GunicornWebWorker', 'GunicornUVLoopWebWorker')
   
   
   class GunicornWebWorker(base.Worker):
   
  +    DEFAULT_AIOHTTP_LOG_FORMAT = AccessLogger.LOG_FORMAT
  +    DEFAULT_GUNICORN_LOG_FORMAT = GunicornAccessLogFormat.default
  +
       def __init__(self, *args, **kw):  # pragma: no cover
           super().__init__(*args, **kw)
   
  @@ -48,7 +53,8 @@
               timeout=self.cfg.timeout,
               keep_alive=self.cfg.keepalive,
               access_log=self.log.access_log,
  -            access_log_format=self.cfg.access_log_format)
  +            access_log_format=self._get_valid_log_format(
  +                self.cfg.access_log_format))
   
       @asyncio.coroutine
       def close(self):
  @@ -158,6 +164,20 @@
               ctx.set_ciphers(cfg.ciphers)
           return ctx
   
  +    def _get_valid_log_format(self, source_format):
  +        if source_format == self.DEFAULT_GUNICORN_LOG_FORMAT:
  +            return self.DEFAULT_AIOHTTP_LOG_FORMAT
  +        elif re.search(r'%\([^\)]+\)', source_format):
  +            raise ValueError(
  +                "Gunicorn's style options in form of `%(name)s` are not "
  +                "supported for the log formatting. Please use aiohttp's "
  +                "format specification to configure access log formatting: "
  +                "http://aiohttp.readthedocs.io/en/stable/logging.html"
  +                "#format-specification"
  +            )
  +        else:
  +            return source_format
  +
   
   class GunicornUVLoopWebWorker(GunicornWebWorker):
  
verification_info: {"golden_diff": "diff --git a/aiohttp/worker.py b/aiohttp/worker.py\n--- a/aiohttp/worker.py\n+++ b/aiohttp/worker.py\n@@ -2,19 +2,24 @@\n \n import asyncio\n import os\n+import re\n import signal\n import ssl\n import sys\n \n import gunicorn.workers.base as base\n \n-from aiohttp.helpers import ensure_future\n+from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat\n+from aiohttp.helpers import AccessLogger, ensure_future\n \n __all__ = ('GunicornWebWorker', 'GunicornUVLoopWebWorker')\n \n \n class GunicornWebWorker(base.Worker):\n \n+    DEFAULT_AIOHTTP_LOG_FORMAT = AccessLogger.LOG_FORMAT\n+    DEFAULT_GUNICORN_LOG_FORMAT = GunicornAccessLogFormat.default\n+\n     def __init__(self, *args, **kw):  # pragma: no cover\n         super().__init__(*args, **kw)\n \n@@ -48,7 +53,8 @@\n             timeout=self.cfg.timeout,\n             keep_alive=self.cfg.keepalive,\n             access_log=self.log.access_log,\n-            access_log_format=self.cfg.access_log_format)\n+            access_log_format=self._get_valid_log_format(\n+                self.cfg.access_log_format))\n \n     @asyncio.coroutine\n     def close(self):\n@@ -158,6 +164,20 @@\n             ctx.set_ciphers(cfg.ciphers)\n         return ctx\n \n+    def _get_valid_log_format(self, source_format):\n+        if source_format == self.DEFAULT_GUNICORN_LOG_FORMAT:\n+            return self.DEFAULT_AIOHTTP_LOG_FORMAT\n+        elif re.search(r'%\\([^\\)]+\\)', source_format):\n+            raise ValueError(\n+                \"Gunicorn's style options in form of `%(name)s` are not \"\n+                \"supported for the log formatting. Please use aiohttp's \"\n+                \"format specification to configure access log formatting: \"\n+                \"http://aiohttp.readthedocs.io/en/stable/logging.html\"\n+                \"#format-specification\"\n+            )\n+        else:\n+            return source_format\n+\n \n class GunicornUVLoopWebWorker(GunicornWebWorker):\n", "issue": "access log format is invalid when using gunicorn worker\nIt seems you have to pass in `--access-logformat='%a %l %u %t \"%r\" %s %b \"%{Referrer}i\" \"%{User-Agent}i\"'` to gunicorn for logging to work, they default format from gunicorn is `\"%(h)s %(l)s %(u)s %(t)s \"%(r)s\" %(s)s %(b)s \"%(f)s\" \"%(a)s\"` which doesn't work with aiohttp\n\n", "before_files": [{"content": "\"\"\"Async gunicorn worker for aiohttp.web\"\"\"\n\nimport asyncio\nimport os\nimport signal\nimport ssl\nimport sys\n\nimport gunicorn.workers.base as base\n\nfrom aiohttp.helpers import ensure_future\n\n__all__ = ('GunicornWebWorker', 'GunicornUVLoopWebWorker')\n\n\nclass GunicornWebWorker(base.Worker):\n\n    def __init__(self, *args, **kw):  # pragma: no cover\n        super().__init__(*args, **kw)\n\n        self.servers = {}\n        self.exit_code = 0\n\n    def init_process(self):\n        # create new event_loop after fork\n        asyncio.get_event_loop().close()\n\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n\n        super().init_process()\n\n    def run(self):\n        self.loop.run_until_complete(self.wsgi.startup())\n        self._runner = ensure_future(self._run(), loop=self.loop)\n\n        try:\n            self.loop.run_until_complete(self._runner)\n        finally:\n            self.loop.close()\n\n        sys.exit(self.exit_code)\n\n    def make_handler(self, app):\n        return app.make_handler(\n            logger=self.log,\n            debug=self.cfg.debug,\n            timeout=self.cfg.timeout,\n            keep_alive=self.cfg.keepalive,\n            access_log=self.log.access_log,\n            access_log_format=self.cfg.access_log_format)\n\n    @asyncio.coroutine\n    def close(self):\n        if self.servers:\n            servers = self.servers\n            self.servers = None\n\n            # stop accepting connections\n            for server, handler in servers.items():\n                self.log.info(\"Stopping server: %s, connections: %s\",\n                              self.pid, len(handler.connections))\n                server.close()\n                yield from server.wait_closed()\n\n            # send on_shutdown event\n            yield from self.wsgi.shutdown()\n\n            # stop alive connections\n            tasks = [\n                handler.finish_connections(\n                    timeout=self.cfg.graceful_timeout / 100 * 95)\n                for handler in servers.values()]\n            yield from asyncio.gather(*tasks, loop=self.loop)\n\n            # cleanup application\n            yield from self.wsgi.cleanup()\n\n    @asyncio.coroutine\n    def _run(self):\n\n        ctx = self._create_ssl_context(self.cfg) if self.cfg.is_ssl else None\n\n        for sock in self.sockets:\n            handler = self.make_handler(self.wsgi)\n            srv = yield from self.loop.create_server(handler, sock=sock.sock,\n                                                     ssl=ctx)\n            self.servers[srv] = handler\n\n        # If our parent changed then we shut down.\n        pid = os.getpid()\n        try:\n            while self.alive:\n                self.notify()\n\n                cnt = sum(handler.requests_count\n                          for handler in self.servers.values())\n                if self.cfg.max_requests and cnt > self.cfg.max_requests:\n                    self.alive = False\n                    self.log.info(\"Max requests, shutting down: %s\", self)\n\n                elif pid == os.getpid() and self.ppid != os.getppid():\n                    self.alive = False\n                    self.log.info(\"Parent changed, shutting down: %s\", self)\n                else:\n                    yield from asyncio.sleep(1.0, loop=self.loop)\n\n        except BaseException:\n            pass\n\n        yield from self.close()\n\n    def init_signals(self):\n        # Set up signals through the event loop API.\n\n        self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit,\n                                     signal.SIGQUIT, None)\n\n        self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit,\n                                     signal.SIGTERM, None)\n\n        self.loop.add_signal_handler(signal.SIGINT, self.handle_quit,\n                                     signal.SIGINT, None)\n\n        self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch,\n                                     signal.SIGWINCH, None)\n\n        self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,\n                                     signal.SIGUSR1, None)\n\n        self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort,\n                                     signal.SIGABRT, None)\n\n        # Don't let SIGTERM and SIGUSR1 disturb active requests\n        # by interrupting system calls\n        signal.siginterrupt(signal.SIGTERM, False)\n        signal.siginterrupt(signal.SIGUSR1, False)\n\n    def handle_quit(self, sig, frame):\n        self.alive = False\n\n    def handle_abort(self, sig, frame):\n        self.alive = False\n        self.exit_code = 1\n\n    @staticmethod\n    def _create_ssl_context(cfg):\n        \"\"\" Creates SSLContext instance for usage in asyncio.create_server.\n\n        See ssl.SSLSocket.__init__ for more details.\n        \"\"\"\n        ctx = ssl.SSLContext(cfg.ssl_version)\n        ctx.load_cert_chain(cfg.certfile, cfg.keyfile)\n        ctx.verify_mode = cfg.cert_reqs\n        if cfg.ca_certs:\n            ctx.load_verify_locations(cfg.ca_certs)\n        if cfg.ciphers:\n            ctx.set_ciphers(cfg.ciphers)\n        return ctx\n\n\nclass GunicornUVLoopWebWorker(GunicornWebWorker):\n\n    def init_process(self):\n        import uvloop\n\n        # Close any existing event loop before setting a\n        # new policy.\n        asyncio.get_event_loop().close()\n\n        # Setup uvloop policy, so that every\n        # asyncio.get_event_loop() will create an instance\n        # of uvloop event loop.\n        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\n        super().init_process()\n", "path": "aiohttp/worker.py"}], "after_files": [{"content": "\"\"\"Async gunicorn worker for aiohttp.web\"\"\"\n\nimport asyncio\nimport os\nimport re\nimport signal\nimport ssl\nimport sys\n\nimport gunicorn.workers.base as base\n\nfrom gunicorn.config import AccessLogFormat as GunicornAccessLogFormat\nfrom aiohttp.helpers import AccessLogger, ensure_future\n\n__all__ = ('GunicornWebWorker', 'GunicornUVLoopWebWorker')\n\n\nclass GunicornWebWorker(base.Worker):\n\n    DEFAULT_AIOHTTP_LOG_FORMAT = AccessLogger.LOG_FORMAT\n    DEFAULT_GUNICORN_LOG_FORMAT = GunicornAccessLogFormat.default\n\n    def __init__(self, *args, **kw):  # pragma: no cover\n        super().__init__(*args, **kw)\n\n        self.servers = {}\n        self.exit_code = 0\n\n    def init_process(self):\n        # create new event_loop after fork\n        asyncio.get_event_loop().close()\n\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n\n        super().init_process()\n\n    def run(self):\n        self.loop.run_until_complete(self.wsgi.startup())\n        self._runner = ensure_future(self._run(), loop=self.loop)\n\n        try:\n            self.loop.run_until_complete(self._runner)\n        finally:\n            self.loop.close()\n\n        sys.exit(self.exit_code)\n\n    def make_handler(self, app):\n        return app.make_handler(\n            logger=self.log,\n            debug=self.cfg.debug,\n            timeout=self.cfg.timeout,\n            keep_alive=self.cfg.keepalive,\n            access_log=self.log.access_log,\n            access_log_format=self._get_valid_log_format(\n                self.cfg.access_log_format))\n\n    @asyncio.coroutine\n    def close(self):\n        if self.servers:\n            servers = self.servers\n            self.servers = None\n\n            # stop accepting connections\n            for server, handler in servers.items():\n                self.log.info(\"Stopping server: %s, connections: %s\",\n                              self.pid, len(handler.connections))\n                server.close()\n                yield from server.wait_closed()\n\n            # send on_shutdown event\n            yield from self.wsgi.shutdown()\n\n            # stop alive connections\n            tasks = [\n                handler.finish_connections(\n                    timeout=self.cfg.graceful_timeout / 100 * 95)\n                for handler in servers.values()]\n            yield from asyncio.gather(*tasks, loop=self.loop)\n\n            # cleanup application\n            yield from self.wsgi.cleanup()\n\n    @asyncio.coroutine\n    def _run(self):\n\n        ctx = self._create_ssl_context(self.cfg) if self.cfg.is_ssl else None\n\n        for sock in self.sockets:\n            handler = self.make_handler(self.wsgi)\n            srv = yield from self.loop.create_server(handler, sock=sock.sock,\n                                                     ssl=ctx)\n            self.servers[srv] = handler\n\n        # If our parent changed then we shut down.\n        pid = os.getpid()\n        try:\n            while self.alive:\n                self.notify()\n\n                cnt = sum(handler.requests_count\n                          for handler in self.servers.values())\n                if self.cfg.max_requests and cnt > self.cfg.max_requests:\n                    self.alive = False\n                    self.log.info(\"Max requests, shutting down: %s\", self)\n\n                elif pid == os.getpid() and self.ppid != os.getppid():\n                    self.alive = False\n                    self.log.info(\"Parent changed, shutting down: %s\", self)\n                else:\n                    yield from asyncio.sleep(1.0, loop=self.loop)\n\n        except BaseException:\n            pass\n\n        yield from self.close()\n\n    def init_signals(self):\n        # Set up signals through the event loop API.\n\n        self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit,\n                                     signal.SIGQUIT, None)\n\n        self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit,\n                                     signal.SIGTERM, None)\n\n        self.loop.add_signal_handler(signal.SIGINT, self.handle_quit,\n                                     signal.SIGINT, None)\n\n        self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch,\n                                     signal.SIGWINCH, None)\n\n        self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,\n                                     signal.SIGUSR1, None)\n\n        self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort,\n                                     signal.SIGABRT, None)\n\n        # Don't let SIGTERM and SIGUSR1 disturb active requests\n        # by interrupting system calls\n        signal.siginterrupt(signal.SIGTERM, False)\n        signal.siginterrupt(signal.SIGUSR1, False)\n\n    def handle_quit(self, sig, frame):\n        self.alive = False\n\n    def handle_abort(self, sig, frame):\n        self.alive = False\n        self.exit_code = 1\n\n    @staticmethod\n    def _create_ssl_context(cfg):\n        \"\"\" Creates SSLContext instance for usage in asyncio.create_server.\n\n        See ssl.SSLSocket.__init__ for more details.\n        \"\"\"\n        ctx = ssl.SSLContext(cfg.ssl_version)\n        ctx.load_cert_chain(cfg.certfile, cfg.keyfile)\n        ctx.verify_mode = cfg.cert_reqs\n        if cfg.ca_certs:\n            ctx.load_verify_locations(cfg.ca_certs)\n        if cfg.ciphers:\n            ctx.set_ciphers(cfg.ciphers)\n        return ctx\n\n    def _get_valid_log_format(self, source_format):\n        if source_format == self.DEFAULT_GUNICORN_LOG_FORMAT:\n            return self.DEFAULT_AIOHTTP_LOG_FORMAT\n        elif re.search(r'%\\([^\\)]+\\)', source_format):\n            raise ValueError(\n                \"Gunicorn's style options in form of `%(name)s` are not \"\n                \"supported for the log formatting. Please use aiohttp's \"\n                \"format specification to configure access log formatting: \"\n                \"http://aiohttp.readthedocs.io/en/stable/logging.html\"\n                \"#format-specification\"\n            )\n        else:\n            return source_format\n\n\nclass GunicornUVLoopWebWorker(GunicornWebWorker):\n\n    def init_process(self):\n        import uvloop\n\n        # Close any existing event loop before setting a\n        # new policy.\n        asyncio.get_event_loop().close()\n\n        # Setup uvloop policy, so that every\n        # asyncio.get_event_loop() will create an instance\n        # of uvloop event loop.\n        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\n        super().init_process()\n", "path": "aiohttp/worker.py"}]}