Create a HTTP Request Body Log Server within a minute with Docker

  • fennng 

I am playing with telegram bot these two days. I used a google script web app as the web server to handle telegram’s request. I would like to see the requests sent by telegram bot. So I forward the content from telegram to my own server.

function doPost(e){
    var body = JSON.parse(e.postData.contents);
    var payload = preparePayload(body);
    var data = {
        "method": "post",
        "payload": payload
    }
    UrlFetchApp.fetch("https://api.telegram.org/botMyBotKEY/", data);

    var dataFromTelegram = {
        "method": "post",
        "payload": e.postData.contents
    }
    UrlFetchApp.fetch("http://test.dengnz.com", dataFromTelegram);
}

So I need my server to log the request body into a log file. The two tools comes into my mind are nginx and php.

I tried nginx, but to let nginx log HTTP request body, I will either need echo_read_request_body module or fast CGI module. Unfortunately, you cannot add these modules into official nginx docker container. And you have to use newer version of nginx so that you can do json_escape to make sure you don’t see a lot of \x22 in your json log.

I also tried a third party nginx image (nmarus/nginx-full), it worked with some minor config, but it’s an old version of nginx which cannot do json escape.

So I end up with using a docker php server, which is so much easier to setup. It will just take you a minute.

First, create a file call index.php with the following content

<?php $req_dump = print_r($_REQUEST, TRUE);
    $fp = fopen('request.log', 'a');
    fwrite($fp, '['.date("c").']'.$req_dump."\n");
    fclose($fp);
?>

Editing:

I update above php code to the following so that it output a better result

<?php
    $req_dump = file_get_contents('php://input');
    #echo $req_dump;
    $fp = fopen('request.log', 'a');
    fwrite($fp, '['.date("c").']'. "\n" .$req_dump."\n");
    fclose($fp);
?>

Then run the following command within the folder of above file

docker run -it --rm -d -p 80:80 --name phpHTTPLog \
-v "$PWD":/usr/src/myapp -w /usr/src/myapp php:7.0-cli php -S 0.0.0.0:80

If you are behind a nginx-proxy, you may run something like this with your
own config

docker run -it --rm -d -p 8080:80 --name phpHTTPLog \
--network wp-net \
--network-alias httpLog \
-e VIRTUAL_HOST=test.dengnz.com,httpLog.dengnz.com \
-e "LETSENCRYPT_HOST=test.dengnz.com,httpLog.dengnz.com" \
-e "LETSENCRYPT_EMAIL=soody@qq.com" \
-v "$PWD":/usr/src/myapp -w /usr/src/myapp php:7.0-cli php -S 0.0.0.0:80

Now run this command to watch the log file

tail -f request.log

Now you can see all the requests send by telegram bot (or whatever you are
testing)

When you are done, Ctrl+C to exit tail command then run

docker stop phpHTTPLog

to stop and delete the docker container

Note that you may need to add sudo before docker command if you are not
running under root user.

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注