tornado日志管理

默認(rèn)數(shù)據(jù)格式

默認(rèn)情況下,采用tornado的web框架運(yùn)行起來之后,任何訪問都會(huì)直接在控制臺(tái)輸出日志信息,格式如下:

[I 160807 09:27:17 web:1971] 200 GET / (::1) 7.00ms
[I 160807 09:27:23 web:1971] 200 GET /login (::1) 12.00ms

這條日志的信息量其實(shí)不小,每個(gè)字段的含義分別是:

源數(shù)據(jù) 含義
I INFO
160807 日期
09:27:23 具體時(shí)間
web 模塊名稱
1971 在第幾行執(zhí)行打印輸出的這條日志信息
200 GET / (::1) 7.00ms 輸出的內(nèi)容.

期望數(shù)據(jù)格式

按照我理想中的日志格式,細(xì)化下來應(yīng)該是這個(gè)樣子的:

[2016-08-07 09:38:01 執(zhí)行文件名:執(zhí)行函數(shù)名:執(zhí)行行數(shù) 日志等級(jí)] 內(nèi)容消息

解決辦法

經(jīng)過近3個(gè)小時(shí)的stackoverflow搜索(其實(shí)沒有結(jié)果)、翻看官網(wǎng)介紹以及源碼分析,最終我的實(shí)現(xiàn)方式是:

  1. 在啟動(dòng)文件(main.py)中創(chuàng)建一個(gè)日志格式類(繼承tornado.log.LogFormatter).
  2. 重新定義輸出格式(具體請(qǐng)參考下面提供的樣例代碼).
  3. 重置logger.handlers對(duì)象的LogFormatter對(duì)象.

代碼: tornado_loggerFormatter.py

 -.- coding:utf-8 -.-
# __author__ = 'zhengtong'
import tornado.ioloop
import tornado.web
import tornado.options
import tornado.httpserver
import tornado.concurrent
import tornado.log
import logging
import os

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            ('/', DemoHandler),
        ]

        self.settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            cookie_secret='MEZzzzzzl4NkRWFtb3zzzzg3Y1JMZm5IMnBDcZEXOVhCNXNzzzzRWXJ6ax2d0pzzzz=',
            xsrf_cookies=True,
            compress_response=True,
            login_url='/',
        )
        super(Application, self).__init__(handlers, **self.settings)


class DemoHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.write('hello world!')


class LogFormatter(tornado.log.LogFormatter):

    def __init__(self):
        super(LogFormatter, self).__init__(
            fmt='%(color)s[%(asctime)s %(filename)s:%(funcName)s:%(lineno)d %(levelname)s]%(end_color)s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )


def main():
    tornado.options.define("port", default=80, help="run on the given port", type=int)
    tornado.options.parse_command_line()
    [i.setFormatter(LogFormatter()) for i in logging.getLogger().handlers]
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(tornado.options.options.port)
    tornado.ioloop.IOLoop.current().start()


if __name__ == "__main__":
    main()

輸出結(jié)果

[2016-08-07 09:50:13 web.py:log_request:1971 INFO] 200 GET / (::1) 2.00ms

日志保存致文件

...
...

def main():
    ...
    tornado.options.define("log_file_prefix", default="/tmp/tornado_main.log")
    tornado.options.parse_command_line()
    ...

日志文件按時(shí)間日期分割

...
...

def main():
    ...
    tornado.options.define("log_rotate_mode", default='time')   # 輪詢模式: time or size
    tornado.options.define("log_rotate_when", default='S')      # 單位: S / M / H / D / W0 - W6
    tornado.options.define("log_rotate_interval", default=60)   # 間隔: 60秒
    ...
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 譯者說 Tornado 4.3于2015年11月6日發(fā)布,該版本正式支持Python3.5的async/await...
    TaoBeier閱讀 3,184評(píng)論 0 10
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,688評(píng)論 19 139
  • 在應(yīng)用程序中添加日志記錄總的來說基于三個(gè)目的:監(jiān)視代碼中變量的變化情況,周期性的記錄到文件中供其他應(yīng)用進(jìn)行統(tǒng)計(jì)分析...
    時(shí)待吾閱讀 5,242評(píng)論 1 13
  • 前言 在自動(dòng)化測(cè)試實(shí)踐過程中,必不可少的就是進(jìn)行日志管理,方便調(diào)試和生產(chǎn)問題追蹤,python提供了logg...
    苦葉子閱讀 937評(píng)論 0 0
  • 在應(yīng)用程序中添加日志記錄總的來說基于三個(gè)目的:監(jiān)視代碼中變量的變化情況,周期性的記錄到文件中供其他應(yīng)用進(jìn)行統(tǒng)計(jì)分析...
    時(shí)待吾閱讀 5,164評(píng)論 0 6

友情鏈接更多精彩內(nèi)容