mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-19 11:19:36 +00:00
A failed request could reach the client's error logger twice: once from the step that failed, without a request when that was the TLS setup or the proxy CONNECT, and again from send_() with the request. A content receiver or progress callback that canceled was reported twice too, a CONNECT answered with 407 only without a request, and a stream that failed to open not at all unless TLS failed. Report a failure in one place instead. The outermost send() reports the request's error once, with the request the caller made, also when the failure happened on a redirect (a redirect client no longer gets the error logger) and when an answer carries an error, such as a proxy's 407. open_stream() reports a stream that fails to open the same way. Only an upload body compressed before send() still reports where it fails.
58 lines
2.7 KiB
Markdown
58 lines
2.7 KiB
Markdown
---
|
|
title: "C19. クライアントにログを設定する"
|
|
order: 19
|
|
status: "draft"
|
|
---
|
|
|
|
クライアントから送ったリクエストと受け取ったレスポンスをログに残したいときは、`set_logger()`を使います。エラーだけを拾いたいなら`set_error_logger()`が別に用意されています。
|
|
|
|
## リクエストとレスポンスをログに残す
|
|
|
|
```cpp
|
|
httplib::Client cli("https://api.example.com");
|
|
|
|
cli.set_logger([](const httplib::Request &req, const httplib::Response &res) {
|
|
std::cout << req.method << " " << req.path
|
|
<< " -> " << res.status << std::endl;
|
|
});
|
|
|
|
auto res = cli.Get("/users");
|
|
```
|
|
|
|
`set_logger()`に渡したコールバックは、リクエストが完了するたびに呼ばれます。リクエストとレスポンスの両方を引数で受け取れるので、メソッドやパス、ステータスコード、ヘッダー、ボディなど好きな情報をログに残せます。
|
|
|
|
## エラーだけを拾う
|
|
|
|
ネットワーク層のエラーが起きたとき(`Error::Connection`など)は、`set_logger()`は呼ばれません。レスポンスが無いからです。こうしたエラーを拾いたいときは`set_error_logger()`を使います。
|
|
|
|
```cpp
|
|
cli.set_error_logger([](const httplib::Error &err, const httplib::Request *req) {
|
|
std::cerr << "error: " << httplib::to_string(err);
|
|
if (req) {
|
|
std::cerr << " (" << req->method << " " << req->path << ")";
|
|
}
|
|
std::cerr << std::endl;
|
|
});
|
|
```
|
|
|
|
失敗したリクエストは、送ったリクエストと一緒に1回だけ報告されます。リダイレクト先で失敗した場合も同じです。`open_stream()`や`stream::Get()`でストリームを開くのに失敗した場合も同じように報告され、ボディを読む途中のエラーは`read_error()`で返ります。`req`がヌルポインタになるのは、どのリクエストにも属さないエラーをサーバーのエラーロガーが受け取るときだけです。
|
|
|
|
## 両方を組み合わせる
|
|
|
|
成功時は通常のログ、失敗時はエラーログ、という2本立てにすると便利です。
|
|
|
|
```cpp
|
|
cli.set_logger([](const auto &req, const auto &res) {
|
|
std::cout << "[ok] " << req.method << " " << req.path
|
|
<< " " << res.status << std::endl;
|
|
});
|
|
|
|
cli.set_error_logger([](const auto &err, const auto *req) {
|
|
std::cerr << "[ng] " << httplib::to_string(err);
|
|
if (req) std::cerr << " " << req->method << " " << req->path;
|
|
std::cerr << std::endl;
|
|
});
|
|
```
|
|
|
|
> **Note:** ログコールバックはリクエスト処理と同じスレッドで同期的に呼ばれます。重い処理を入れるとリクエストがその分遅くなるので、必要なら別スレッドのキューに流しましょう。
|