summaryrefslogtreecommitdiff
path: root/http
diff options
context:
space:
mode:
authorEd Tanous <ed@tanous.net>2023-07-18 03:06:25 +0300
committerEd Tanous <ed@tanous.net>2023-07-20 01:38:41 +0300
commit62598e31d0988d589506d5091bd38f72d61faf5e (patch)
treee3e548632da934083c21cc1262f8b9d8f255f2a9 /http
parent609ba4c9ffb9c6b83861ff557108c89007ca369a (diff)
downloadbmcweb-62598e31d0988d589506d5091bd38f72d61faf5e.tar.xz
Replace logging with std::format
std::format is a much more modern logging solution, and gives us a lot more flexibility, and better compile times when doing logging. Unfortunately, given its level of compile time checks, it needs to be a method, instead of the stream style logging we had before. This requires a pretty substantial change. Fortunately, this change can be largely automated, via the script included in this commit under scripts/replace_logs.py. This is to aid people in moving their patchsets over to the new form in the short period where old patches will be based on the old logging. The intention is that this script eventually goes away. The old style logging (stream based) looked like. BMCWEB_LOG_DEBUG << "Foo " << foo; The new equivalent of the above would be: BMCWEB_LOG_DEBUG("Foo {}", foo); In the course of doing this, this also cleans up several ignored linter errors, including macro usage, and array to pointer deconstruction. Note, This patchset does remove the timestamp from the log message. In practice, this was duplicated between journald and bmcweb, and there's no need for both to exist. One design decision of note is the addition of logPtr. Because the compiler can't disambiguate between const char* and const MyThing*, it's necessary to add an explicit cast to void*. This is identical to how fmt handled it. Tested: compiled with logging meson_option enabled, and launched bmcweb Saw the usual logging, similar to what was present before: ``` [Error include/webassets.hpp:60] Unable to find or open /usr/share/www/ static file hosting disabled [Debug include/persistent_data.hpp:133] Restored Session Timeout: 1800 [Debug redfish-core/include/event_service_manager.hpp:671] Old eventService config not exist [Info src/webserver_main.cpp:59] Starting webserver on port 18080 [Error redfish-core/include/event_service_manager.hpp:1301] inotify_add_watch failed for redfish log file. [Info src/webserver_main.cpp:137] Start Hostname Monitor Service... ``` Signed-off-by: Ed Tanous <ed@tanous.net> Change-Id: I86a46aa2454be7fe80df608cb7e5573ca4029ec8
Diffstat (limited to 'http')
-rw-r--r--http/app.hpp6
-rw-r--r--http/complete_response_fields.hpp4
-rw-r--r--http/http2_connection.hpp90
-rw-r--r--http/http_client.hpp191
-rw-r--r--http/http_connection.hpp107
-rw-r--r--http/http_response.hpp24
-rw-r--r--http/http_server.hpp16
-rw-r--r--http/logging.hpp273
-rw-r--r--http/mutual_tls.hpp35
-rw-r--r--http/nghttp2_adapters.hpp2
-rw-r--r--http/parsing.hpp4
-rw-r--r--http/routing.hpp45
-rw-r--r--http/routing/websocketrule.hpp4
-rw-r--r--http/server_sent_event.hpp38
-rw-r--r--http/websocket.hpp22
15 files changed, 470 insertions, 391 deletions
diff --git a/http/app.hpp b/http/app.hpp
index 0f0f47b80f..d9c88b9563 100644
--- a/http/app.hpp
+++ b/http/app.hpp
@@ -144,7 +144,7 @@ class App
void debugPrint()
{
- BMCWEB_LOG_DEBUG << "Routing:";
+ BMCWEB_LOG_DEBUG("Routing:");
router.debugPrint();
}
@@ -162,8 +162,8 @@ class App
App& ssl(std::shared_ptr<boost::asio::ssl::context>&& ctx)
{
sslContext = std::move(ctx);
- BMCWEB_LOG_INFO << "app::ssl context use_count="
- << sslContext.use_count();
+ BMCWEB_LOG_INFO("app::ssl context use_count={}",
+ sslContext.use_count());
return *this;
}
diff --git a/http/complete_response_fields.hpp b/http/complete_response_fields.hpp
index 1819db59b5..66a4bb79af 100644
--- a/http/complete_response_fields.hpp
+++ b/http/complete_response_fields.hpp
@@ -20,8 +20,8 @@ namespace crow
inline void completeResponseFields(const Request& req, Response& res)
{
- BMCWEB_LOG_INFO << "Response: " << ' ' << req.url().encoded_path() << ' '
- << res.resultInt();
+ BMCWEB_LOG_INFO("Response: {} {}", req.url().encoded_path(),
+ res.resultInt());
addSecurityHeaders(req, res);
authentication::cleanupTempSession(req);
diff --git a/http/http2_connection.hpp b/http/http2_connection.hpp
index dad5089731..a63b234575 100644
--- a/http/http2_connection.hpp
+++ b/http/http2_connection.hpp
@@ -66,7 +66,7 @@ class HTTP2Connection :
if (sendServerConnectionHeader() != 0)
{
- BMCWEB_LOG_ERROR << "send_server_connection_header failed";
+ BMCWEB_LOG_ERROR("send_server_connection_header failed");
return;
}
doRead();
@@ -74,7 +74,7 @@ class HTTP2Connection :
int sendServerConnectionHeader()
{
- BMCWEB_LOG_DEBUG << "send_server_connection_header()";
+ BMCWEB_LOG_DEBUG("send_server_connection_header()");
uint32_t maxStreams = 4;
std::array<nghttp2_settings_entry, 2> iv = {
@@ -83,7 +83,7 @@ class HTTP2Connection :
int rv = ngSession.submitSettings(iv);
if (rv != 0)
{
- BMCWEB_LOG_ERROR << "Fatal error: " << nghttp2_strerror(rv);
+ BMCWEB_LOG_ERROR("Fatal error: {}", nghttp2_strerror(rv));
return -1;
}
return 0;
@@ -97,20 +97,20 @@ class HTTP2Connection :
{
if (source == nullptr || source->ptr == nullptr)
{
- BMCWEB_LOG_DEBUG << "Source was null???";
+ BMCWEB_LOG_DEBUG("Source was null???");
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
- BMCWEB_LOG_DEBUG << "File read callback length: " << length;
+ BMCWEB_LOG_DEBUG("File read callback length: {}", length);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Http2StreamData* str = reinterpret_cast<Http2StreamData*>(source->ptr);
crow::Response& res = str->res;
- BMCWEB_LOG_DEBUG << "total: " << res.body().size()
- << " send_sofar: " << str->sentSofar;
+ BMCWEB_LOG_DEBUG("total: {} send_sofar: {}", res.body().size(),
+ str->sentSofar);
size_t toSend = std::min(res.body().size() - str->sentSofar, length);
- BMCWEB_LOG_DEBUG << "Copying " << toSend << " bytes to buf";
+ BMCWEB_LOG_DEBUG("Copying {} bytes to buf", toSend);
std::string::iterator bodyBegin = res.body().begin();
std::advance(bodyBegin, str->sentSofar);
@@ -120,7 +120,7 @@ class HTTP2Connection :
if (str->sentSofar >= res.body().size())
{
- BMCWEB_LOG_DEBUG << "Setting OEF flag";
+ BMCWEB_LOG_DEBUG("Setting OEF flag");
*dataFlags |= NGHTTP2_DATA_FLAG_EOF;
//*dataFlags |= NGHTTP2_DATA_FLAG_NO_COPY;
}
@@ -138,7 +138,7 @@ class HTTP2Connection :
int sendResponse(Response& completedRes, int32_t streamId)
{
- BMCWEB_LOG_DEBUG << "send_response stream_id:" << streamId;
+ BMCWEB_LOG_DEBUG("send_response stream_id:{}", streamId);
auto it = streams.find(streamId);
if (it == streams.end())
@@ -175,7 +175,7 @@ class HTTP2Connection :
int rv = ngSession.submitResponse(streamId, hdr, &dataPrd);
if (rv != 0)
{
- BMCWEB_LOG_ERROR << "Fatal error: " << nghttp2_strerror(rv);
+ BMCWEB_LOG_ERROR("Fatal error: {}", nghttp2_strerror(rv));
close();
return -1;
}
@@ -201,7 +201,7 @@ class HTTP2Connection :
int onRequestRecv(int32_t streamId)
{
- BMCWEB_LOG_DEBUG << "on_request_recv";
+ BMCWEB_LOG_DEBUG("on_request_recv");
auto it = streams.find(streamId);
if (it == streams.end())
@@ -211,14 +211,14 @@ class HTTP2Connection :
}
crow::Request& thisReq = it->second->req;
- BMCWEB_LOG_DEBUG << "Handling " << &thisReq << " \""
- << thisReq.url().encoded_path() << "\"";
+ BMCWEB_LOG_DEBUG("Handling {} \"{}\"", logPtr(&thisReq),
+ thisReq.url().encoded_path());
crow::Response& thisRes = it->second->res;
thisRes.setCompleteRequestHandler(
[this, streamId](Response& completeRes) {
- BMCWEB_LOG_DEBUG << "res.completeRequestHandler called";
+ BMCWEB_LOG_DEBUG("res.completeRequestHandler called");
if (sendResponse(completeRes, streamId) != 0)
{
close();
@@ -234,7 +234,7 @@ class HTTP2Connection :
int onFrameRecvCallback(const nghttp2_frame& frame)
{
- BMCWEB_LOG_DEBUG << "frame type " << static_cast<int>(frame.hd.type);
+ BMCWEB_LOG_DEBUG("frame type {}", static_cast<int>(frame.hd.type));
switch (frame.hd.type)
{
case NGHTTP2_DATA:
@@ -255,15 +255,15 @@ class HTTP2Connection :
const nghttp2_frame* frame,
void* userData)
{
- BMCWEB_LOG_DEBUG << "on_frame_recv_callback";
+ BMCWEB_LOG_DEBUG("on_frame_recv_callback");
if (userData == nullptr)
{
- BMCWEB_LOG_CRITICAL << "user data was null?";
+ BMCWEB_LOG_CRITICAL("user data was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
if (frame == nullptr)
{
- BMCWEB_LOG_CRITICAL << "frame was null?";
+ BMCWEB_LOG_CRITICAL("frame was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
return userPtrToSelf(userData).onFrameRecvCallback(*frame);
@@ -281,10 +281,10 @@ class HTTP2Connection :
int32_t streamId,
uint32_t /*unused*/, void* userData)
{
- BMCWEB_LOG_DEBUG << "on_stream_close_callback stream " << streamId;
+ BMCWEB_LOG_DEBUG("on_stream_close_callback stream {}", streamId);
if (userData == nullptr)
{
- BMCWEB_LOG_CRITICAL << "user data was null?";
+ BMCWEB_LOG_CRITICAL("user data was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
auto stream = userPtrToSelf(userData).streams.find(streamId);
@@ -308,8 +308,8 @@ class HTTP2Connection :
std::string_view valueSv(reinterpret_cast<const char*>(value.data()),
value.size());
- BMCWEB_LOG_DEBUG << "on_header_callback name: " << nameSv << " value "
- << valueSv;
+ BMCWEB_LOG_DEBUG("on_header_callback name: {} value {}", nameSv,
+ valueSv);
switch (frame.hd.type)
{
@@ -321,7 +321,7 @@ class HTTP2Connection :
auto thisStream = streams.find(frame.hd.stream_id);
if (thisStream == streams.end())
{
- BMCWEB_LOG_ERROR << "Unknown stream" << frame.hd.stream_id;
+ BMCWEB_LOG_ERROR("Unknown stream{}", frame.hd.stream_id);
close();
return -1;
}
@@ -338,7 +338,7 @@ class HTTP2Connection :
boost::beast::http::string_to_verb(valueSv);
if (verb == boost::beast::http::verb::unknown)
{
- BMCWEB_LOG_ERROR << "Unknown http verb " << valueSv;
+ BMCWEB_LOG_ERROR("Unknown http verb {}", valueSv);
close();
return -1;
}
@@ -365,22 +365,22 @@ class HTTP2Connection :
{
if (userData == nullptr)
{
- BMCWEB_LOG_CRITICAL << "user data was null?";
+ BMCWEB_LOG_CRITICAL("user data was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
if (frame == nullptr)
{
- BMCWEB_LOG_CRITICAL << "frame was null?";
+ BMCWEB_LOG_CRITICAL("frame was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
if (name == nullptr)
{
- BMCWEB_LOG_CRITICAL << "name was null?";
+ BMCWEB_LOG_CRITICAL("name was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
if (value == nullptr)
{
- BMCWEB_LOG_CRITICAL << "value was null?";
+ BMCWEB_LOG_CRITICAL("value was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
return userPtrToSelf(userData).onHeaderCallback(*frame, {name, namelen},
@@ -392,7 +392,7 @@ class HTTP2Connection :
if (frame.hd.type == NGHTTP2_HEADERS &&
frame.headers.cat == NGHTTP2_HCAT_REQUEST)
{
- BMCWEB_LOG_DEBUG << "create stream for id " << frame.hd.stream_id;
+ BMCWEB_LOG_DEBUG("create stream for id {}", frame.hd.stream_id);
std::pair<boost::container::flat_map<
int32_t, std::unique_ptr<Http2StreamData>>::iterator,
@@ -409,15 +409,15 @@ class HTTP2Connection :
const nghttp2_frame* frame,
void* userData)
{
- BMCWEB_LOG_DEBUG << "on_begin_headers_callback";
+ BMCWEB_LOG_DEBUG("on_begin_headers_callback");
if (userData == nullptr)
{
- BMCWEB_LOG_CRITICAL << "user data was null?";
+ BMCWEB_LOG_CRITICAL("user data was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
if (frame == nullptr)
{
- BMCWEB_LOG_CRITICAL << "frame was null?";
+ BMCWEB_LOG_CRITICAL("frame was null?");
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
return userPtrToSelf(userData).onBeginHeadersCallback(*frame);
@@ -428,7 +428,7 @@ class HTTP2Connection :
size_t sendLength)
{
self->isWriting = false;
- BMCWEB_LOG_DEBUG << "Sent " << sendLength;
+ BMCWEB_LOG_DEBUG("Sent {}", sendLength);
if (ec)
{
self->close();
@@ -457,7 +457,7 @@ class HTTP2Connection :
ssize_t onSendCallback(nghttp2_session* /*session */, const uint8_t* data,
size_t length, int /* flags */)
{
- BMCWEB_LOG_DEBUG << "On send callback size=" << length;
+ BMCWEB_LOG_DEBUG("On send callback size={}", length);
size_t copied = boost::asio::buffer_copy(
sendBuffer.prepare(length), boost::asio::buffer(data, length));
sendBuffer.commit(copied);
@@ -489,20 +489,20 @@ class HTTP2Connection :
void doRead()
{
- BMCWEB_LOG_DEBUG << this << " doRead";
+ BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
adaptor.async_read_some(
inBuffer.prepare(8192),
[this, self(shared_from_this())](
const boost::system::error_code& ec, size_t bytesTransferred) {
- BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
- << " Bytes";
+ BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
+ bytesTransferred);
if (ec)
{
- BMCWEB_LOG_ERROR << this
- << " Error while reading: " << ec.message();
+ BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
+ ec.message());
close();
- BMCWEB_LOG_DEBUG << this << " from read(1)";
+ BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
return;
}
inBuffer.commit(bytesTransferred);
@@ -513,13 +513,13 @@ class HTTP2Connection :
std::span<const uint8_t> bufferSpan{
std::bit_cast<const uint8_t*>(bufferIt.data()),
bufferIt.size()};
- BMCWEB_LOG_DEBUG << "http2 is getting " << bufferSpan.size()
- << " bytes";
+ BMCWEB_LOG_DEBUG("http2 is getting {} bytes",
+ bufferSpan.size());
ssize_t readLen = ngSession.memRecv(bufferSpan);
if (readLen <= 0)
{
- BMCWEB_LOG_ERROR << "nghttp2_session_mem_recv returned "
- << readLen;
+ BMCWEB_LOG_ERROR("nghttp2_session_mem_recv returned {}",
+ readLen);
close();
return;
}
diff --git a/http/http_client.hpp b/http/http_client.hpp
index 07fa85d6f9..d82c566a06 100644
--- a/http/http_client.hpp
+++ b/http/http_client.hpp
@@ -84,7 +84,7 @@ static inline boost::system::error_code
defaultRetryHandler(unsigned int respCode)
{
// As a default, assume 200X is alright
- BMCWEB_LOG_DEBUG << "Using default check for response code validity";
+ BMCWEB_LOG_DEBUG("Using default check for response code validity");
if ((respCode < 200) || (respCode >= 300))
{
return boost::system::errc::make_error_code(
@@ -165,9 +165,8 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
void doResolve()
{
state = ConnState::resolveInProgress;
- BMCWEB_LOG_DEBUG << "Trying to resolve: " << host << ":"
- << std::to_string(port)
- << ", id: " << std::to_string(connId);
+ BMCWEB_LOG_DEBUG("Trying to resolve: {}:{}, id: {}", host,
+ std::to_string(port), std::to_string(connId));
resolver.async_resolve(host, std::to_string(port),
std::bind_front(&ConnectionInfo::afterResolve,
@@ -180,19 +179,18 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
{
if (ec || (endpointList.empty()))
{
- BMCWEB_LOG_ERROR << "Resolve failed: " << ec.message() << " "
- << host << ":" << std::to_string(port);
+ BMCWEB_LOG_ERROR("Resolve failed: {} {}:{}", ec.message(), host,
+ std::to_string(port));
state = ConnState::resolveFailed;
waitAndRetry();
return;
}
- BMCWEB_LOG_DEBUG << "Resolved " << host << ":" << std::to_string(port)
- << ", id: " << std::to_string(connId);
+ BMCWEB_LOG_DEBUG("Resolved {}:{}, id: {}", host, std::to_string(port),
+ std::to_string(connId));
state = ConnState::connectInProgress;
- BMCWEB_LOG_DEBUG << "Trying to connect to: " << host << ":"
- << std::to_string(port)
- << ", id: " << std::to_string(connId);
+ BMCWEB_LOG_DEBUG("Trying to connect to: {}:{}, id: {}", host,
+ std::to_string(port), std::to_string(connId));
timer.expires_after(std::chrono::seconds(30));
timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
@@ -217,17 +215,17 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
timer.cancel();
if (ec)
{
- BMCWEB_LOG_ERROR << "Connect " << endpoint.address().to_string()
- << ":" << std::to_string(endpoint.port())
- << ", id: " << std::to_string(connId)
- << " failed: " << ec.message();
+ BMCWEB_LOG_ERROR("Connect {}:{}, id: {} failed: {}",
+ endpoint.address().to_string(),
+ std::to_string(endpoint.port()),
+ std::to_string(connId), ec.message());
state = ConnState::connectFailed;
waitAndRetry();
return;
}
- BMCWEB_LOG_DEBUG << "Connected to: " << endpoint.address().to_string()
- << ":" << std::to_string(endpoint.port())
- << ", id: " << std::to_string(connId);
+ BMCWEB_LOG_DEBUG(
+ "Connected to: {}:{}, id: {}", endpoint.address().to_string(),
+ std::to_string(endpoint.port()), std::to_string(connId));
if (sslConn)
{
doSslHandshake();
@@ -265,15 +263,14 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
timer.cancel();
if (ec)
{
- BMCWEB_LOG_ERROR << "SSL Handshake failed -"
- << " id: " << std::to_string(connId)
- << " error: " << ec.message();
+ BMCWEB_LOG_ERROR("SSL Handshake failed - id: {} error: {}",
+ std::to_string(connId), ec.message());
state = ConnState::handshakeFailed;
waitAndRetry();
return;
}
- BMCWEB_LOG_DEBUG << "SSL Handshake successful -"
- << " id: " << std::to_string(connId);
+ BMCWEB_LOG_DEBUG("SSL Handshake successful - id: {}",
+ std::to_string(connId));
state = ConnState::connected;
sendMessage();
}
@@ -316,14 +313,14 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
timer.cancel();
if (ec)
{
- BMCWEB_LOG_ERROR << "sendMessage() failed: " << ec.message() << " "
- << host << ":" << std::to_string(port);
+ BMCWEB_LOG_ERROR("sendMessage() failed: {} {}:{}", ec.message(),
+ host, std::to_string(port));
state = ConnState::sendFailed;
waitAndRetry();
return;
}
- BMCWEB_LOG_DEBUG << "sendMessage() bytes transferred: "
- << bytesTransferred;
+ BMCWEB_LOG_DEBUG("sendMessage() bytes transferred: {}",
+ bytesTransferred);
recvMessage();
}
@@ -370,28 +367,28 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
timer.cancel();
if (ec && ec != boost::asio::ssl::error::stream_truncated)
{
- BMCWEB_LOG_ERROR << "recvMessage() failed: " << ec.message()
- << " from " << host << ":" << std::to_string(port);
+ BMCWEB_LOG_ERROR("recvMessage() failed: {} from {}:{}",
+ ec.message(), host, std::to_string(port));
state = ConnState::recvFailed;
waitAndRetry();
return;
}
- BMCWEB_LOG_DEBUG << "recvMessage() bytes transferred: "
- << bytesTransferred;
- BMCWEB_LOG_DEBUG << "recvMessage() data: " << parser->get().body();
+ BMCWEB_LOG_DEBUG("recvMessage() bytes transferred: {}",
+ bytesTransferred);
+ BMCWEB_LOG_DEBUG("recvMessage() data: {}", parser->get().body());
unsigned int respCode = parser->get().result_int();
- BMCWEB_LOG_DEBUG << "recvMessage() Header Response Code: " << respCode;
+ BMCWEB_LOG_DEBUG("recvMessage() Header Response Code: {}", respCode);
// Make sure the received response code is valid as defined by
// the associated retry policy
if (connPolicy->invalidResp(respCode))
{
// The listener failed to receive the Sent-Event
- BMCWEB_LOG_ERROR << "recvMessage() Listener Failed to "
- "receive Sent-Event. Header Response Code: "
- << respCode << " from " << host << ":"
- << std::to_string(port);
+ BMCWEB_LOG_ERROR(
+ "recvMessage() Listener Failed to "
+ "receive Sent-Event. Header Response Code: {} from {}:{}",
+ respCode, host, std::to_string(port));
state = ConnState::recvFailed;
waitAndRetry();
return;
@@ -403,8 +400,7 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
// Keep the connection alive if server supports it
// Else close the connection
- BMCWEB_LOG_DEBUG << "recvMessage() keepalive : "
- << parser->keep_alive();
+ BMCWEB_LOG_DEBUG("recvMessage() keepalive : {}", parser->keep_alive());
// Copy the response into a Response object so that it can be
// processed by the callback function.
@@ -418,13 +414,13 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
{
if (ec == boost::asio::error::operation_aborted)
{
- BMCWEB_LOG_DEBUG
- << "async_wait failed since the operation is aborted";
+ BMCWEB_LOG_DEBUG(
+ "async_wait failed since the operation is aborted");
return;
}
if (ec)
{
- BMCWEB_LOG_ERROR << "async_wait failed: " << ec.message();
+ BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
// If the timer fails, we need to close the socket anyway, same as
// if it expired.
}
@@ -441,10 +437,9 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
if ((retryCount >= connPolicy->maxRetryAttempts) ||
(state == ConnState::sslInitFailed))
{
- BMCWEB_LOG_ERROR << "Maximum number of retries reached."
- << " " << host << ":" << std::to_string(port);
- BMCWEB_LOG_DEBUG << "Retry policy: "
- << connPolicy->retryPolicyAction;
+ BMCWEB_LOG_ERROR("Maximum number of retries reached. {}:{}", host,
+ std::to_string(port));
+ BMCWEB_LOG_DEBUG("Retry policy: {}", connPolicy->retryPolicyAction);
if (connPolicy->retryPolicyAction == "TerminateAfterRetries")
{
@@ -470,10 +465,9 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
retryCount++;
- BMCWEB_LOG_DEBUG << "Attempt retry after "
- << std::to_string(
- connPolicy->retryIntervalSecs.count())
- << " seconds. RetryCount = " << retryCount;
+ BMCWEB_LOG_DEBUG("Attempt retry after {} seconds. RetryCount = {}",
+ std::to_string(connPolicy->retryIntervalSecs.count()),
+ retryCount);
timer.expires_after(connPolicy->retryIntervalSecs);
timer.async_wait(std::bind_front(&ConnectionInfo::onTimerDone, this,
shared_from_this()));
@@ -484,13 +478,13 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
{
if (ec == boost::asio::error::operation_aborted)
{
- BMCWEB_LOG_DEBUG
- << "async_wait failed since the operation is aborted"
- << ec.message();
+ BMCWEB_LOG_DEBUG(
+ "async_wait failed since the operation is aborted{}",
+ ec.message());
}
else if (ec)
{
- BMCWEB_LOG_ERROR << "async_wait failed: " << ec.message();
+ BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
// Ignore the error and continue the retry loop to attempt
// sending the event as per the retry policy
}
@@ -508,15 +502,14 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
// not_connected happens sometimes so don't bother reporting it.
if (ec && ec != boost::beast::errc::not_connected)
{
- BMCWEB_LOG_ERROR << host << ":" << std::to_string(port)
- << ", id: " << std::to_string(connId)
- << " shutdown failed: " << ec.message();
+ BMCWEB_LOG_ERROR("{}:{}, id: {} shutdown failed: {}", host,
+ std::to_string(port), std::to_string(connId),
+ ec.message());
}
else
{
- BMCWEB_LOG_DEBUG << host << ":" << std::to_string(port)
- << ", id: " << std::to_string(connId)
- << " closed gracefully";
+ BMCWEB_LOG_DEBUG("{}:{}, id: {} closed gracefully", host,
+ std::to_string(port), std::to_string(connId));
}
if (retry)
@@ -549,15 +542,14 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
{
if (ec)
{
- BMCWEB_LOG_ERROR << host << ":" << std::to_string(port)
- << ", id: " << std::to_string(connId)
- << " shutdown failed: " << ec.message();
+ BMCWEB_LOG_ERROR("{}:{}, id: {} shutdown failed: {}", host,
+ std::to_string(port), std::to_string(connId),
+ ec.message());
}
else
{
- BMCWEB_LOG_DEBUG << host << ":" << std::to_string(port)
- << ", id: " << std::to_string(connId)
- << " closed gracefully";
+ BMCWEB_LOG_DEBUG("{}:{}, id: {} closed gracefully", host,
+ std::to_string(port), std::to_string(connId));
}
shutdownConn(retry);
}
@@ -583,9 +575,9 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
boost::beast::error_code ec{static_cast<int>(::ERR_get_error()),
boost::asio::error::get_ssl_category()};
- BMCWEB_LOG_ERROR << "SSL_set_tlsext_host_name " << host << ":"
- << port << ", id: " << std::to_string(connId)
- << " failed: " << ec.message();
+ BMCWEB_LOG_ERROR(
+ "SSL_set_tlsext_host_name {}:{}, id: {} failed: {}", host, port,
+ std::to_string(connId), ec.message());
// Set state as sslInit failed so that we close the connection
// and take appropriate action as per retry configuration.
state = ConnState::sslInitFailed;
@@ -611,8 +603,8 @@ class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
if (!sslCtx)
{
- BMCWEB_LOG_ERROR << "prepareSSLContext failed - " << host << ":"
- << port << ", id: " << std::to_string(connId);
+ BMCWEB_LOG_ERROR("prepareSSLContext failed - {}:{}, id: {}",
+ host, port, std::to_string(connId));
// Don't retry if failure occurs while preparing SSL context
// such as certificate is invalid or set cipher failure or set
// host name failure etc... Setting conn state to sslInitFailed
@@ -648,8 +640,8 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
{
if (requestQueue.empty())
{
- BMCWEB_LOG_ERROR
- << "setConnProps() should not have been called when requestQueue is empty";
+ BMCWEB_LOG_ERROR(
+ "setConnProps() should not have been called when requestQueue is empty");
return;
}
@@ -657,9 +649,9 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
conn.req = std::move(nextReq.req);
conn.callback = std::move(nextReq.callback);
- BMCWEB_LOG_DEBUG << "Setting properties for connection " << conn.host
- << ":" << std::to_string(conn.port)
- << ", id: " << std::to_string(conn.connId);
+ BMCWEB_LOG_DEBUG("Setting properties for connection {}:{}, id: {}",
+ conn.host, std::to_string(conn.port),
+ std::to_string(conn.connId));
// We can remove the request from the queue at this point
requestQueue.pop_front();
@@ -680,11 +672,10 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
// Reuse the connection to send the next request in the queue
if (!requestQueue.empty())
{
- BMCWEB_LOG_DEBUG << std::to_string(requestQueue.size())
- << " requests remaining in queue for " << destIP
- << ":" << std::to_string(destPort)
- << ", reusing connnection "
- << std::to_string(connId);
+ BMCWEB_LOG_DEBUG(
+ "{} requests remaining in queue for {}:{}, reusing connnection {}",
+ std::to_string(requestQueue.size()), destIP,
+ std::to_string(destPort), std::to_string(connId));
setConnProps(*conn);
@@ -744,14 +735,13 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
if (conn->state == ConnState::idle)
{
- BMCWEB_LOG_DEBUG << "Grabbing idle connection "
- << commonMsg;
+ BMCWEB_LOG_DEBUG("Grabbing idle connection {}", commonMsg);
conn->sendMessage();
}
else
{
- BMCWEB_LOG_DEBUG << "Reusing existing connection "
- << commonMsg;
+ BMCWEB_LOG_DEBUG("Reusing existing connection {}",
+ commonMsg);
conn->doResolve();
}
return;
@@ -762,8 +752,8 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
// the queue
if (connections.size() < connPolicy->maxConnections)
{
- BMCWEB_LOG_DEBUG << "Adding new connection to pool " << destIP
- << ":" << std::to_string(destPort);
+ BMCWEB_LOG_DEBUG("Adding new connection to pool {}:{}", destIP,
+ std::to_string(destPort));
auto conn = addConnection();
conn->req = std::move(thisReq);
conn->callback = std::move(cb);
@@ -771,16 +761,17 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
}
else if (requestQueue.size() < maxRequestQueueSize)
{
- BMCWEB_LOG_ERROR << "Max pool size reached. Adding data to queue."
- << destIP << ":" << std::to_string(destPort);
+ BMCWEB_LOG_ERROR(
+ "Max pool size reached. Adding data to queue.{}:{}", destIP,
+ std::to_string(destPort));
requestQueue.emplace_back(std::move(thisReq), std::move(cb));
}
else
{
// If we can't buffer the request then we should let the callback
// handle a 429 Too Many Requests dummy response
- BMCWEB_LOG_ERROR << destIP << ":" << std::to_string(destPort)
- << " request queue full. Dropping request.";
+ BMCWEB_LOG_ERROR("{}:{} request queue full. Dropping request.",
+ destIP, std::to_string(destPort));
Response dummyRes;
dummyRes.result(boost::beast::http::status::too_many_requests);
resHandler(dummyRes);
@@ -801,7 +792,8 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
std::shared_ptr<ConnectionPool> self = weakSelf.lock();
if (!self)
{
- BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
+ BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
+ logPtr(self.get()));
return;
}
@@ -815,10 +807,9 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
auto& ret = connections.emplace_back(std::make_shared<ConnectionInfo>(
ioc, id, connPolicy, destIP, destPort, useSSL, newId));
- BMCWEB_LOG_DEBUG << "Added connection "
- << std::to_string(connections.size() - 1)
- << " to pool " << destIP << ":"
- << std::to_string(destPort);
+ BMCWEB_LOG_DEBUG("Added connection {} to pool {}:{}",
+ std::to_string(connections.size() - 1), destIP,
+ std::to_string(destPort));
return ret;
}
@@ -832,8 +823,8 @@ class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
id(idIn), connPolicy(connPolicyIn), destIP(destIPIn),
destPort(destPortIn), useSSL(useSSLIn)
{
- BMCWEB_LOG_DEBUG << "Initializing connection pool for " << destIP << ":"
- << std::to_string(destPort);
+ BMCWEB_LOG_DEBUG("Initializing connection pool for {}:{}", destIP,
+ std::to_string(destPort));
// Initialize the pool with a single connection
addConnection();
@@ -852,8 +843,8 @@ class HttpClient
// sendDataWithCallback()
static void genericResHandler(const Response& res)
{
- BMCWEB_LOG_DEBUG << "Response handled with return code: "
- << std::to_string(res.resultInt());
+ BMCWEB_LOG_DEBUG("Response handled with return code: {}",
+ std::to_string(res.resultInt()));
}
public:
diff --git a/http/http_connection.hpp b/http/http_connection.hpp
index cb252f96aa..b5d0d2e59e 100644
--- a/http/http_connection.hpp
+++ b/http/http_connection.hpp
@@ -68,8 +68,8 @@ class Connection :
connectionCount++;
- BMCWEB_LOG_DEBUG << this << " Connection open, total "
- << connectionCount;
+ BMCWEB_LOG_DEBUG("{} Connection open, total {}", logPtr(this),
+ connectionCount);
}
~Connection()
@@ -78,8 +78,8 @@ class Connection :
cancelDeadlineTimer();
connectionCount--;
- BMCWEB_LOG_DEBUG << this << " Connection closed, total "
- << connectionCount;
+ BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
+ connectionCount);
}
Connection(const Connection&) = delete;
@@ -97,9 +97,8 @@ class Connection :
mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
if (mtlsSession)
{
- BMCWEB_LOG_DEBUG
- << this
- << " Generating TLS session: " << mtlsSession->uniqueId;
+ BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
+ mtlsSession->uniqueId);
}
}
return true;
@@ -126,7 +125,7 @@ class Connection :
static_cast<unsigned int>(id.length()));
if (ret == 0)
{
- BMCWEB_LOG_ERROR << this << " failed to set SSL id";
+ BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
}
}
@@ -143,7 +142,8 @@ class Connection :
{
if (connectionCount >= 100)
{
- BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
+ BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
+ logPtr(this));
return;
}
@@ -183,8 +183,8 @@ class Connection :
{
std::string_view selectedProtocol(
std::bit_cast<const char*>(alpn), alpnlen);
- BMCWEB_LOG_DEBUG << "ALPN selected protocol \""
- << selectedProtocol << "\" len: " << alpnlen;
+ BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
+ selectedProtocol, alpnlen);
if (selectedProtocol == "h2")
{
auto http2 =
@@ -205,7 +205,7 @@ class Connection :
crow::Request& thisReq = req.emplace(parser->release(), reqEc);
if (reqEc)
{
- BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
+ BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
res.result(boost::beast::http::status::bad_request);
completeRequest(res);
return;
@@ -226,11 +226,10 @@ class Connection :
}
}
- BMCWEB_LOG_INFO << "Request: "
- << " " << this << " HTTP/" << thisReq.version() / 10
- << "." << thisReq.version() % 10 << ' '
- << thisReq.methodString() << " " << thisReq.target()
- << " " << thisReq.ipAddress.to_string();
+ BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
+ thisReq.version() / 10, thisReq.version() % 10,
+ thisReq.methodString(), thisReq.target(),
+ thisReq.ipAddress.to_string());
res.isAliveHelper = [this]() -> bool { return isAlive(); };
@@ -248,7 +247,7 @@ class Connection :
req->method()) &&
thisReq.session == nullptr)
{
- BMCWEB_LOG_WARNING << "Authentication failed";
+ BMCWEB_LOG_WARNING("Authentication failed");
forward_unauthorized::sendUnauthorized(
req->url().encoded_path(),
req->getHeaderValue("X-Requested-With"),
@@ -258,7 +257,7 @@ class Connection :
}
#endif // BMCWEB_INSECURE_DISABLE_AUTHX
auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
- BMCWEB_LOG_DEBUG << "Setting completion handler";
+ BMCWEB_LOG_DEBUG("Setting completion handler");
asyncResp->res.setCompleteRequestHandler(
[self(shared_from_this())](crow::Response& thisRes) {
self->completeRequest(thisRes);
@@ -320,9 +319,8 @@ class Connection :
adaptor.next_layer().close();
if (mtlsSession != nullptr)
{
- BMCWEB_LOG_DEBUG
- << this
- << " Removing TLS session: " << mtlsSession->uniqueId;
+ BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
+ mtlsSession->uniqueId);
persistent_data::SessionStore::getInstance().removeSession(
mtlsSession);
}
@@ -371,7 +369,7 @@ class Connection :
boost::system::error_code getClientIp(boost::asio::ip::address& ip)
{
boost::system::error_code ec;
- BMCWEB_LOG_DEBUG << "Fetch the client IP address";
+ BMCWEB_LOG_DEBUG("Fetch the client IP address");
boost::asio::ip::tcp::endpoint endpoint =
boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
@@ -379,8 +377,8 @@ class Connection :
{
// If remote endpoint fails keep going. "ClientOriginIPAddress"
// will be empty.
- BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
- << ec;
+ BMCWEB_LOG_ERROR("Failed to get the client's IP Address. ec : {}",
+ ec);
return ec;
}
ip = endpoint.address();
@@ -390,7 +388,7 @@ class Connection :
private:
void doReadHeaders()
{
- BMCWEB_LOG_DEBUG << this << " doReadHeaders";
+ BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
// Clean up any previous Connection.
boost::beast::http::async_read_header(
@@ -398,21 +396,21 @@ class Connection :
[this,
self(shared_from_this())](const boost::system::error_code& ec,
std::size_t bytesTransferred) {
- BMCWEB_LOG_DEBUG << this << " async_read_header "
- << bytesTransferred << " Bytes";
+ BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
+ bytesTransferred);
bool errorWhileReading = false;
if (ec)
{
errorWhileReading = true;
if (ec == boost::beast::http::error::end_of_stream)
{
- BMCWEB_LOG_WARNING
- << this << " Error while reading: " << ec.message();
+ BMCWEB_LOG_WARNING("{} Error while reading: {}",
+ logPtr(this), ec.message());
}
else
{
- BMCWEB_LOG_ERROR
- << this << " Error while reading: " << ec.message();
+ BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
+ ec.message());
}
}
else
@@ -431,7 +429,7 @@ class Connection :
if (errorWhileReading)
{
close();
- BMCWEB_LOG_DEBUG << this << " from read(1)";
+ BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
return;
}
@@ -440,7 +438,7 @@ class Connection :
boost::asio::ip::address ip;
if (getClientIp(ip))
{
- BMCWEB_LOG_DEBUG << "Unable to get client IP";
+ BMCWEB_LOG_DEBUG("Unable to get client IP");
}
#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
boost::beast::http::verb method = parser->get().method();
@@ -454,13 +452,13 @@ class Connection :
parser->content_length();
if (contentLength && *contentLength > loggedOutPostBodyLimit)
{
- BMCWEB_LOG_DEBUG << "Content length greater than limit "
- << *contentLength;
+ BMCWEB_LOG_DEBUG("Content length greater than limit {}",
+ *contentLength);
close();
return;
}
- BMCWEB_LOG_DEBUG << "Starting quick deadline";
+ BMCWEB_LOG_DEBUG("Starting quick deadline");
}
#endif // BMCWEB_INSECURE_DISABLE_AUTHX
@@ -476,22 +474,22 @@ class Connection :
void doRead()
{
- BMCWEB_LOG_DEBUG << this << " doRead";
+ BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
startDeadline();
boost::beast::http::async_read_some(
adaptor, buffer, *parser,
[this,
self(shared_from_this())](const boost::system::error_code& ec,
std::size_t bytesTransferred) {
- BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
- << " Bytes";
+ BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
+ bytesTransferred);
if (ec)
{
- BMCWEB_LOG_ERROR << this
- << " Error while reading: " << ec.message();
+ BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
+ ec.message());
close();
- BMCWEB_LOG_DEBUG << this << " from read(1)";
+ BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
return;
}
@@ -515,7 +513,7 @@ class Connection :
void doWrite(crow::Response& thisRes)
{
- BMCWEB_LOG_DEBUG << this << " doWrite";
+ BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
thisRes.preparePayload();
serializer.emplace(*thisRes.stringResponse);
startDeadline();
@@ -523,25 +521,25 @@ class Connection :
[this, self(shared_from_this())](
const boost::system::error_code& ec,
std::size_t bytesTransferred) {
- BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
- << " bytes";
+ BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
+ bytesTransferred);
cancelDeadlineTimer();
if (ec)
{
- BMCWEB_LOG_DEBUG << this << " from write(2)";
+ BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
return;
}
if (!keepAlive)
{
close();
- BMCWEB_LOG_DEBUG << this << " from write(1)";
+ BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
return;
}
serializer.reset();
- BMCWEB_LOG_DEBUG << this << " Clearing response";
+ BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
res.clear();
parser.emplace(std::piecewise_construct, std::make_tuple());
parser->body_limit(httpReqBodyLimit); // reset body limit for
@@ -580,7 +578,8 @@ class Connection :
weakSelf.lock();
if (!self)
{
- BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
+ BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
+ logPtr(self.get()));
return;
}
@@ -593,16 +592,18 @@ class Connection :
}
if (ec)
{
- BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
+ BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
+ ec);
}
- BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
+ BMCWEB_LOG_WARNING("{}Connection timed out, closing",
+ logPtr(self.get()));
self->close();
});
timerStarted = true;
- BMCWEB_LOG_DEBUG << this << " timer started";
+ BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
}
Adaptor adaptor;
diff --git a/http/http_response.hpp b/http/http_response.hpp
index 93c90d7d09..c4f9366ed3 100644
--- a/http/http_response.hpp
+++ b/http/http_response.hpp
@@ -66,8 +66,8 @@ struct Response
Response& operator=(Response&& r) noexcept
{
- BMCWEB_LOG_DEBUG << "Moving response containers; this: " << this
- << "; other: " << &r;
+ BMCWEB_LOG_DEBUG("Moving response containers; this: {}; other: {}",
+ logPtr(this), logPtr(&r));
if (this == &r)
{
return *this;
@@ -167,9 +167,9 @@ struct Response
stringResponse->result() == status::no_content ||
stringResponse->result() == status::not_modified))
{
- BMCWEB_LOG_CRITICAL
- << this
- << " Response content provided but code was no-content or not_modified, which aren't allowed to have a body";
+ BMCWEB_LOG_CRITICAL(
+ "{} Response content provided but code was no-content or not_modified, which aren't allowed to have a body",
+ logPtr(this));
pSize = 0;
body().clear();
}
@@ -179,7 +179,7 @@ struct Response
void clear()
{
- BMCWEB_LOG_DEBUG << this << " Clearing response containers";
+ BMCWEB_LOG_DEBUG("{} Clearing response containers", logPtr(this));
stringResponse.emplace(response_type{});
jsonValue = nullptr;
completed = false;
@@ -216,14 +216,14 @@ struct Response
}
if (completed)
{
- BMCWEB_LOG_ERROR << this << " Response was ended twice";
+ BMCWEB_LOG_ERROR("{} Response was ended twice", logPtr(this));
return;
}
completed = true;
- BMCWEB_LOG_DEBUG << this << " calling completion handler";
+ BMCWEB_LOG_DEBUG("{} calling completion handler", logPtr(this));
if (completeRequestHandler)
{
- BMCWEB_LOG_DEBUG << this << " completion handler was valid";
+ BMCWEB_LOG_DEBUG("{} completion handler was valid", logPtr(this));
completeRequestHandler(*this);
}
}
@@ -235,7 +235,7 @@ struct Response
void setCompleteRequestHandler(std::function<void(Response&)>&& handler)
{
- BMCWEB_LOG_DEBUG << this << " setting completion handler";
+ BMCWEB_LOG_DEBUG("{} setting completion handler", logPtr(this));
completeRequestHandler = std::move(handler);
// Now that we have a new completion handler attached, we're no longer
@@ -245,8 +245,8 @@ struct Response
std::function<void(Response&)> releaseCompleteRequestHandler()
{
- BMCWEB_LOG_DEBUG << this << " releasing completion handler"
- << static_cast<bool>(completeRequestHandler);
+ BMCWEB_LOG_DEBUG("{} releasing completion handler{}", logPtr(this),
+ static_cast<bool>(completeRequestHandler));
std::function<void(Response&)> ret = completeRequestHandler;
completeRequestHandler = nullptr;
completed = true;
diff --git a/http/http_server.hpp b/http/http_server.hpp
index 91de8db37d..dbb95b42dd 100644
--- a/http/http_server.hpp
+++ b/http/http_server.hpp
@@ -89,8 +89,8 @@ class Server
return dateStr;
};
- BMCWEB_LOG_INFO << "bmcweb server is running, local endpoint "
- << acceptor->local_endpoint().address().to_string();
+ BMCWEB_LOG_INFO("bmcweb server is running, local endpoint {}",
+ acceptor->local_endpoint().address().to_string());
startAsyncWaitForSignal();
doAccept();
}
@@ -114,7 +114,7 @@ class Server
fs::create_directories(certPath);
}
fs::path certFile = certPath / "server.pem";
- BMCWEB_LOG_INFO << "Building SSL Context file=" << certFile.string();
+ BMCWEB_LOG_INFO("Building SSL Context file={}", certFile.string());
std::string sslPemFile(certFile);
ensuressl::ensureOpensslKeyPresentAndValid(sslPemFile);
std::shared_ptr<boost::asio::ssl::context> sslContext =
@@ -130,21 +130,21 @@ class Server
[this](const boost::system::error_code& ec, int signalNo) {
if (ec)
{
- BMCWEB_LOG_INFO << "Error in signal handler" << ec.message();
+ BMCWEB_LOG_INFO("Error in signal handler{}", ec.message());
}
else
{
if (signalNo == SIGHUP)
{
- BMCWEB_LOG_INFO << "Receivied reload signal";
+ BMCWEB_LOG_INFO("Receivied reload signal");
loadCertificate();
boost::system::error_code ec2;
acceptor->cancel(ec2);
if (ec2)
{
- BMCWEB_LOG_ERROR
- << "Error while canceling async operations:"
- << ec2.message();
+ BMCWEB_LOG_ERROR(
+ "Error while canceling async operations:{}",
+ ec2.message());
}
startAsyncWaitForSignal();
}
diff --git a/http/logging.hpp b/http/logging.hpp
index 368548f9c0..bf5e42eb79 100644
--- a/http/logging.hpp
+++ b/http/logging.hpp
@@ -2,16 +2,119 @@
#include "bmcweb_config.h"
-#include <algorithm>
-#include <array>
-#include <cstdio>
-#include <cstdlib>
-#include <ctime>
-#include <filesystem>
+#include <boost/system/error_code.hpp>
+#include <boost/url/pct_string_view.hpp>
+#include <boost/url/string_view.hpp>
+#include <boost/url/url.hpp>
+#include <nlohmann/json.hpp>
+
+#include <bit>
+#include <format>
#include <iostream>
-#include <sstream>
-#include <string>
+#include <source_location>
#include <string_view>
+#include <system_error>
+
+// Clang-tidy would rather these be static, but using static causes the template
+// specialization to not function. Ignore the warning.
+// NOLINTBEGIN(readability-convert-member-functions-to-static, cert-dcl58-cpp)
+template <>
+struct std::formatter<boost::system::error_code>
+{
+ constexpr auto parse(std::format_parse_context& ctx)
+ {
+ return ctx.begin();
+ }
+
+ auto format(const boost::system::error_code& ec, auto& ctx) const
+ {
+ return std::format_to(ctx.out(), "{}", ec.what());
+ }
+};
+
+template <>
+struct std::formatter<boost::urls::pct_string_view>
+{
+ constexpr auto parse(std::format_parse_context& ctx)
+ {
+ return ctx.begin();
+ }
+ auto format(const boost::urls::pct_string_view& msg, auto& ctx) const
+ {
+ return std::format_to(ctx.out(), "{}",
+ std::string_view(msg.data(), msg.size()));
+ }
+};
+
+template <>
+struct std::formatter<boost::urls::url>
+{
+ constexpr auto parse(std::format_parse_context& ctx)
+ {
+ return ctx.begin();
+ }
+ auto format(const boost::urls::url& msg, auto& ctx) const
+ {
+ return std::format_to(ctx.out(), "{}", std::string_view(msg.buffer()));
+ }
+};
+
+template <>
+struct std::formatter<boost::core::string_view>
+{
+ constexpr auto parse(std::format_parse_context& ctx)
+ {
+ return ctx.begin();
+ }
+ auto format(const boost::core::string_view& msg, auto& ctx) const
+ {
+ return std::format_to(ctx.out(), "{}", std::string_view(msg));
+ }
+};
+
+template <>
+struct std::formatter<void*>
+{
+ constexpr auto parse(std::format_parse_context& ctx)
+ {
+ return ctx.begin();
+ }
+ auto format(const void*& ptr, auto& ctx) const
+ {
+ return std::format_to(ctx.out(), "{}",
+ std::to_string(std::bit_cast<size_t>(ptr)));
+ }
+};
+
+template <>
+struct std::formatter<nlohmann::json::json_pointer>
+{
+ constexpr auto parse(std::format_parse_context& ctx)
+ {
+ return ctx.begin();
+ }
+ auto format(const nlohmann::json::json_pointer& ptr, auto& ctx) const
+ {
+ return std::format_to(ctx.out(), "{}", ptr.to_string());
+ }
+};
+
+template <>
+struct std::formatter<nlohmann::json>
+{
+ static constexpr auto parse(std::format_parse_context& ctx)
+ {
+ return ctx.begin();
+ }
+ auto format(const nlohmann::json& json, auto& ctx) const
+ {
+ return std::format_to(
+ ctx.out(), "{}",
+ json.dump(-1, ' ', false,
+ nlohmann::json::error_handler_t::replace));
+ }
+};
+// NOLINTEND(readability-convert-member-functions-to-static, cert-dcl58-cpp)
namespace crow
{
@@ -51,103 +154,83 @@ constexpr crow::LogLevel getLogLevelFromName(std::string_view name)
constexpr crow::LogLevel bmcwebCurrentLoggingLevel =
getLogLevelFromName(bmcwebLoggingLevel);
-class Logger
+struct FormatString
{
- private:
- //
- static std::string timestamp()
- {
- std::string date;
- date.resize(32, '\0');
- time_t t = time(nullptr);
-
- tm myTm{};
-
- gmtime_r(&t, &myTm);
-
- size_t sz = strftime(date.data(), date.size(), "%Y-%m-%d %H:%M:%S",
- &myTm);
- date.resize(sz);
- return date;
- }
-
- public:
- Logger([[maybe_unused]] const std::string& prefix,
- [[maybe_unused]] const std::string& filename,
- [[maybe_unused]] const size_t line)
- {
- stringstream << "(" << timestamp() << ") [" << prefix << " "
- << std::filesystem::path(filename).filename() << ":"
- << line << "] ";
- }
- ~Logger()
- {
- stringstream << std::endl;
- std::cerr << stringstream.str();
- }
-
- Logger(const Logger&) = delete;
- Logger(Logger&&) = delete;
- Logger& operator=(const Logger&) = delete;
- Logger& operator=(const Logger&&) = delete;
-
- //
- template <typename T>
- Logger& operator<<([[maybe_unused]] const T& value)
- {
- // Somewhere in the code we're implicitly casting an array to a
- // pointer in logging code. It's non-trivial to find,
- // so disable the check here for now
- // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
- stringstream << value;
- return *this;
- }
+ std::string_view str;
+ std::source_location loc;
+
+ // NOLINTNEXTLINE(google-explicit-constructor)
+ FormatString(const char* strIn, const std::source_location& locIn =
+ std::source_location::current()) :
+ str(strIn),
+ loc(locIn)
+ {}
+};
- constexpr static LogLevel getCurrentLogLevel()
- {
- return bmcwebCurrentLoggingLevel;
- }
+template <typename T>
+const void* logPtr(T p)
+{
+ static_assert(std::is_pointer<T>::value,
+ "Can't use logPtr without pointer");
+ return std::bit_cast<const void*>(p);
+}
- constexpr static bool isLoggingEnabled()
+template <LogLevel level>
+inline void vlog(const FormatString& format, std::format_args&& args)
+{
+ if constexpr (bmcwebCurrentLoggingLevel > level)
{
- return getCurrentLogLevel() >= crow::LogLevel::Debug;
+ return;
}
-
- constexpr static bool checkLoggingLevel(const LogLevel level)
+ constexpr size_t stringIndex = static_cast<size_t>(level);
+ static_assert(stringIndex < mapLogLevelFromName.size(),
+ "Missing string for level");
+ constexpr std::string_view levelString =
+ mapLogLevelFromName[stringIndex].first;
+ std::string_view filename = format.loc.file_name();
+ if (filename.starts_with("../"))
{
- return isLoggingEnabled() && (getCurrentLogLevel() <= level);
+ filename = filename.substr(3);
}
-
- private:
- //
- std::ostringstream stringstream;
-};
+ std::cout << std::format("[{} {}:{}] ", levelString, filename,
+ format.loc.line());
+ std::cout << std::vformat(format.str, args);
+ std::putc('\n', stdout);
+}
} // namespace crow
-// Disable clang-tidy warnings about unused macros.
-// NOLINTBEGIN(cppcoreguidelines-macro-usage, clang-diagnostic-unused-macros)
-
-// The logging functions currently use macros. Now that we have c++20, ideally
-// they'd use source_location with fixed functions, but for the moment, disable
-// the check.
-#define BMCWEB_LOG_CRITICAL \
- if constexpr (crow::Logger::checkLoggingLevel(crow::LogLevel::Critical)) \
- crow::Logger("CRITICAL", __FILE__, __LINE__)
-
-#define BMCWEB_LOG_ERROR \
- if constexpr (crow::Logger::checkLoggingLevel(crow::LogLevel::Error)) \
- crow::Logger("ERROR", __FILE__, __LINE__)
+template <typename... Args>
+inline void BMCWEB_LOG_CRITICAL(const crow::FormatString& format,
+ Args&&... args)
+{
+ crow::vlog<crow::LogLevel::Critical>(
+ format, std::make_format_args(std::forward<Args>(args)...));
+}
-#define BMCWEB_LOG_WARNING \
- if constexpr (crow::Logger::checkLoggingLevel(crow::LogLevel::Warning)) \
- crow::Logger("WARNING", __FILE__, __LINE__)
+template <typename... Args>
+inline void BMCWEB_LOG_ERROR(const crow::FormatString& format, Args&&... args)
+{
+ crow::vlog<crow::LogLevel::Error>(
+ format, std::make_format_args(std::forward<Args>(args)...));
+}
-#define BMCWEB_LOG_INFO \
- if constexpr (crow::Logger::checkLoggingLevel(crow::LogLevel::Info)) \
- crow::Logger("INFO", __FILE__, __LINE__)
+template <typename... Args>
+inline void BMCWEB_LOG_WARNING(const crow::FormatString& format, Args&&... args)
+{
+ crow::vlog<crow::LogLevel::Warning>(
+ format, std::make_format_args(std::forward<Args>(args)...));
+}
-#define BMCWEB_LOG_DEBUG \
- if constexpr (crow::Logger::checkLoggingLevel(crow::LogLevel::Debug)) \
- crow::Logger("DEBUG", __FILE__, __LINE__)
+template <typename... Args>
+inline void BMCWEB_LOG_INFO(const crow::FormatString& format, Args&&... args)
+{
+ crow::vlog<crow::LogLevel::Info>(
+ format, std::make_format_args(std::forward<Args>(args)...));
+}
-// NOLINTEND(cppcoreguidelines-macro-usage, clang-diagnostic-unused-macros)
+template <typename... Args>
+inline void BMCWEB_LOG_DEBUG(const crow::FormatString& format, Args&&... args)
+{
+ crow::vlog<crow::LogLevel::Debug>(
+ format, std::make_format_args(std::forward<Args>(args)...));
+}
diff --git a/http/mutual_tls.hpp b/http/mutual_tls.hpp
index f8af0f6f57..9cd4cde01c 100644
--- a/http/mutual_tls.hpp
+++ b/http/mutual_tls.hpp
@@ -21,14 +21,14 @@ inline std::shared_ptr<persistent_data::UserSession>
.getAuthMethodsConfig()
.tls)
{
- BMCWEB_LOG_DEBUG << "TLS auth_config is disabled";
+ BMCWEB_LOG_DEBUG("TLS auth_config is disabled");
return nullptr;
}
X509_STORE_CTX* cts = ctx.native_handle();
if (cts == nullptr)
{
- BMCWEB_LOG_DEBUG << "Cannot get native TLS handle.";
+ BMCWEB_LOG_DEBUG("Cannot get native TLS handle.");
return nullptr;
}
@@ -36,7 +36,7 @@ inline std::shared_ptr<persistent_data::UserSession>
X509* peerCert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
if (peerCert == nullptr)
{
- BMCWEB_LOG_DEBUG << "Cannot get current TLS certificate.";
+ BMCWEB_LOG_DEBUG("Cannot get current TLS certificate.");
return nullptr;
}
@@ -44,7 +44,7 @@ inline std::shared_ptr<persistent_data::UserSession>
int ctxError = X509_STORE_CTX_get_error(cts);
if (ctxError != X509_V_OK)
{
- BMCWEB_LOG_INFO << "Last TLS error is: " << ctxError;
+ BMCWEB_LOG_INFO("Last TLS error is: {}", ctxError);
return nullptr;
}
// Check that we have reached final certificate in chain
@@ -52,12 +52,13 @@ inline std::shared_ptr<persistent_data::UserSession>
if (depth != 0)
{
- BMCWEB_LOG_DEBUG << "Certificate verification in progress (depth "
- << depth << "), waiting to reach final depth";
+ BMCWEB_LOG_DEBUG(
+ "Certificate verification in progress (depth {}), waiting to reach final depth",
+ depth);
return nullptr;
}
- BMCWEB_LOG_DEBUG << "Certificate verification of final depth";
+ BMCWEB_LOG_DEBUG("Certificate verification of final depth");
// Verify KeyUsage
bool isKeyUsageDigitalSignature = false;
@@ -68,7 +69,7 @@ inline std::shared_ptr<persistent_data::UserSession>
if ((usage == nullptr) || (usage->data == nullptr))
{
- BMCWEB_LOG_DEBUG << "TLS usage is null";
+ BMCWEB_LOG_DEBUG("TLS usage is null");
return nullptr;
}
@@ -88,9 +89,9 @@ inline std::shared_ptr<persistent_data::UserSession>
if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
{
- BMCWEB_LOG_DEBUG << "Certificate ExtendedKeyUsage does "
- "not allow provided certificate to "
- "be used for user authentication";
+ BMCWEB_LOG_DEBUG("Certificate ExtendedKeyUsage does "
+ "not allow provided certificate to "
+ "be used for user authentication");
return nullptr;
}
@@ -101,7 +102,7 @@ inline std::shared_ptr<persistent_data::UserSession>
if (extUsage == nullptr)
{
- BMCWEB_LOG_DEBUG << "TLS extUsage is null";
+ BMCWEB_LOG_DEBUG("TLS extUsage is null");
return nullptr;
}
@@ -121,9 +122,9 @@ inline std::shared_ptr<persistent_data::UserSession>
// Certificate has to have proper key usages set
if (!isExKeyUsageClientAuth)
{
- BMCWEB_LOG_DEBUG << "Certificate ExtendedKeyUsage does "
- "not allow provided certificate to "
- "be used for user authentication";
+ BMCWEB_LOG_DEBUG("Certificate ExtendedKeyUsage does "
+ "not allow provided certificate to "
+ "be used for user authentication");
return nullptr;
}
std::string sslUser;
@@ -136,14 +137,14 @@ inline std::shared_ptr<persistent_data::UserSession>
if (status == -1)
{
- BMCWEB_LOG_DEBUG << "TLS cannot get username to create session";
+ BMCWEB_LOG_DEBUG("TLS cannot get username to create session");
return nullptr;
}
size_t lastChar = sslUser.find('\0');
if (lastChar == std::string::npos || lastChar == 0)
{
- BMCWEB_LOG_DEBUG << "Invalid TLS user name";
+ BMCWEB_LOG_DEBUG("Invalid TLS user name");
return nullptr;
}
sslUser.resize(lastChar);
diff --git a/http/nghttp2_adapters.hpp b/http/nghttp2_adapters.hpp
index 3c1f549e85..9f4dc911d7 100644
--- a/http/nghttp2_adapters.hpp
+++ b/http/nghttp2_adapters.hpp
@@ -99,7 +99,7 @@ struct nghttp2_session
{
if (nghttp2_session_server_new(&ptr, callbacks.get(), nullptr) != 0)
{
- BMCWEB_LOG_ERROR << "nghttp2_session_server_new failed";
+ BMCWEB_LOG_ERROR("nghttp2_session_server_new failed");
return;
}
}
diff --git a/http/parsing.hpp b/http/parsing.hpp
index f16d8903da..839b51cae1 100644
--- a/http/parsing.hpp
+++ b/http/parsing.hpp
@@ -24,7 +24,7 @@ inline JsonParseResult parseRequestAsJson(const crow::Request& req,
if (!boost::iequals(contentType, "application/json") &&
!boost::iequals(contentType, "application/json; charset=utf-8"))
{
- BMCWEB_LOG_WARNING << "Failed to parse content type on request";
+ BMCWEB_LOG_WARNING("Failed to parse content type on request");
#ifndef BMCWEB_INSECURE_IGNORE_CONTENT_TYPE
return JsonParseResult::BadContentType;
#endif
@@ -32,7 +32,7 @@ inline JsonParseResult parseRequestAsJson(const crow::Request& req,
jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
if (jsonOut.is_discarded())
{
- BMCWEB_LOG_WARNING << "Failed to parse json in request";
+ BMCWEB_LOG_WARNING("Failed to parse json in request");
return JsonParseResult::BadJsonData;
}
diff --git a/http/routing.hpp b/http/routing.hpp
index 1b2c131576..49a51f18e7 100644
--- a/http/routing.hpp
+++ b/http/routing.hpp
@@ -307,18 +307,20 @@ class Trie
{
if (n->paramChildrens[i] != 0U)
{
- BMCWEB_LOG_DEBUG << std::string(
- 2U * level, ' ') /*<< "("<<n->paramChildrens[i]<<") "*/;
+ BMCWEB_LOG_DEBUG(
+ "{}({}{}",
+ std::string(2U * level,
+ ' ') /*, n->paramChildrens[i], ") "*/);
switch (static_cast<ParamType>(i))
{
case ParamType::STRING:
- BMCWEB_LOG_DEBUG << "<str>";
+ BMCWEB_LOG_DEBUG("<str>");
break;
case ParamType::PATH:
- BMCWEB_LOG_DEBUG << "<path>";
+ BMCWEB_LOG_DEBUG("<path>");
break;
case ParamType::MAX:
- BMCWEB_LOG_DEBUG << "<ERROR>";
+ BMCWEB_LOG_DEBUG("<ERROR>");
break;
}
@@ -327,9 +329,9 @@ class Trie
}
for (const Node::ChildMap::value_type& kv : n->children)
{
- BMCWEB_LOG_DEBUG
- << std::string(2U * level, ' ') /*<< "(" << kv.second << ") "*/
- << kv.first;
+ BMCWEB_LOG_DEBUG("{}({}{}{}",
+ std::string(2U * level, ' ') /*, kv.second, ") "*/,
+ kv.first);
debugNodePrint(&nodes[kv.second], level + 1);
}
}
@@ -498,7 +500,7 @@ class Router
FindRoute route;
if (index >= perMethods.size())
{
- BMCWEB_LOG_CRITICAL << "Bad index???";
+ BMCWEB_LOG_CRITICAL("Bad index???");
return route;
}
const PerMethod& perMethod = perMethods[index];
@@ -574,8 +576,7 @@ class Router
unsigned ruleIndex = found.first;
if (ruleIndex == 0U)
{
- BMCWEB_LOG_DEBUG << "Cannot match rules "
- << req.url().encoded_path();
+ BMCWEB_LOG_DEBUG("Cannot match rules {}", req.url().encoded_path());
asyncResp->res.result(boost::beast::http::status::not_found);
return;
}
@@ -589,16 +590,16 @@ class Router
size_t methods = rule.getMethods();
if ((methods & (1U << static_cast<size_t>(*verb))) == 0)
{
- BMCWEB_LOG_DEBUG
- << "Rule found but method mismatch: "
- << req.url().encoded_path() << " with " << req.methodString()
- << "(" << static_cast<uint32_t>(*verb) << ") / " << methods;
+ BMCWEB_LOG_DEBUG(
+ "Rule found but method mismatch: {} with {}({}) / {}",
+ req.url().encoded_path(), req.methodString(),
+ static_cast<uint32_t>(*verb), methods);
asyncResp->res.result(boost::beast::http::status::not_found);
return;
}
- BMCWEB_LOG_DEBUG << "Matched rule (upgrade) '" << rule.rule << "' "
- << static_cast<uint32_t>(*verb) << " / " << methods;
+ BMCWEB_LOG_DEBUG("Matched rule (upgrade) '{}' {} / {}", rule.rule,
+ static_cast<uint32_t>(*verb), methods);
// TODO(ed) This should be able to use std::bind_front, but it doesn't
// appear to work with the std::move on adaptor.
@@ -665,9 +666,8 @@ class Router
BaseRule& rule = *foundRoute.route.rule;
std::vector<std::string> params = std::move(foundRoute.route.params);
- BMCWEB_LOG_DEBUG << "Matched rule '" << rule.rule << "' "
- << static_cast<uint32_t>(*verb) << " / "
- << rule.getMethods();
+ BMCWEB_LOG_DEBUG("Matched rule '{}' {} / {}", rule.rule,
+ static_cast<uint32_t>(*verb), rule.getMethods());
if (req.session == nullptr)
{
@@ -684,8 +684,9 @@ class Router
{
for (size_t i = 0; i < perMethods.size(); i++)
{
- BMCWEB_LOG_DEBUG << boost::beast::http::to_string(
- static_cast<boost::beast::http::verb>(i));
+ BMCWEB_LOG_DEBUG("{}",
+ boost::beast::http::to_string(
+ static_cast<boost::beast::http::verb>(i)));
perMethods[i].trie.debugPrint();
}
}
diff --git a/http/routing/websocketrule.hpp b/http/routing/websocketrule.hpp
index c8f706db51..5e558f2edb 100644
--- a/http/routing/websocketrule.hpp
+++ b/http/routing/websocketrule.hpp
@@ -32,7 +32,7 @@ class WebSocketRule : public BaseRule
const std::shared_ptr<bmcweb::AsyncResp>& /*asyncResp*/,
boost::asio::ip::tcp::socket&& adaptor) override
{
- BMCWEB_LOG_DEBUG << "Websocket handles upgrade";
+ BMCWEB_LOG_DEBUG("Websocket handles upgrade");
std::shared_ptr<
crow::websocket::ConnectionImpl<boost::asio::ip::tcp::socket>>
myConnection = std::make_shared<
@@ -47,7 +47,7 @@ class WebSocketRule : public BaseRule
boost::beast::ssl_stream<boost::asio::ip::tcp::socket>&&
adaptor) override
{
- BMCWEB_LOG_DEBUG << "Websocket handles upgrade";
+ BMCWEB_LOG_DEBUG("Websocket handles upgrade");
std::shared_ptr<crow::websocket::ConnectionImpl<
boost::beast::ssl_stream<boost::asio::ip::tcp::socket>>>
myConnection = std::make_shared<crow::websocket::ConnectionImpl<
diff --git a/http/server_sent_event.hpp b/http/server_sent_event.hpp
index 02af0b7523..773394836f 100644
--- a/http/server_sent_event.hpp
+++ b/http/server_sent_event.hpp
@@ -49,7 +49,7 @@ class ConnectionImpl : public Connection
timer(ioc), openHandler(std::move(openHandlerIn)),
closeHandler(std::move(closeHandlerIn))
{
- BMCWEB_LOG_DEBUG << "SseConnectionImpl: SSE constructor " << this;
+ BMCWEB_LOG_DEBUG("SseConnectionImpl: SSE constructor {}", logPtr(this));
}
ConnectionImpl(const ConnectionImpl&) = delete;
@@ -59,7 +59,7 @@ class ConnectionImpl : public Connection
~ConnectionImpl() override
{
- BMCWEB_LOG_DEBUG << "SSE ConnectionImpl: SSE destructor " << this;
+ BMCWEB_LOG_DEBUG("SSE ConnectionImpl: SSE destructor {}", logPtr(this));
}
boost::asio::io_context& getIoContext() override
@@ -72,7 +72,7 @@ class ConnectionImpl : public Connection
{
if (!openHandler)
{
- BMCWEB_LOG_CRITICAL << "No open handler???";
+ BMCWEB_LOG_CRITICAL("No open handler???");
return;
}
openHandler(*this);
@@ -85,13 +85,13 @@ class ConnectionImpl : public Connection
{
closeHandler(*this);
}
- BMCWEB_LOG_DEBUG << "Closing SSE connection " << this << " - " << msg;
+ BMCWEB_LOG_DEBUG("Closing SSE connection {} - {}", logPtr(this), msg);
boost::beast::get_lowest_layer(adaptor).close();
}
void sendSSEHeader()
{
- BMCWEB_LOG_DEBUG << "Starting SSE connection";
+ BMCWEB_LOG_DEBUG("Starting SSE connection");
using BodyType = boost::beast::http::buffer_body;
boost::beast::http::response<BodyType> res(
boost::beast::http::status::ok, 11, BodyType{});
@@ -113,11 +113,11 @@ class ConnectionImpl : public Connection
serializer.reset();
if (ec)
{
- BMCWEB_LOG_ERROR << "Error sending header" << ec;
+ BMCWEB_LOG_ERROR("Error sending header{}", ec);
close("async_write_header failed");
return;
}
- BMCWEB_LOG_DEBUG << "SSE header sent - Connection established";
+ BMCWEB_LOG_DEBUG("SSE header sent - Connection established");
serializer.reset();
@@ -138,7 +138,7 @@ class ConnectionImpl : public Connection
}
if (ec)
{
- BMCWEB_LOG_ERROR << "Read error: " << ec;
+ BMCWEB_LOG_ERROR("Read error: {}", ec);
}
close("Close SSE connection");
@@ -152,7 +152,7 @@ class ConnectionImpl : public Connection
}
if (inputBuffer.size() == 0)
{
- BMCWEB_LOG_DEBUG << "inputBuffer is empty... Bailing out";
+ BMCWEB_LOG_DEBUG("inputBuffer is empty... Bailing out");
return;
}
startTimeout();
@@ -179,19 +179,19 @@ class ConnectionImpl : public Connection
if (ec == boost::asio::error::eof)
{
- BMCWEB_LOG_ERROR << "async_write_some() SSE stream closed";
+ BMCWEB_LOG_ERROR("async_write_some() SSE stream closed");
close("SSE stream closed");
return;
}
if (ec)
{
- BMCWEB_LOG_ERROR << "async_write_some() failed: " << ec.message();
+ BMCWEB_LOG_ERROR("async_write_some() failed: {}", ec.message());
close("async_write_some failed");
return;
}
- BMCWEB_LOG_DEBUG << "async_write_some() bytes transferred: "
- << bytesTransferred;
+ BMCWEB_LOG_DEBUG("async_write_some() bytes transferred: {}",
+ bytesTransferred);
doWrite();
}
@@ -200,7 +200,7 @@ class ConnectionImpl : public Connection
{
if (msg.empty())
{
- BMCWEB_LOG_DEBUG << "Empty data, bailing out.";
+ BMCWEB_LOG_DEBUG("Empty data, bailing out.");
return;
}
@@ -249,22 +249,24 @@ class ConnectionImpl : public Connection
std::shared_ptr<Connection> self = weakSelf.lock();
if (!self)
{
- BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
+ BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
+ logPtr(self.get()));
return;
}
if (ec == boost::asio::error::operation_aborted)
{
- BMCWEB_LOG_DEBUG << "operation aborted";
+ BMCWEB_LOG_DEBUG("operation aborted");
// Canceled wait means the path succeeeded.
return;
}
if (ec)
{
- BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
+ BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()), ec);
}
- BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
+ BMCWEB_LOG_WARNING("{}Connection timed out, closing",
+ logPtr(self.get()));
self->close("closing connection");
}
diff --git a/http/websocket.hpp b/http/websocket.hpp
index 434a0c1944..216c4131db 100644
--- a/http/websocket.hpp
+++ b/http/websocket.hpp
@@ -75,7 +75,7 @@ class ConnectionImpl : public Connection
/* Turn on the timeouts on websocket stream to server role */
ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(
boost::beast::role_type::server));
- BMCWEB_LOG_DEBUG << "Creating new connection " << this;
+ BMCWEB_LOG_DEBUG("Creating new connection {}", logPtr(this));
}
boost::asio::io_context& getIoContext() override
@@ -86,7 +86,7 @@ class ConnectionImpl : public Connection
void start()
{
- BMCWEB_LOG_DEBUG << "starting connection " << this;
+ BMCWEB_LOG_DEBUG("starting connection {}", logPtr(this));
using bf = boost::beast::http::field;
@@ -104,7 +104,7 @@ class ConnectionImpl : public Connection
!crow::utility::constantTimeStringCompare(
protocol, session->csrfToken))
{
- BMCWEB_LOG_ERROR << "Websocket CSRF error";
+ BMCWEB_LOG_ERROR("Websocket CSRF error");
m.result(boost::beast::http::status::unauthorized);
return;
}
@@ -131,7 +131,7 @@ class ConnectionImpl : public Connection
const boost::system::error_code& ec) {
if (ec)
{
- BMCWEB_LOG_ERROR << "Error in ws.async_accept " << ec;
+ BMCWEB_LOG_ERROR("Error in ws.async_accept {}", ec);
return;
}
acceptDone();
@@ -151,8 +151,8 @@ class ConnectionImpl : public Connection
{
if (doingWrite)
{
- BMCWEB_LOG_CRITICAL
- << "Cannot mix sendEx usage with sendBinary or sendText";
+ BMCWEB_LOG_CRITICAL(
+ "Cannot mix sendEx usage with sendBinary or sendText");
onDone();
return;
}
@@ -169,7 +169,7 @@ class ConnectionImpl : public Connection
if (ec)
{
- BMCWEB_LOG_ERROR << "Error in ws.async_write " << ec;
+ BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
self->close("write error");
}
});
@@ -210,7 +210,7 @@ class ConnectionImpl : public Connection
}
if (ec)
{
- BMCWEB_LOG_ERROR << "Error closing websocket " << ec;
+ BMCWEB_LOG_ERROR("Error closing websocket {}", ec);
return;
}
});
@@ -223,7 +223,7 @@ class ConnectionImpl : public Connection
void acceptDone()
{
- BMCWEB_LOG_DEBUG << "Websocket accepted connection";
+ BMCWEB_LOG_DEBUG("Websocket accepted connection");
if (openHandler)
{
@@ -264,7 +264,7 @@ class ConnectionImpl : public Connection
{
if (ec != boost::beast::websocket::error::closed)
{
- BMCWEB_LOG_ERROR << "doRead error " << ec;
+ BMCWEB_LOG_ERROR("doRead error {}", ec);
}
if (closeHandler)
{
@@ -306,7 +306,7 @@ class ConnectionImpl : public Connection
}
if (ec)
{
- BMCWEB_LOG_ERROR << "Error in ws.async_write " << ec;
+ BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
return;
}
doWrite();