【问题标题】:Format Default Python Logging for tornado.access为 tornado.access 格式化默认 Python 日志记录
【发布时间】:2016-05-13 10:48:27
【问题描述】:

我想更改默认 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  
  } 
}

【问题讨论】:

    标签: python json logging tornado


    【解决方案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))
    

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多