简体   繁体   中英

Format Default Python Logging for tornado.access

I want to change the format for default tornado.access log

this is the default log format:

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

This is my Logging Configuration :

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',
        },
    }
}

and this is how I Load Config File in app.py server initiator file:

logging.config.dictConfig(LOGGING)

This config generates this formated log:

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

But I want to show it as such json where the format is like below and nodes can contain inner 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  
  } 
}

To get more detailed information, you'll need to provide a log_function to your Application :

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM