Files
cpp-httplib/docs-src/pages/ja/cookbook/c19-client-logger.md
T
yhirose 9bfd2ddf1c Fix README and docs pages that no longer match the code
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.
2026-10-18 10:13:57 -04:00

2.5 KiB

title, order, status
title order status
C19. クライアントにログを設定する 19 draft

クライアントから送ったリクエストと受け取ったレスポンスをログに残したいときは、set_logger()を使います。エラーだけを拾いたいならset_error_logger()が別に用意されています。

リクエストとレスポンスをログに残す

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()を使います。

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;
});

第2引数のreqはヌルポインタのこともあります。TLSハンドシェイクやCA証明書の読み込み、プロキシのトンネル確立など、接続の準備中にエラーが起きた場合です。使う前に必ずヌルチェックしてください。

両方を組み合わせる

成功時は通常のログ、失敗時はエラーログ、という2本立てにすると便利です。

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: ログコールバックはリクエスト処理と同じスレッドで同期的に呼ばれます。重い処理を入れるとリクエストがその分遅くなるので、必要なら別スレッドのキューに流しましょう。