Python tornado.log.app_log.error() Examples

The following are 30 code examples of tornado.log.app_log.error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.log.app_log , or try the search function .
Example #1
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        """The ``ssl_options`` keyword argument may either be an
        `ssl.SSLContext` object or a dictionary of keywords arguments
        for `ssl.wrap_socket`
        """
        self._ssl_options = kwargs.pop('ssl_options', _client_ssl_defaults)
        super(SSLIOStream, self).__init__(*args, **kwargs)
        self._ssl_accepting = True
        self._handshake_reading = False
        self._handshake_writing = False
        self._ssl_connect_callback = None
        self._server_hostname = None

        # If the socket is already connected, attempt to start the handshake.
        try:
            self.socket.getpeername()
        except socket.error:
            pass
        else:
            # Indirectly start the handshake, which will run on the next
            # IOLoop iteration and then the real IO state will be set in
            # _handle_events.
            self._add_io_state(self.io_loop.WRITE) 
Example #2
Source File: gen.py    From tornado-zh with MIT License 6 votes vote down vote up
def get_result(self):
        result_list = []
        exc_info = None
        for f in self.children:
            try:
                result_list.append(f.get_result())
            except Exception as e:
                if exc_info is None:
                    exc_info = sys.exc_info()
                else:
                    if not isinstance(e, self.quiet_exceptions):
                        app_log.error("Multiple exceptions in yield list",
                                      exc_info=True)
        if exc_info is not None:
            raise_exc_info(exc_info)
        if self.keys is not None:
            return dict(zip(self.keys, result_list))
        else:
            return list(result_list) 
Example #3
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def close(self, exc_info=False):
        """Close this stream.

        If ``exc_info`` is true, set the ``error`` attribute to the current
        exception from `sys.exc_info` (or if ``exc_info`` is a tuple,
        use that instead of `sys.exc_info`).
        """
        if not self.closed():
            if exc_info:
                if not isinstance(exc_info, tuple):
                    exc_info = sys.exc_info()
                if any(exc_info):
                    self.error = exc_info[1]
            if self._read_until_close:
                if (self._streaming_callback is not None and
                        self._read_buffer_size):
                    self._run_read_callback(self._read_buffer_size, True)
                self._read_until_close = False
                self._run_read_callback(self._read_buffer_size, False)
            if self._state is not None:
                self.io_loop.remove_handler(self.fileno())
                self._state = None
            self.close_fd()
            self._closed = True
        self._maybe_run_close_callback() 
Example #4
Source File: websocket.py    From tornado-zh with MIT License 6 votes vote down vote up
def headers_received(self, start_line, headers):
        if start_line.code != 101:
            return super(WebSocketClientConnection, self).headers_received(
                start_line, headers)

        self.headers = headers
        self.protocol = self.get_websocket_protocol()
        self.protocol._process_server_headers(self.key, self.headers)
        self.protocol._receive_frame()

        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

        self.stream = self.connection.detach()
        self.stream.set_close_callback(self.on_connection_close)
        # Once we've taken over the connection, clear the final callback
        # we set on the http request.  This deactivates the error handling
        # in simple_httpclient that would otherwise interfere with our
        # ability to see exceptions.
        self.final_callback = None

        self.connect_future.set_result(self) 
Example #5
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def close(self, exc_info=False):
        """Close this stream.

        If ``exc_info`` is true, set the ``error`` attribute to the current
        exception from `sys.exc_info` (or if ``exc_info`` is a tuple,
        use that instead of `sys.exc_info`).
        """
        if not self.closed():
            if exc_info:
                if not isinstance(exc_info, tuple):
                    exc_info = sys.exc_info()
                if any(exc_info):
                    self.error = exc_info[1]
            if self._read_until_close:
                if (self._streaming_callback is not None and
                        self._read_buffer_size):
                    self._run_read_callback(self._read_buffer_size, True)
                self._read_until_close = False
                self._run_read_callback(self._read_buffer_size, False)
            if self._state is not None:
                self.io_loop.remove_handler(self.fileno())
                self._state = None
            self.close_fd()
            self._closed = True
        self._maybe_run_close_callback() 
