apply new loggers
This commit is contained in:
parent
4bdb9a2c8e
commit
a46e004f07
|
@ -1,7 +1,7 @@
|
||||||
from argparse import ArgumentParser
|
from argparse import ArgumentParser
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
|
|
||||||
from sanic.log import log
|
from sanic.log import logger
|
||||||
from sanic.app import Sanic
|
from sanic.app import Sanic
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
@ -36,9 +36,9 @@ if __name__ == "__main__":
|
||||||
app.run(host=args.host, port=args.port,
|
app.run(host=args.host, port=args.port,
|
||||||
workers=args.workers, debug=args.debug, ssl=ssl)
|
workers=args.workers, debug=args.debug, ssl=ssl)
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
log.error("No module named {} found.\n"
|
logger.error("No module named {} found.\n"
|
||||||
" Example File: project/sanic_server.py -> app\n"
|
" Example File: project/sanic_server.py -> app\n"
|
||||||
" Example Module: project.sanic_server.app"
|
" Example Module: project.sanic_server.app"
|
||||||
.format(e.name))
|
.format(e.name))
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
log.error("{}".format(e))
|
logger.error("{}".format(e))
|
||||||
|
|
14
sanic/app.py
14
sanic/app.py
|
@ -14,7 +14,7 @@ from sanic.config import Config
|
||||||
from sanic.constants import HTTP_METHODS
|
from sanic.constants import HTTP_METHODS
|
||||||
from sanic.exceptions import ServerError, URLBuildError, SanicException
|
from sanic.exceptions import ServerError, URLBuildError, SanicException
|
||||||
from sanic.handlers import ErrorHandler
|
from sanic.handlers import ErrorHandler
|
||||||
from sanic.log import log
|
from sanic.log import logger, error_logger
|
||||||
from sanic.response import HTTPResponse, StreamingHTTPResponse
|
from sanic.response import HTTPResponse, StreamingHTTPResponse
|
||||||
from sanic.router import Router
|
from sanic.router import Router
|
||||||
from sanic.server import serve, serve_multiple, HttpProtocol, Signal
|
from sanic.server import serve, serve_multiple, HttpProtocol, Signal
|
||||||
|
@ -542,7 +542,7 @@ class Sanic:
|
||||||
response = await self._run_response_middleware(request,
|
response = await self._run_response_middleware(request,
|
||||||
response)
|
response)
|
||||||
except:
|
except:
|
||||||
log.exception(
|
error_logger.exception(
|
||||||
'Exception occured in one of response middleware handlers'
|
'Exception occured in one of response middleware handlers'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -609,12 +609,12 @@ class Sanic:
|
||||||
else:
|
else:
|
||||||
serve_multiple(server_settings, workers)
|
serve_multiple(server_settings, workers)
|
||||||
except:
|
except:
|
||||||
log.exception(
|
error_logger.exception(
|
||||||
'Experienced exception while trying to serve')
|
'Experienced exception while trying to serve')
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
self.is_running = False
|
self.is_running = False
|
||||||
log.info("Server Stopped")
|
logger.info("Server Stopped")
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
"""This kills the Sanic"""
|
"""This kills the Sanic"""
|
||||||
|
@ -757,9 +757,9 @@ class Sanic:
|
||||||
server_settings[settings_name] = listeners
|
server_settings[settings_name] = listeners
|
||||||
|
|
||||||
if debug:
|
if debug:
|
||||||
log.setLevel(logging.DEBUG)
|
logger.setLevel(logging.DEBUG)
|
||||||
if self.config.LOGO is not None:
|
if self.config.LOGO is not None:
|
||||||
log.debug(self.config.LOGO)
|
logger.debug(self.config.LOGO)
|
||||||
|
|
||||||
if run_async:
|
if run_async:
|
||||||
server_settings['run_async'] = True
|
server_settings['run_async'] = True
|
||||||
|
@ -769,6 +769,6 @@ class Sanic:
|
||||||
proto = "http"
|
proto = "http"
|
||||||
if ssl is not None:
|
if ssl is not None:
|
||||||
proto = "https"
|
proto = "https"
|
||||||
log.info('Goin\' Fast @ {}://{}:{}'.format(proto, host, port))
|
logger.info('Goin\' Fast @ {}://{}:{}'.format(proto, host, port))
|
||||||
|
|
||||||
return server_settings
|
return server_settings
|
||||||
|
|
|
@ -12,7 +12,7 @@ from sanic.exceptions import (
|
||||||
TRACEBACK_WRAPPER_HTML,
|
TRACEBACK_WRAPPER_HTML,
|
||||||
TRACEBACK_WRAPPER_INNER_HTML,
|
TRACEBACK_WRAPPER_INNER_HTML,
|
||||||
TRACEBACK_BORDER)
|
TRACEBACK_BORDER)
|
||||||
from sanic.log import log
|
from sanic.log import logger
|
||||||
from sanic.response import text, html
|
from sanic.response import text, html
|
||||||
|
|
||||||
|
|
||||||
|
@ -90,7 +90,7 @@ class ErrorHandler:
|
||||||
'Exception raised in exception handler "{}" '
|
'Exception raised in exception handler "{}" '
|
||||||
'for uri: "{}"\n{}').format(
|
'for uri: "{}"\n{}').format(
|
||||||
handler.__name__, url, format_exc())
|
handler.__name__, url, format_exc())
|
||||||
log.error(response_message)
|
logger.error(response_message)
|
||||||
return text(response_message, 500)
|
return text(response_message, 500)
|
||||||
else:
|
else:
|
||||||
return text('An error occurred while handling an error', 500)
|
return text('An error occurred while handling an error', 500)
|
||||||
|
@ -101,7 +101,7 @@ class ErrorHandler:
|
||||||
Override this method in an ErrorHandler subclass to prevent
|
Override this method in an ErrorHandler subclass to prevent
|
||||||
logging exceptions.
|
logging exceptions.
|
||||||
"""
|
"""
|
||||||
getattr(log, level)(message)
|
getattr(logger, level)(message)
|
||||||
|
|
||||||
def default(self, request, exception):
|
def default(self, request, exception):
|
||||||
self.log(format_exc())
|
self.log(format_exc())
|
||||||
|
@ -117,7 +117,7 @@ class ErrorHandler:
|
||||||
response_message = (
|
response_message = (
|
||||||
'Exception occurred while handling uri: "{}"\n{}'.format(
|
'Exception occurred while handling uri: "{}"\n{}'.format(
|
||||||
request.url, format_exc()))
|
request.url, format_exc()))
|
||||||
log.error(response_message)
|
logger.error(response_message)
|
||||||
return html(html_output, status=500)
|
return html(html_output, status=500)
|
||||||
else:
|
else:
|
||||||
return html(INTERNAL_SERVER_ERROR_HTML, status=500)
|
return html(INTERNAL_SERVER_ERROR_HTML, status=500)
|
||||||
|
|
11
sanic/log.py
11
sanic/log.py
|
@ -8,7 +8,8 @@ LOGGING_CONFIG_DEFAULTS = dict(
|
||||||
loggers={
|
loggers={
|
||||||
"root": {
|
"root": {
|
||||||
"level": "INFO",
|
"level": "INFO",
|
||||||
"handlers": ["console"]},
|
"handlers": ["console"]
|
||||||
|
},
|
||||||
"sanic.error": {
|
"sanic.error": {
|
||||||
"level": "INFO",
|
"level": "INFO",
|
||||||
"handlers": ["error_console"],
|
"handlers": ["error_console"],
|
||||||
|
@ -45,12 +46,6 @@ LOGGING_CONFIG_DEFAULTS = dict(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class AccessLogger:
|
logger = logging.getLogger('root')
|
||||||
|
|
||||||
def __init__(self, logger, access_log_format=None):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
log = logging.getLogger('sanic')
|
|
||||||
error_logger = logging.getLogger('sanic.error')
|
error_logger = logging.getLogger('sanic.error')
|
||||||
access_logger = logging.getLogger('sanic.access')
|
access_logger = logging.getLogger('sanic.access')
|
||||||
|
|
|
@ -17,7 +17,7 @@ except ImportError:
|
||||||
json_loads = json.loads
|
json_loads = json.loads
|
||||||
|
|
||||||
from sanic.exceptions import InvalidUsage
|
from sanic.exceptions import InvalidUsage
|
||||||
from sanic.log import log
|
from sanic.log import logger
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"
|
DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"
|
||||||
|
@ -114,7 +114,7 @@ class Request(dict):
|
||||||
self.parsed_form, self.parsed_files = (
|
self.parsed_form, self.parsed_files = (
|
||||||
parse_multipart_form(self.body, boundary))
|
parse_multipart_form(self.body, boundary))
|
||||||
except Exception:
|
except Exception:
|
||||||
log.exception("Failed when parsing form")
|
logger.exception("Failed when parsing form")
|
||||||
|
|
||||||
return self.parsed_form
|
return self.parsed_form
|
||||||
|
|
||||||
|
|
|
@ -24,7 +24,7 @@ try:
|
||||||
except ImportError:
|
except ImportError:
|
||||||
async_loop = asyncio
|
async_loop = asyncio
|
||||||
|
|
||||||
from sanic.log import log, netlog
|
from sanic.log import logger, access_logger, error_logger
|
||||||
from sanic.response import HTTPResponse
|
from sanic.response import HTTPResponse
|
||||||
from sanic.request import Request
|
from sanic.request import Request
|
||||||
from sanic.exceptions import (
|
from sanic.exceptions import (
|
||||||
|
@ -247,7 +247,7 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
self.request.version, keep_alive,
|
self.request.version, keep_alive,
|
||||||
self.request_timeout))
|
self.request_timeout))
|
||||||
if self.access_log:
|
if self.access_log:
|
||||||
netlog.info('', extra={
|
access_logger.info('', extra={
|
||||||
'status': response.status,
|
'status': response.status,
|
||||||
'byte': len(response.body),
|
'byte': len(response.body),
|
||||||
'host': '{0}:{1}'.format(self.request.ip[0],
|
'host': '{0}:{1}'.format(self.request.ip[0],
|
||||||
|
@ -256,13 +256,13 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
self.request.url)
|
self.request.url)
|
||||||
})
|
})
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
log.error(
|
logger.error(
|
||||||
('Invalid response object for url {}, '
|
('Invalid response object for url {}, '
|
||||||
'Expected Type: HTTPResponse, Actual Type: {}').format(
|
'Expected Type: HTTPResponse, Actual Type: {}').format(
|
||||||
self.url, type(response)))
|
self.url, type(response)))
|
||||||
self.write_error(ServerError('Invalid response type'))
|
self.write_error(ServerError('Invalid response type'))
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
log.error(
|
logger.error(
|
||||||
'Connection lost before response written @ {}'.format(
|
'Connection lost before response written @ {}'.format(
|
||||||
self.request.ip))
|
self.request.ip))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
@ -289,7 +289,7 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
await response.stream(
|
await response.stream(
|
||||||
self.request.version, keep_alive, self.request_timeout)
|
self.request.version, keep_alive, self.request_timeout)
|
||||||
if self.access_log:
|
if self.access_log:
|
||||||
netlog.info('', extra={
|
access_logger.info('', extra={
|
||||||
'status': response.status,
|
'status': response.status,
|
||||||
'byte': -1,
|
'byte': -1,
|
||||||
'host': '{0}:{1}'.format(self.request.ip[0],
|
'host': '{0}:{1}'.format(self.request.ip[0],
|
||||||
|
@ -298,13 +298,13 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
self.request.url)
|
self.request.url)
|
||||||
})
|
})
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
log.error(
|
logger.error(
|
||||||
('Invalid response object for url {}, '
|
('Invalid response object for url {}, '
|
||||||
'Expected Type: HTTPResponse, Actual Type: {}').format(
|
'Expected Type: HTTPResponse, Actual Type: {}').format(
|
||||||
self.url, type(response)))
|
self.url, type(response)))
|
||||||
self.write_error(ServerError('Invalid response type'))
|
self.write_error(ServerError('Invalid response type'))
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
log.error(
|
logger.error(
|
||||||
'Connection lost before response written @ {}'.format(
|
'Connection lost before response written @ {}'.format(
|
||||||
self.request.ip))
|
self.request.ip))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
@ -325,7 +325,7 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
version = self.request.version if self.request else '1.1'
|
version = self.request.version if self.request else '1.1'
|
||||||
self.transport.write(response.output(version))
|
self.transport.write(response.output(version))
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
log.error(
|
logger.error(
|
||||||
'Connection lost before error written @ {}'.format(
|
'Connection lost before error written @ {}'.format(
|
||||||
self.request.ip if self.request else 'Unknown'))
|
self.request.ip if self.request else 'Unknown'))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
@ -350,21 +350,21 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
extra['request'] = 'nil'
|
extra['request'] = 'nil'
|
||||||
if self.parser and not (self.keep_alive
|
if self.parser and not (self.keep_alive
|
||||||
and extra['status'] == 408):
|
and extra['status'] == 408):
|
||||||
netlog.info('', extra=extra)
|
access_logger.info('', extra=extra)
|
||||||
self.transport.close()
|
self.transport.close()
|
||||||
|
|
||||||
def bail_out(self, message, from_error=False):
|
def bail_out(self, message, from_error=False):
|
||||||
if from_error or self.transport.is_closing():
|
if from_error or self.transport.is_closing():
|
||||||
log.error(
|
logger.error(
|
||||||
("Transport closed @ {} and exception "
|
("Transport closed @ {} and exception "
|
||||||
"experienced during error handling").format(
|
"experienced during error handling").format(
|
||||||
self.transport.get_extra_info('peername')))
|
self.transport.get_extra_info('peername')))
|
||||||
log.debug(
|
logger.debug(
|
||||||
'Exception:\n{}'.format(traceback.format_exc()))
|
'Exception:\n{}'.format(traceback.format_exc()))
|
||||||
else:
|
else:
|
||||||
exception = ServerError(message)
|
exception = ServerError(message)
|
||||||
self.write_error(exception)
|
self.write_error(exception)
|
||||||
log.error(message)
|
logger.error(message)
|
||||||
|
|
||||||
def cleanup(self):
|
def cleanup(self):
|
||||||
self.parser = None
|
self.parser = None
|
||||||
|
@ -508,7 +508,7 @@ def serve(host, port, request_handler, error_handler, before_start=None,
|
||||||
try:
|
try:
|
||||||
http_server = loop.run_until_complete(server_coroutine)
|
http_server = loop.run_until_complete(server_coroutine)
|
||||||
except:
|
except:
|
||||||
log.exception("Unable to start server")
|
logger.exception("Unable to start server")
|
||||||
return
|
return
|
||||||
|
|
||||||
trigger_events(after_start, loop)
|
trigger_events(after_start, loop)
|
||||||
|
@ -519,14 +519,14 @@ def serve(host, port, request_handler, error_handler, before_start=None,
|
||||||
try:
|
try:
|
||||||
loop.add_signal_handler(_signal, loop.stop)
|
loop.add_signal_handler(_signal, loop.stop)
|
||||||
except NotImplementedError:
|
except NotImplementedError:
|
||||||
log.warn('Sanic tried to use loop.add_signal_handler but it is'
|
logger.warn('Sanic tried to use loop.add_signal_handler but it is'
|
||||||
' not implemented on this platform.')
|
' not implemented on this platform.')
|
||||||
pid = os.getpid()
|
pid = os.getpid()
|
||||||
try:
|
try:
|
||||||
log.info('Starting worker [{}]'.format(pid))
|
logger.info('Starting worker [{}]'.format(pid))
|
||||||
loop.run_forever()
|
loop.run_forever()
|
||||||
finally:
|
finally:
|
||||||
log.info("Stopping worker [{}]".format(pid))
|
logger.info("Stopping worker [{}]".format(pid))
|
||||||
|
|
||||||
# Run the on_stop function if provided
|
# Run the on_stop function if provided
|
||||||
trigger_events(before_stop, loop)
|
trigger_events(before_stop, loop)
|
||||||
|
@ -588,7 +588,7 @@ def serve_multiple(server_settings, workers):
|
||||||
server_settings['port'] = None
|
server_settings['port'] = None
|
||||||
|
|
||||||
def sig_handler(signal, frame):
|
def sig_handler(signal, frame):
|
||||||
log.info("Received signal {}. Shutting down.".format(
|
logger.info("Received signal {}. Shutting down.".format(
|
||||||
Signals(signal).name))
|
Signals(signal).name))
|
||||||
for process in processes:
|
for process in processes:
|
||||||
os.kill(process.pid, SIGINT)
|
os.kill(process.pid, SIGINT)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import traceback
|
import traceback
|
||||||
from json import JSONDecodeError
|
from json import JSONDecodeError
|
||||||
|
|
||||||
from sanic.log import log
|
from sanic.log import logger
|
||||||
|
|
||||||
HOST = '127.0.0.1'
|
HOST = '127.0.0.1'
|
||||||
PORT = 42101
|
PORT = 42101
|
||||||
|
@ -19,7 +19,7 @@ class SanicTestClient:
|
||||||
url = 'http://{host}:{port}{uri}'.format(
|
url = 'http://{host}:{port}{uri}'.format(
|
||||||
host=HOST, port=PORT, uri=uri)
|
host=HOST, port=PORT, uri=uri)
|
||||||
|
|
||||||
log.info(url)
|
logger.info(url)
|
||||||
conn = aiohttp.TCPConnector(verify_ssl=False)
|
conn = aiohttp.TCPConnector(verify_ssl=False)
|
||||||
async with aiohttp.ClientSession(
|
async with aiohttp.ClientSession(
|
||||||
cookies=cookies, connector=conn) as session:
|
cookies=cookies, connector=conn) as session:
|
||||||
|
@ -61,7 +61,7 @@ class SanicTestClient:
|
||||||
**request_kwargs)
|
**request_kwargs)
|
||||||
results[-1] = response
|
results[-1] = response
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error(
|
logger.error(
|
||||||
'Exception:\n{}'.format(traceback.format_exc()))
|
'Exception:\n{}'.format(traceback.format_exc()))
|
||||||
exceptions.append(e)
|
exceptions.append(e)
|
||||||
self.app.stop()
|
self.app.stop()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user