mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-19 11:19:36 +00:00
Bring the READMEs and the docs pages (en and ja) in line with the current header: - Fix the client sample that does not compile, the Transfer-Encoding statement for default headers, the verifier callback comment, the thread pool spawn rule, the sanitize_filename description, and the inverted Accept-Encoding sentence. - Describe recent behaviour: TLS errors behind Read/Write failures, Host validation, Connection: close for a body without length, content_reader rules, refused CONNECT, WebSocketClient proxies, CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and the payload limit of the Stream API. - Complete the API references of WebSocket, WebSocketClient and the stream:: helpers, and the SSE reconnect rules. - Fix cookbook pages: keychain loading on every backend, received Close status, a multipart sample that trusted the client's file name, an echo sample that sent binary as text, SNI, pre-request handler scope, stop() with WebSocket handlers, and the thread pool notes. - Restore the mutex in the LLM app's Chapter 5 code.
71 lines
3.3 KiB
Markdown
71 lines
3.3 KiB
Markdown
---
|
|
title: "S15. リクエストをログに記録する"
|
|
order: 34
|
|
status: "draft"
|
|
---
|
|
|
|
サーバーが受け取ったリクエストと返したレスポンスをログに残したいときは、`Server::set_logger()`を使います。リクエストごとに、レスポンスを書き出す直前に呼ばれるので、アクセスログやメトリクス収集の土台になります。
|
|
|
|
## 基本の使い方
|
|
|
|
```cpp
|
|
svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
|
|
std::cout << req.remote_addr << " "
|
|
<< req.method << " " << req.path
|
|
<< " -> " << res.status << std::endl;
|
|
});
|
|
```
|
|
|
|
ログコールバックには`Request`と`Response`が渡ります。メソッド、パス、ステータスコード、クライアントIP、ヘッダー、ボディなど、好きな情報を取り出せます。
|
|
|
|
`req.path`はパーセントデコード済みなので、CR/LFのような制御文字を含むことがあります。ログファイルに書き出す前にエスケープしてください。そうしないと、細工したリクエストでログの行を偽造されてしまいます。
|
|
|
|
## アクセスログ風のフォーマット
|
|
|
|
Apache / Nginxのアクセスログに似た形式で残す例です。
|
|
|
|
```cpp
|
|
svr.set_logger([](const auto &req, const auto &res) {
|
|
auto now = std::time(nullptr);
|
|
char timebuf[32];
|
|
std::strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S",
|
|
std::localtime(&now));
|
|
|
|
std::cout << timebuf << " "
|
|
<< req.remote_addr << " "
|
|
<< "\"" << req.method << " " << req.path << "\" "
|
|
<< res.status << " "
|
|
<< res.body.size() << "B"
|
|
<< std::endl;
|
|
});
|
|
```
|
|
|
|
マウントポイントから配信するファイルのように、コンテンツプロバイダで送るレスポンスでは、この時点の`res.body`は空なので、サイズは`0B`になります。
|
|
|
|
## 処理時間を測る
|
|
|
|
ログで処理時間を出したいときは、pre-routingハンドラで開始時刻を`res.user_data`に保存しておき、ロガーで差分を取ります。
|
|
|
|
```cpp
|
|
svr.set_pre_routing_handler([](const auto &req, auto &res) {
|
|
res.user_data.set("start", std::chrono::steady_clock::now());
|
|
return httplib::Server::HandlerResponse::Unhandled;
|
|
});
|
|
|
|
svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
|
|
auto *start = res.user_data.get<std::chrono::steady_clock::time_point>("start");
|
|
auto elapsed = start
|
|
? std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
std::chrono::steady_clock::now() - *start).count()
|
|
: 0;
|
|
std::cout << req.method << " " << req.path
|
|
<< " " << res.status << " " << elapsed << "ms" << std::endl;
|
|
});
|
|
```
|
|
|
|
ロガーはレスポンスを書き出す前に呼ばれるので、この時間にボディの送信時間は含まれません。
|
|
|
|
`user_data`の使い方は[S12. `res.user_data`でハンドラ間データを渡す](../s12-user-data)も参照してください。
|
|
|
|
> **Note:** ロガーはリクエスト処理と同じスレッドで同期的に呼ばれ、サーバー内のすべてのロガー呼び出しが1つのロックを共有します。重い処理を直接入れると全体のスループットが落ちるので、必要ならキューに流して非同期で処理しましょう。
|