Example #6
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def _run_read_callback(self, size, streaming):
        if streaming:
            callback = self._streaming_callback
        else:
            callback = self._read_callback
            self._read_callback = self._streaming_callback = None
            if self._read_future is not None:
                assert callback is None
                future = self._read_future
                self._read_future = None
                future.set_result(self._consume(size))
        if callback is not None:
            assert (self._read_future is None) or streaming
            self._run_callback(callback, self._consume(size))
        else:
            # If we scheduled a callback, we will add the error listener
            # afterwards.  If we didn't, we have to do it now.
            self._maybe_add_error_listener() 
Example #7
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #8
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def log_request(self, handler):
        """写一个完成的HTTP 请求到日志中.

        默认情况下会写到python 根(root)logger. 要改变这种行为
        无论是子类应用和复写这个方法, 或者传递一个函数到应用的
        设置字典中作为 ``log_function``.
        """
        if "log_function" in self.settings:
            self.settings["log_function"](handler)
            return
        if handler.get_status() < 400:
            log_method = access_log.info
        elif handler.get_status() < 500:
            log_method = access_log.warning
        else:
            log_method = access_log.error
        request_time = 1000.0 * handler.request.request_time()
        log_method("%d %s %.2fms", handler.get_status(),
                   handler._request_summary(), request_time) 
Example #9
Source File: websocket.py    From tornado-zh with MIT License 6 votes vote down vote up
def headers_received(self, start_line, headers):
        if start_line.code != 101:
            return super(WebSocketClientConnection, self).headers_received(
                start_line, headers)

        self.headers = headers
        self.protocol = self.get_websocket_protocol()
        self.protocol._process_server_headers(self.key, self.headers)
        self.protocol._receive_frame()

        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

        self.stream = self.connection.detach()
        self.stream.set_close_callback(self.on_connection_close)
        # Once we've taken over the connection, clear the final callback
        # we set on the http request.  This deactivates the error handling
        # in simple_httpclient that would otherwise interfere with our
        # ability to see exceptions.
        self.final_callback = None

        self.connect_future.set_result(self) 
Example #10
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def log_exception(self, typ, value, tb):
        """复写来自定义未捕获异常的日志.

        默认情况下 `HTTPError` 的日志实例作为警告(warning)没有堆栈追踪(在
        ``tornado.general`` logger), 其他作为错误(error)的异常带有堆栈
        追踪(在 ``tornado.application`` logger).

        .. versionadded:: 3.1
        """
        if isinstance(value, HTTPError):
            if value.log_message:
                format = "%d %s: " + value.log_message
                args = ([value.status_code, self._request_summary()] +
                        list(value.args))
                gen_log.warning(format, *args)
        else:
            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
                          self.request, exc_info=(typ, value, tb)) 
Example #11
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #12
Source File: ioloop.py    From tornado-zh with MIT License 6 votes vote down vote up
def _run_callback(self, callback):
        """Runs a callback with error handling.

        For use in subclasses.
        """
        try:
            ret = callback()
            if ret is not None:
                from tornado import gen
                # Functions that return Futures typically swallow all
                # exceptions and store them in the Future.  If a Future
                # makes it out to the IOLoop, ensure its exception (if any)
                # gets logged too.
                try:
                    ret = gen.convert_yielded(ret)
                except gen.BadYieldError:
                    # It's not unusual for add_callback to be used with
                    # methods returning a non-None and non-yieldable
                    # result, which should just be ignored.
                    pass
                else:
                    self.add_future(ret, lambda f: f.result())
        except Exception:
            self.handle_callback_exception(callback) 
Example #13
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def log_exception(self, typ, value, tb):
        """复写来自定义未捕获异常的日志.

        默认情况下 `HTTPError` 的日志实例作为警告(warning)没有堆栈追踪(在
        ``tornado.general`` logger), 其他作为错误(error)的异常带有堆栈
        追踪(在 ``tornado.application`` logger).

        .. versionadded:: 3.1
        """
        if isinstance(value, HTTPError):
            if value.log_message:
                format = "%d %s: " + value.log_message
                args = ([value.status_code, self._request_summary()] +
                        list(value.args))
                gen_log.warning(format, *args)
        else:
            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
                          self.request, exc_info=(typ, value, tb)) 
