Skip to main content
 首页 » 编程设计

python之格式化 tornado.access 的默认 Python 日志记录

2025年04月02日13zdz8207

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

请您参考如下方法:

要获得更详细的信息,您需要为您的应用程序提供一个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))