How to extract status code from uvicorn.access log

61 views Asked by At

I am using fastapi with uvicorn , Currently I am trying to print the logs in json , and I want to extract http status code from uvicron logs , currently its merged in message field, can we extract it and print as separate variable,

    LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'json': {
            '()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
            'fmt': '%(asctime)s %(name)s %(levelname)s %(message)s',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'json',
        },
    },
    'loggers': {
        # Configure the root logger
        '': {
            'handlers': ['console'],
            'level': ROOT_LEVEL,
        },
        # Configure Uvicorn's access log to use JSON
        'uvicorn.access': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        # Configure Uvicorn's error log to use JSON
        'uvicorn.error': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}
logging.config.dictConfig(LOGGING_CONFIG)

Currently logs are printing as

{"asctime": "2024-02-15 13:38:24,713", "name": "uvicorn.access", "levelname": "INFO", "message": "127.0.0.1:33266 - \"POST /v1/example" 404"}

I want to have it like this

{"staus_code": "400","asctime": "2024-02-15 13:38:24,713", "name": "uvicorn.access", "levelname": "INFO", "message": "127.0.0.1:33266 - \"POST /v1/example"}
0

There are 0 answers