Example #14
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def _handle_request_exception(self, e):
        if isinstance(e, Finish):
            # Not an error; just finish the request without logging.
            if not self._finished:
                self.finish(*e.args)
            return
        try:
            self.log_exception(*sys.exc_info())
        except Exception:
            # An error here should still get a best-effort send_error()
            # to avoid leaking the connection.
            app_log.error("Error in exception logger", exc_info=True)
        if self._finished:
            # Extra errors after the request has been finished should
            # be logged, but there is no reason to continue to try and
            # send a response.
            return
        if isinstance(e, HTTPError):
            if e.status_code not in httputil.responses and not e.reason:
                gen_log.error("Bad HTTP status code: %d", e.status_code)
                self.send_error(500, exc_info=sys.exc_info())
            else:
                self.send_error(e.status_code, exc_info=sys.exc_info())
        else:
            self.send_error(500, exc_info=sys.exc_info()) 
Example #15
Source File: ioloop.py    From tornado-zh with MIT License 6 votes vote down vote up
def _run_callback(self, callback):
        """Runs a callback with error handling.

        For use in subclasses.
        """
        try:
            ret = callback()
            if ret is not None:
                from tornado import gen
                # Functions that return Futures typically swallow all
                # exceptions and store them in the Future.  If a Future
                # makes it out to the IOLoop, ensure its exception (if any)
                # gets logged too.
                try:
                    ret = gen.convert_yielded(ret)
                except gen.BadYieldError:
                    # It's not unusual for add_callback to be used with
                    # methods returning a non-None and non-yieldable
                    # result, which should just be ignored.
                    pass
                else:
                    self.add_future(ret, lambda f: f.result())
        except Exception:
            self.handle_callback_exception(callback) 
Example #16
Source File: iostream.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_fd_error(self):
        errno = self.socket.getsockopt(socket.SOL_SOCKET,
                                       socket.SO_ERROR)
        return socket.error(errno, os.strerror(errno)) 
Example #17
Source File: iostream.py    From tornado-zh with MIT License 5 votes vote down vote up
def read_from_fd(self):
        if self._ssl_accepting:
            # If the handshake hasn't finished yet, there can't be anything
            # to read (attempting to read may or may not raise an exception
            # depending on the SSL version)
            return None
        try:
            # SSLSocket objects have both a read() and recv() method,
            # while regular sockets only have recv().
            # The recv() method blocks (at least in python 2.6) if it is
            # called when there is nothing to read, so we have to use
            # read() instead.
            chunk = self.socket.read(self.read_chunk_size)
        except ssl.SSLError as e:
            # SSLError is a subclass of socket.error, so this except
            # block must come first.
            if e.args[0] == ssl.SSL_ERROR_WANT_READ:
                return None
            else:
                raise
        except socket.error as e:
            if e.args[0] in _ERRNO_WOULDBLOCK:
                return None
            else:
                raise
        if not chunk:
            self.close()
            return None
        return chunk 
Example #18
Source File: iostream.py    From tornado-zh with MIT License 5 votes vote down vote up
def write_to_fd(self, data):
        try:
            return self.socket.send(data)
        except ssl.SSLError as e:
            if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
                # the socket is not writeable; we need to transform this into
                # an EWOULDBLOCK socket.error or a zero return value,
                # either of which will be recognized by the caller of this
                # method. Prior to Python 3.5, an unwriteable socket would
                # simply return 0 bytes written.
                return 0
            raise 
Example #19
Source File: iostream.py    From tornado-zh with MIT License 5 votes vote down vote up
def _is_connreset(self, exc):
        """Return true if exc is ECONNRESET or equivalent.

        May be overridden in subclasses.
        """
        return (isinstance(exc, (socket.error, IOError)) and
                errno_from_exception(exc) in _ERRNO_CONNRESET) 
Example #20
Source File: iostream.py    From tornado-zh with MIT License 5 votes vote down vote up
def _check_closed(self):
        if self.closed():
            raise StreamClosedError(real_error=self.error) 
Example #21
Source File: iostream.py    From tornado-zh with MIT License 5 votes vote down vote up
def read_from_fd(self):
        try:
            chunk = self.socket.recv(self.read_chunk_size)
        except socket.error as e:
            if e.args[0] in _ERRNO_WOULDBLOCK:
                return None
            else:
                raise
        if not chunk:
            self.close()
            return None
        return chunk 
Example #22
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
def set_default_headers(self):
        """复写这个方法可以在请求开始的时候设置HTTP头.

        例如, 在这里可以设置一个自定义 ``Server`` 头. 注意在一般的
        请求过程流里可能不会实现你预期的效果, 因为头部可能在错误处
        理(error handling)中被重置.
        """
        pass 
