Skip to content
This repository
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 79 lines (69 sloc) 2.119 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "simplehttp.h"

const char *simplehttp_method(struct evhttp_request *req)
{
    const char *method;
    
    switch (req->type) {
        case EVHTTP_REQ_GET:
            method = "GET";
            break;
        case EVHTTP_REQ_POST:
            method = "POST";
            break;
        case EVHTTP_REQ_HEAD:
            method = "HEAD";
            break;
        default:
            method = NULL;
            break;
    }
    
    return method;
}

void simplehttp_log(const char *host, struct evhttp_request *req, uint64_t req_time, const char *id, int display_post)
{
    // NOTE: this is localtime not gmtime
    time_t now;
    struct tm *tm_now;
    char datetime_buf[64];
    char code;
    const char *method;
    char *uri;
    int response_code;
    int type;
    
    time(&now);
    tm_now = localtime(&now);
    strftime(datetime_buf, 64, "%y%m%d %H:%M:%S", tm_now);
    
    if (req) {
        if (req->response_code >= 500 && req->response_code < 600) {
            code = 'E';
        } else if (req->response_code >= 400 && req->response_code < 500) {
            code = 'W';
        } else {
            code = 'I';
        }
        response_code = req->response_code;
        method = simplehttp_method(req);
        uri = req->uri;
        type = req->type;
    } else {
        code = 'E';
        response_code = 0;
        method = "NA";
        uri = "";
        type = -1;
    }
    
    fprintf(stdout, "[%c %s %s] %d %s %s%s", code, datetime_buf, id, response_code, method, host, uri);
    
    if (display_post && (type == EVHTTP_REQ_POST)) {
        if (req->input_buffer == NULL || EVBUFFER_DATA(req->input_buffer) == NULL) {
            fprintf(stdout, "<ERROR req->input_buffer=%p, EVBUFFER_DATA=%p>", req->input_buffer, /* must be */ NULL);
        } else {
            fprintf(stdout, "?");
            fwrite(EVBUFFER_DATA(req->input_buffer), EVBUFFER_LENGTH(req->input_buffer), 1, stdout);
        }
    }
    
    fprintf(stdout, " %.3fms\n", req_time / 1000.0);
}
Something went wrong with that request. Please try again.