Python tornado 之 自定义日志与使用Application的属性

1、自定义日志格式

查看源代码后,可以发现tornado的日志由函数 log_request 控制

因此重写log_request函数,就能实现自定义日志

发现log_request函数中调用一个名称为 handler._request_summary() 的函数

这个函数 request_summary() 是属于handler对象的

所以也改造一下这个函数即可,可以通过vars(handler)查看handler的属性

import os.path

import tornado.ioloop
import tornado.web
from tornado.log import access_log
from tornado.options import define
from tornado.options import options


class MyApplication(tornado.web.Application):
    def __init__(self, ):
        template_path = os.path.join(os.path.dirname(__file__), 'template')
        template_path = os.path.abspath(template_path)
        static_path = os.path.join(template_path, 'static'),
        self.data = dict(a='a', b='b', c='c', d='1', e='2')
        settings = {
            'handlers': [  # 请求路由
                ('/', BaseHandler),
            ],
            'template_path': template_path,  # 模板路径
            'static_path': static_path,  # 静态资源路径
            'debug': True,  # 设置为debug模式
        }
        super().__init__(**settings)

    def log_request(self, handler):
        """Writes a completed HTTP request to the logs.

        By default writes to the python root logger.  To change
        this behavior either subclass Application and override this method,
        or pass a function in the application settings dictionary as
        ``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(),
                   self.handler_info(handler), request_time)

    def handler_info(self, handler):
        # 获取HTTPServerRequest对象的一些属性,因为handler是HTTPServerRequest的对象
        # 可以通过vars(handler)查看它具有的属性
        request = handler.request
        msg = '{} {} {}'.format(request.method, request.uri, request.remote_ip)
        return msg


class BaseHandler(tornado.web.RequestHandler):
    def get(self):
        # 在Application定义的属性,在RequestHandler子类中可以通过self.application.属性访问
        print('Application中的data:{}'.format(self.application.data))
        self.render('base_template.html')


if __name__ == '__main__':
    # 定义端口, 可以全局使用options.port获取,可通过命令行更改
    define('port', default=8080, help='设置启动服务的端口', type=int)
    options.parse_command_line()  # 分析命令行参数

    application = MyApplication()
    # 监听端口8080,可以通过命令行改变,python xxx.py --port=8090
    application.listen(options.port)
    tornado.ioloop.IOLoop.current().start()  # 启动web服务

2、使用Application的属性

通过查看 RequestHandler 类的定义可以看到

该类有一个属性是self.application

所以定义在Application中的属性,可以在RequestHandler子类中使用

import os.path

import tornado.ioloop
import tornado.web
from tornado.options import define
from tornado.options import options


class MyApplication(tornado.web.Application):
    def __init__(self, ):
        template_path = os.path.join(os.path.dirname(__file__), 'template')
        template_path = os.path.abspath(template_path)
        static_path = os.path.join(template_path, 'static'),
        self.data = dict(a='a', b='b', c='c', d='1', e='2')
        settings = {
            'handlers': [  # 请求路由
                ('/', BaseHandler),
            ],
            'template_path': template_path,  # 模板路径
            'static_path': static_path,  # 静态资源路径
            'debug': True,  # 设置为debug模式
        }
        super().__init__(**settings)


class BaseHandler(tornado.web.RequestHandler):
    def get(self):
        # 在Application定义的属性,在RequestHandler子类中可以通过self.application.属性访问
        print('Application中的data:{}'.format(self.application.data))
        self.render('base_template.html')


if __name__ == '__main__':
    # 定义端口, 可以全局使用options.port获取,可通过命令行更改
    define('port', default=8080, help='设置启动服务的端口', type=int)
    options.parse_command_line()  # 分析命令行参数

    application = MyApplication()
    # 监听端口8080,可以通过命令行改变,python xxx.py --port=8090
    application.listen(options.port)
    tornado.ioloop.IOLoop.current().start()  # 启动web服务

 

posted @ 2021-08-06 14:59  南风丶轻语  阅读(543)  评论(0编辑  收藏  举报