Example #23
Source File: websocket.py    From tornado-zh with MIT License 5 votes vote down vote up
def _on_http_response(self, response):
        if not self.connect_future.done():
            if response.error:
                self.connect_future.set_exception(response.error)
            else:
                self.connect_future.set_exception(WebSocketError(
                    "Non-websocket response")) 
Example #24
Source File: websocket.py    From tornado-zh with MIT License 5 votes vote down vote up
def _run_callback(self, callback, *args, **kwargs):
        """Runs the given callback with exception handling.

        On error, aborts the websocket connection and returns False.
        """
        try:
            callback(*args, **kwargs)
        except Exception:
            app_log.error("Uncaught exception in %s",
                          self.request.path, exc_info=True)
            self._abort() 
Example #25
Source File: twisted.py    From tornado-zh with MIT License 5 votes vote down vote up
def _invoke_callback(self, fd, events):
        if fd not in self._fds:
            return
        (reader, writer) = self._fds[fd]
        if reader:
            err = None
            if reader.fileno() == -1:
                err = error.ConnectionLost()
            elif events & IOLoop.READ:
                err = log.callWithLogger(reader, reader.doRead)
            if err is None and events & IOLoop.ERROR:
                err = error.ConnectionLost()
            if err is not None:
                self.removeReader(reader)
                reader.readConnectionLost(failure.Failure(err))
        if writer:
            err = None
            if writer.fileno() == -1:
                err = error.ConnectionLost()
            elif events & IOLoop.WRITE:
                err = log.callWithLogger(writer, writer.doWrite)
            if err is None and events & IOLoop.ERROR:
                err = error.ConnectionLost()
            if err is not None:
                self.removeWriter(writer)
                writer.writeConnectionLost(failure.Failure(err)) 
Example #26
Source File: twisted.py    From tornado-zh with MIT License 5 votes vote down vote up
def _called(self):
        self._active = False
        self._reactor._removeDelayedCall(self)
        try:
            self._func()
        except:
            app_log.error("_called caught exception", exc_info=True) 
Example #27
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
def _get_cached_version(cls, abs_path):
        with cls._lock:
            hashes = cls._static_hashes
            if abs_path not in hashes:
                try:
                    hashes[abs_path] = cls.get_content_version(abs_path)
                except Exception:
                    gen_log.error("Could not open static file %r", abs_path)
                    hashes[abs_path] = None
            hsh = hashes.get(abs_path)
            if hsh:
                return hsh
        return None 
Example #28
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
def send_error(self, status_code=500, **kwargs):
        """给浏览器发送给定的HTTP 错误码.

        如果 `flush()` 已经被调用, 它是不可能发送错误的, 所以这个方法将终止
        响应. 如果输出已经被写但尚未flush, 它将被丢弃并被错误页代替.

        复写 `write_error()` 来自定义它返回的错误页. 额外的关键字参数将
        被传递给 `write_error`.
        """
        if self._headers_written:
            gen_log.error("Cannot send error response after headers written")
            if not self._finished:
                # If we get an error between writing headers and finishing,
                # we are unlikely to be able to finish due to a
                # Content-Length mismatch. Try anyway to release the
                # socket.
                try:
                    self.finish()
                except Exception:
                    gen_log.error("Failed to flush partial response",
                                  exc_info=True)
            return
        self.clear()

        reason = kwargs.get('reason')
        if 'exc_info' in kwargs:
            exception = kwargs['exc_info'][1]
            if isinstance(exception, HTTPError) and exception.reason:
                reason = exception.reason
        self.set_status(status_code, reason=reason)
        try:
            self.write_error(status_code, **kwargs)
        except Exception:
            app_log.error("Uncaught exception in write_error", exc_info=True)
        if not self._finished:
            self.finish() 
Example #29
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
def set_default_headers(self):
        """复写这个方法可以在请求开始的时候设置HTTP头.

        例如, 在这里可以设置一个自定义 ``Server`` 头. 注意在一般的
        请求过程流里可能不会实现你预期的效果, 因为头部可能在错误处
        理(error handling)中被重置.
        """
        pass 
Example #30
Source File: testing.py    From tornado-zh with MIT License 5 votes vote down vote up
def run(self, result=None):
        with ExceptionStackContext(self._handle_exception):
            super(AsyncTestCase, self).run(result)
        # As a last resort, if an exception escaped super.run() and wasn't
        # re-raised in tearDown, raise it here.  This will cause the
        # unittest run to fail messily, but that's better than silently
        # ignoring an error.
        self.__rethrow()