首页 > 解决方案 > 在日志文件中包含 POST 请求的内容

问题描述

我有一个 HTTP 服务器,它接受表单的 JSON 请求{"a": 3, "b": 4}并生成{"answer": 7}JSON 响应:

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_json)).
:- use_module(library(http/http_log)).

:- http_handler('/', handle_request, []).

% Start server on specified port.
server(Port) :-
    http_server(http_dispatch, [port(Port)]).

% Calculate a + b.
solve(_{a:A, b:B}, _{answer:N}) :-
    number_codes(X, A),  % Convert from string to number.
    number_codes(Y, B),
    N is X + Y.

handle_request(Request) :-
    http_log('~w~n', Request),  % <--- ATTENTION.
    http_read_json_dict(Request, Query),
    solve(Query, Solution),
    reply_json_dict(Solution).

:- server(9000).

我添加了http_log('~w~n', Request)将所有请求记录到文件的行。但是,生成的日志条目不包括发布请求的内容(即{"a": 3, "b": 4}),我希望将其用于调试目的。这是日志文件的样子:

server(started, 1540001234).
/*Wed Oct 24 01:23:45 2018*/ request(1, 1540123456.789, [peer(ip(127,0,0,1)),method(post),request_uri(/),path(/),http_version(1-1),host(localhost),port(9000),user_agent('wizard/1.2.3'),connection('keep-alive'),content_type('application/json'),content_length(20)]).
protocol(http)
completed(1, 0.00123456, 12, 200, ok).

问题是:POST请求的内容如何包含在日志文件中?

标签: prologswi-prolog

解决方案


例如添加以下指令:

:- 初始化(set_setting( http:log_post_data , 2_000))。

要了解更多信息,请参阅add_post_data/2的文档:

如果设置 http:log_post_data 为整数 > 0,内容长度 < 此设置且 nolog_post_content_type/1 在提供的内容类型上不成功,则添加请求字段 post_data(Data)。

推荐阅读