2016-05-13 121 views
2

我想更改格式默认tornado.access登录格式默认的Python日志记录tornado.access

这是默认的日志格式:

INFO:tornado.access:200 GET/(127.0.0.1) 1.09ms 

这是我的日志记录配置:

LOGGING = { 
    'version': 1, 
    'disable_existing_loggers': False, 
    'formatters': { 
     'verbose_json': { 
      'format': """ 
      { 
       Time: %(asctime)s, 
       Level: %(levelname)s , 
       Name: %(name)s:%(lineno)s, 
       Message: %(message)s 
      } 
      """, 
      'datefmt' : "%d-%b-%Y %H:%M:%S" 
     }, 
    }, 
    'filters': { 
    }, 
    'handlers': { 
     'console': { 
      'level': 'INFO', 
      'class': 'logging.StreamHandler', 
      'formatter': 'verbose_json' 
     }, 
    }, 
    'loggers': { 
     '': { 
      'handlers': ['console'], 
      'level': 'INFO', 
     }, 
    } 
} 

这就是我如何在app.py服务器启动器文件中加载配置文件:

logging.config.dictConfig(LOGGING) 

这个配置生成此格式化日志:

{ 
     Time: 13-May-2016 16:19:03, 
     Level: INFO , 
     Name: tornado.access:1946, 
     Message: 200 POST/(127.0.0.1) 0.93ms 
    } 

但我想它显示为这样的JSON在格式是这样的下方,节点可以包含在内JSON:

{ 
    Time: 13-May-2016 16:19:03,  
    Level: INFO ,  
    Name: tornado.access:1946, 
    Message: { 
    Status_Code: 200, 
    Method: POST, 
    URL: /, 
    Remote_IP: 127.0.0.1, 
    Elapse_Time: 0.93ms 
    } 
} 

回答

1

为了得到更多详细信息,您需要为您的Application提供log_function

def log_function(handler): 
    info = { 
     'Status_Code': handler.get_status(), 
     'Method': handler.request.method, 
     'URL': handler.request.uri, 
     'Remote_IP': handler.request.remote_ip, 
     'Elapsed_Time': '%.2fms' % (handler.request.request_time()*1000) 
    } 
    tornado.log.access_log.info(json.dumps(info, indent=4)) 

# try it out with a dummy application 
app = Application([], log_function=log_function) 
app.listen(8888) 
IOLoop.current().run_sync(lambda: AsyncHTTPClient().fetch(
    'http://localhost:8888/', follow_redirects=False, raise_error=False))