apply new loggers

This commit is contained in:
Yun Xu 2017-09-11 22:12:49 -07:00
parent 4bdb9a2c8e
commit a46e004f07
7 changed files with 39 additions and 44 deletions

View File

@ -1,7 +1,7 @@
from argparse import ArgumentParser
from importlib import import_module
from sanic.log import log
from sanic.log import logger
from sanic.app import Sanic
if __name__ == "__main__":
@ -36,9 +36,9 @@ if __name__ == "__main__":
app.run(host=args.host, port=args.port,
workers=args.workers, debug=args.debug, ssl=ssl)
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 Module: project.sanic_server.app"
.format(e.name))
except ValueError as e:
log.error("{}".format(e))
logger.error("{}".format(e))

View File

@ -14,7 +14,7 @@ from sanic.config import Config
from sanic.constants import HTTP_METHODS
from sanic.exceptions import ServerError, URLBuildError, SanicException
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.router import Router
from sanic.server import serve, serve_multiple, HttpProtocol, Signal
@ -542,7 +542,7 @@ class Sanic:
response = await self._run_response_middleware(request,
response)
except:
log.exception(
error_logger.exception(
'Exception occured in one of response middleware handlers'
)
@ -609,12 +609,12 @@ class Sanic:
else:
serve_multiple(server_settings, workers)
except:
log.exception(
error_logger.exception(
'Experienced exception while trying to serve')
raise
finally:
self.is_running = False
log.info("Server Stopped")
logger.info("Server Stopped")
def stop(self):
"""This kills the Sanic"""
@ -757,9 +757,9 @@ class Sanic:
server_settings[settings_name] = listeners
if debug:
log.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
if self.config.LOGO is not None:
log.debug(self.config.LOGO)
logger.debug(self.config.LOGO)
if run_async:
server_settings['run_async'] = True
@ -769,6 +769,6 @@ class Sanic:
proto = "http"
if ssl is not None:
proto = "https"
log.info('Goin\' Fast @ {}://{}:{}'.format(proto, host, port))
logger.info('Goin\' Fast @ {}://{}:{}'.format(proto, host, port))
return server_settings

View File

@ -12,7 +12,7 @@ from sanic.exceptions import (
TRACEBACK_WRAPPER_HTML,
TRACEBACK_WRAPPER_INNER_HTML,
TRACEBACK_BORDER)
from sanic.log import log
from sanic.log import logger
from sanic.response import text, html
@ -90,7 +90,7 @@ class ErrorHandler:
'Exception raised in exception handler "{}" '
'for uri: "{}"\n{}').format(
handler.__name__, url, format_exc())
log.error(response_message)
logger.error(response_message)
return text(response_message, 500)
else:
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
logging exceptions.
"""
getattr(log, level)(message)
getattr(logger, level)(message)
def default(self, request, exception):
self.log(format_exc())
@ -117,7 +117,7 @@ class ErrorHandler:
response_message = (
'Exception occurred while handling uri: "{}"\n{}'.format(
request.url, format_exc()))
log.error(response_message)
logger.error(response_message)
return html(html_output, status=500)
else:
return html(INTERNAL_SERVER_ERROR_HTML, status=500)

View File

@ -8,7 +8,8 @@ LOGGING_CONFIG_DEFAULTS = dict(
loggers={
"root": {
"level": "INFO",
"handlers": ["console"]},
"handlers": ["console"]
},
"sanic.error": {
"level": "INFO",
"handlers": ["error_console"],
@ -45,12 +46,6 @@ LOGGING_CONFIG_DEFAULTS = dict(
)
class AccessLogger:
def __init__(self, logger, access_log_format=None):
pass
log = logging.getLogger('sanic')
logger = logging.getLogger('root')
error_logger = logging.getLogger('sanic.error')
access_logger = logging.getLogger('sanic.access')

View File

@ -17,7 +17,7 @@ except ImportError:
json_loads = json.loads
from sanic.exceptions import InvalidUsage
from sanic.log import log
from sanic.log import logger
DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"
@ -114,7 +114,7 @@ class Request(dict):
self.parsed_form, self.parsed_files = (
parse_multipart_form(self.body, boundary))
except Exception:
log.exception("Failed when parsing form")
logger.exception("Failed when parsing form")
return self.parsed_form

View File

@ -24,7 +24,7 @@ try:
except ImportError:
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.request import Request
from sanic.exceptions import (
@ -247,7 +247,7 @@ class HttpProtocol(asyncio.Protocol):
self.request.version, keep_alive,
self.request_timeout))
if self.access_log:
netlog.info('', extra={
access_logger.info('', extra={
'status': response.status,
'byte': len(response.body),
'host': '{0}:{1}'.format(self.request.ip[0],
@ -256,13 +256,13 @@ class HttpProtocol(asyncio.Protocol):
self.request.url)
})
except AttributeError:
log.error(
logger.error(
('Invalid response object for url {}, '
'Expected Type: HTTPResponse, Actual Type: {}').format(
self.url, type(response)))
self.write_error(ServerError('Invalid response type'))
except RuntimeError:
log.error(
logger.error(
'Connection lost before response written @ {}'.format(
self.request.ip))
except Exception as e:
@ -289,7 +289,7 @@ class HttpProtocol(asyncio.Protocol):
await response.stream(
self.request.version, keep_alive, self.request_timeout)
if self.access_log:
netlog.info('', extra={
access_logger.info('', extra={
'status': response.status,
'byte': -1,
'host': '{0}:{1}'.format(self.request.ip[0],
@ -298,13 +298,13 @@ class HttpProtocol(asyncio.Protocol):
self.request.url)
})
except AttributeError:
log.error(
logger.error(
('Invalid response object for url {}, '
'Expected Type: HTTPResponse, Actual Type: {}').format(
self.url, type(response)))
self.write_error(ServerError('Invalid response type'))
except RuntimeError:
log.error(
logger.error(
'Connection lost before response written @ {}'.format(
self.request.ip))
except Exception as e:
@ -325,7 +325,7 @@ class HttpProtocol(asyncio.Protocol):
version = self.request.version if self.request else '1.1'
self.transport.write(response.output(version))
except RuntimeError:
log.error(
logger.error(
'Connection lost before error written @ {}'.format(
self.request.ip if self.request else 'Unknown'))
except Exception as e:
@ -350,21 +350,21 @@ class HttpProtocol(asyncio.Protocol):
extra['request'] = 'nil'
if self.parser and not (self.keep_alive
and extra['status'] == 408):
netlog.info('', extra=extra)
access_logger.info('', extra=extra)
self.transport.close()
def bail_out(self, message, from_error=False):
if from_error or self.transport.is_closing():
log.error(
logger.error(
("Transport closed @ {} and exception "
"experienced during error handling").format(
self.transport.get_extra_info('peername')))
log.debug(
logger.debug(
'Exception:\n{}'.format(traceback.format_exc()))
else:
exception = ServerError(message)
self.write_error(exception)
log.error(message)
logger.error(message)
def cleanup(self):
self.parser = None
@ -508,7 +508,7 @@ def serve(host, port, request_handler, error_handler, before_start=None,
try:
http_server = loop.run_until_complete(server_coroutine)
except:
log.exception("Unable to start server")
logger.exception("Unable to start server")
return
trigger_events(after_start, loop)
@ -519,14 +519,14 @@ def serve(host, port, request_handler, error_handler, before_start=None,
try:
loop.add_signal_handler(_signal, loop.stop)
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.')
pid = os.getpid()
try:
log.info('Starting worker [{}]'.format(pid))
logger.info('Starting worker [{}]'.format(pid))
loop.run_forever()
finally:
log.info("Stopping worker [{}]".format(pid))
logger.info("Stopping worker [{}]".format(pid))
# Run the on_stop function if provided
trigger_events(before_stop, loop)
@ -588,7 +588,7 @@ def serve_multiple(server_settings, workers):
server_settings['port'] = None
def sig_handler(signal, frame):
log.info("Received signal {}. Shutting down.".format(
logger.info("Received signal {}. Shutting down.".format(
Signals(signal).name))
for process in processes:
os.kill(process.pid, SIGINT)

View File

@ -1,7 +1,7 @@
import traceback
from json import JSONDecodeError
from sanic.log import log
from sanic.log import logger
HOST = '127.0.0.1'
PORT = 42101
@ -19,7 +19,7 @@ class SanicTestClient:
url = 'http://{host}:{port}{uri}'.format(
host=HOST, port=PORT, uri=uri)
log.info(url)
logger.info(url)
conn = aiohttp.TCPConnector(verify_ssl=False)
async with aiohttp.ClientSession(
cookies=cookies, connector=conn) as session:
@ -61,7 +61,7 @@ class SanicTestClient:
**request_kwargs)
results[-1] = response
except Exception as e:
log.error(
logger.error(
'Exception:\n{}'.format(traceback.format_exc()))
exceptions.append(e)
self.app.stop()