默認(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)方式是:
- 在啟動(dòng)文件(main.py)中創(chuàng)建一個(gè)日志格式類(繼承tornado.log.LogFormatter).
- 重新定義輸出格式(具體請(qǐng)參考下面提供的樣例代碼).
- 重置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秒
...