Skip to content

Commit dae39a3

Browse files
authored
Migrate to std::format logger (#55)
Migrate to std format logger
1 parent ee52ec5 commit dae39a3

File tree

10 files changed

+60
-78
lines changed

10 files changed

+60
-78
lines changed

CMakeLists.txt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
cmake_minimum_required(VERSION 3.5.0)
1+
cmake_minimum_required(VERSION 3.8.0)
22

33
#if (NOT DEFINED VCPKG_TARGET_TRIPLET)
44
if(WIN32)
@@ -95,7 +95,7 @@ file(GLOB_RECURSE SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
9595
file(GLOB_RECURSE HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.hpp")
9696
add_library("${PROJECT_NAME}_static" STATIC ${SOURCES} ${PROTO_HEADER} ${PROTO_SRC})
9797
target_link_libraries("${PROJECT_NAME}_static" PUBLIC ${DEPS_LIBS})
98-
set_property(TARGET "${PROJECT_NAME}_static" PROPERTY CXX_STANDARD 17)
98+
set_property(TARGET "${PROJECT_NAME}_static" PROPERTY CXX_STANDARD 20)
9999
include_directories("${PROJECT_NAME}_static" PUBLIC ${DEPS_INCLUDES} ${Protobuf_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})
100100
if(UNIX)
101101
target_compile_options("${PROJECT_NAME}_static" PRIVATE "-fPIC")
@@ -106,15 +106,15 @@ endif()
106106
file(GLOB_RECURSE DRIVER_MAIN "${CMAKE_CURRENT_SOURCE_DIR}/src/DriverFactory.cpp")
107107
add_library("${PROJECT_NAME}" SHARED ${DRIVER_MAIN} ${HEADERS} ${PROTO_HEADER})
108108
target_link_libraries("${PROJECT_NAME}" PUBLIC "${PROJECT_NAME}_static")
109-
set_property(TARGET "${PROJECT_NAME}" PROPERTY CXX_STANDARD 17)
109+
set_property(TARGET "${PROJECT_NAME}" PROPERTY CXX_STANDARD 20)
110110

111111
# compile tests
112112
function(build_tests target_name test_dir)
113113
file(GLOB TESTS "${CMAKE_CURRENT_SOURCE_DIR}/${test_dir}/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/${test_dir}/*.hpp")
114114
file(GLOB TESTS_COMMON "${CMAKE_CURRENT_SOURCE_DIR}/test/common/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/test/common/*.hpp")
115115
add_executable(${target_name} ${TESTS} ${TESTS_COMMON} ${HEADERS} ${PROTO_HEADER})
116116
target_link_libraries(${target_name} PUBLIC "${PROJECT_NAME}_static" Catch2::Catch2WithMain)
117-
set_property(TARGET ${target_name} PROPERTY CXX_STANDARD 17)
117+
set_property(TARGET ${target_name} PROPERTY CXX_STANDARD 20)
118118
endfunction()
119119
build_tests(tests "test")
120120
build_tests(tests_integration "test/integration")

src/Logger.cpp

Lines changed: 0 additions & 33 deletions
This file was deleted.

src/Logger.hpp

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
#pragma once
22
#include <thread>
33
#include <mutex>
4-
#include <vector>
5-
#include <sstream>
6-
#include <cstdarg>
4+
#include <format>
5+
#include <string>
6+
#include <iostream>
77
#include <openvr_driver.h>
88

99
class Logger {
1010
public:
1111
Logger() : name_("") { }
1212
Logger(const std::string& name) : name_(name) { }
13-
void Log(const char* format, ...);
13+
template<typename... Args>
14+
void Log(const std::format_string<Args...> format_str, Args&&... args) {
15+
std::string message = std::vformat(format_str.get(), std::make_format_args(args...));
16+
std::string prefixed = name_.length() ? std::format("{}: {}", name_, message) : message;
17+
std::lock_guard<std::mutex> lock(mutex_);
18+
LogImpl(prefixed.c_str());
19+
};
1420
protected:
1521
virtual void LogImpl(const char* string) = 0;
1622
std::string name_;
@@ -26,11 +32,15 @@ class NullLogger: public Logger {
2632
class ConsoleLogger: public Logger {
2733
using Logger::Logger;
2834
protected:
29-
void LogImpl(const char* message) override;
35+
void LogImpl(const char* message) override {
36+
std::cout << message << '\n' << std::flush;
37+
}
3038
};
3139

3240
class VRLogger: public Logger {
3341
using Logger::Logger;
3442
protected:
35-
void LogImpl(const char* message) override;
36-
};
43+
void LogImpl(const char* message) override {
44+
vr::VRDriverLog()->Log(message);
45+
}
46+
};

src/TrackerDevice.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ vr::TrackedDeviceIndex_t SlimeVRDriver::TrackerDevice::GetDeviceIndex() {
142142
vr::EVRInitError SlimeVRDriver::TrackerDevice::Activate(uint32_t unObjectId) {
143143
device_index_ = unObjectId;
144144

145-
logger_->Log("Activating tracker %s", serial_.c_str());
145+
logger_->Log("Activating tracker {}", serial_);
146146

147147
// Get the properties handle
148148
auto props = GetDriver()->GetProperties()->TrackedDeviceToPropertyContainer(device_index_);

src/VRDriver.cpp

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ vr::EVRInitError SlimeVRDriver::VRDriver::Init(vr::IVRDriverContext* pDriverCont
1919
auto path = std::string { doc.get_object()["config"].at(0).get_string().value() };
2020
default_chap_path_ = GetDefaultChaperoneFromConfigPath(path);
2121
} catch (simdjson::simdjson_error& e) {
22-
logger_->Log("Error getting VR Config path, continuing: %s", e.error());
22+
logger_->Log("Error getting VR Config path, continuing (error code {})", std::to_string(e.error()));
2323
}
2424

2525
logger_->Log("SlimeVR Driver Loaded Successfully");
@@ -92,7 +92,7 @@ void SlimeVRDriver::VRDriver::RunPoseRequestThread() {
9292
}
9393
}
9494
} else if (universe_error != last_universe_error_) {
95-
logger_->Log("Failed to find current universe: Prop_CurrentUniverseId_Uint64 error = %s",
95+
logger_->Log("Failed to find current universe: Prop_CurrentUniverseId_Uint64 error = {}",
9696
vr::VRPropertiesRaw()->GetPropErrorNameFromEnum(universe_error)
9797
);
9898
}
@@ -218,7 +218,7 @@ void SlimeVRDriver::VRDriver::OnBridgeMessage(const messages::ProtobufMessage& m
218218
{ messages::TrackerStatus_Status_BUSY, "BUSY" },
219219
};
220220
if (status_map.count(status.status())) {
221-
logger_->Log("Tracker status id %i status %s", status.tracker_id(), status_map.at(status.status()).c_str());
221+
logger_->Log("Tracker status id {} status {}", status.tracker_id(), status_map.at(status.status()));
222222
}
223223
}
224224
} else if (message.has_battery()) {
@@ -280,19 +280,19 @@ bool SlimeVRDriver::VRDriver::AddDevice(std::shared_ptr<IVRDevice> device) {
280280
devices_.push_back(device);
281281
devices_by_id_[device->GetDeviceId()] = device;
282282
devices_by_serial_[device->GetSerial()] = device;
283-
logger_->Log("New tracker device added %s (id %i)", device->GetSerial().c_str(), device->GetDeviceId());
283+
logger_->Log("New tracker device added {} (id {})", device->GetSerial(), device->GetDeviceId());
284284
} else {
285-
logger_->Log("Failed to add tracker device %s (id %i)", device->GetSerial().c_str(), device->GetDeviceId());
285+
logger_->Log("Failed to add tracker device {} (id {})", device->GetSerial(), device->GetDeviceId());
286286
return false;
287287
}
288288
} else {
289289
std::shared_ptr<IVRDevice> oldDevice = devices_by_serial_[device->GetSerial()];
290290
if (oldDevice->GetDeviceId() != device->GetDeviceId()) {
291291
devices_by_id_[device->GetDeviceId()] = oldDevice;
292292
oldDevice->SetDeviceId(device->GetDeviceId());
293-
logger_->Log("Device overridden from id %i to %i for serial %s", oldDevice->GetDeviceId(), device->GetDeviceId(), device->GetSerial());
293+
logger_->Log("Device overridden from id {} to {} for serial {}", oldDevice->GetDeviceId(), device->GetDeviceId(), device->GetSerial());
294294
} else {
295-
logger_->Log("Device readded id %i, serial %s", device->GetDeviceId(), device->GetSerial().c_str());
295+
logger_->Log("Device readded id {}, serial {}", device->GetDeviceId(), device->GetSerial());
296296
}
297297
}
298298
return true;
@@ -407,7 +407,7 @@ std::optional<SlimeVRDriver::UniverseTranslation> SlimeVRDriver::VRDriver::Searc
407407
}
408408
}
409409
} catch (simdjson::simdjson_error& e) {
410-
logger_->Log("Error getting universes from %s: %s", path.c_str(), e.what());
410+
logger_->Log("Error getting universes from {}: {}", path, e.what());
411411
return std::nullopt;
412412
}
413413

src/bridge/BridgeClient.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,20 +37,20 @@ void BridgeClient::CreateConnection() {
3737
connection_handle_ = GetLoop()->resource<uvw::pipe_handle>(false);
3838
connection_handle_->on<uvw::connect_event>([this, path](const uvw::connect_event&, uvw::pipe_handle&) {
3939
connection_handle_->read();
40-
logger_->Log("[%s] connected", path.c_str());
40+
logger_->Log("[{}] connected", path);
4141
connected_ = true;
4242
last_error_ = std::nullopt;
4343
});
4444
connection_handle_->on<uvw::end_event>([this, path](const uvw::end_event&, uvw::pipe_handle&) {
45-
logger_->Log("[%s] disconnected", path.c_str());
45+
logger_->Log("[{}] disconnected", path);
4646
Reconnect();
4747
});
4848
connection_handle_->on<uvw::data_event>([this](const uvw::data_event& event, uvw::pipe_handle&) {
4949
OnRecv(event);
5050
});
5151
connection_handle_->on<uvw::error_event>([this, path](const uvw::error_event& event, uvw::pipe_handle&) {
5252
if (!last_error_.has_value() || last_error_ != event.what() || last_path_ != path) {
53-
logger_->Log("[%s] pipe error: %s", path.c_str(), event.what());
53+
logger_->Log("[{}] pipe error: {}", path, event.what());
5454
last_error_ = event.what();
5555
last_path_ = path;
5656
}

src/bridge/BridgeTransport.cpp

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ void BridgeTransport::ResetBuffers() {
6969

7070
void BridgeTransport::OnRecv(const uvw::data_event& event) {
7171
if (!recv_buf_.Push(event.data.get(), event.length)) {
72-
logger_->Log("recv_buf_.Push(%i) failed", event.length);
72+
logger_->Log("recv_buf_.Push({}) failed", event.length);
7373
ResetConnection();
7474
return;
7575
}
@@ -81,13 +81,16 @@ void BridgeTransport::OnRecv(const uvw::data_event& event) {
8181
char len_buf[4];
8282
recv_buf_.Peek(len_buf, 4);
8383
uint32_t size = 0;
84-
size |= static_cast<uint32_t>(len_buf[0]) << 0;
85-
size |= static_cast<uint32_t>(len_buf[1]) << 8;
86-
size |= static_cast<uint32_t>(len_buf[2]) << 16;
87-
size |= static_cast<uint32_t>(len_buf[3]) << 24;
84+
size |= static_cast<uint32_t>(static_cast<uint8_t>(len_buf[0])) << 0;
85+
size |= static_cast<uint32_t>(static_cast<uint8_t>(len_buf[1])) << 8;
86+
size |= static_cast<uint32_t>(static_cast<uint8_t>(len_buf[2])) << 16;
87+
size |= static_cast<uint32_t>(static_cast<uint8_t>(len_buf[3])) << 24;
8888

8989
if (size > VRBRIDGE_MAX_MESSAGE_SIZE) {
90-
logger_->Log("message size overflow");
90+
logger_->Log(
91+
"message size overflow: {} > {}",
92+
size, VRBRIDGE_MAX_MESSAGE_SIZE
93+
);
9194
ResetConnection();
9295
return;
9396
}
@@ -97,7 +100,7 @@ void BridgeTransport::OnRecv(const uvw::data_event& event) {
97100

98101
auto message_buf = std::make_unique<char[]>(size);
99102
if (!recv_buf_.Skip(4) || !recv_buf_.Pop(message_buf.get(), unwrapped_size)) {
100-
logger_->Log("recv_buf_.Pop(%i) failed", size);
103+
logger_->Log("recv_buf_.Pop({}) failed", size);
101104
ResetConnection();
102105
return;
103106
}

test/BridgeServerMock.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,35 +27,35 @@ using namespace std::literals::chrono_literals;
2727
void BridgeServerMock::CreateConnection() {
2828
std::string path = GetBridgePath();
2929

30-
logger_->Log("[%s] listening", path.c_str());
30+
logger_->Log("[{}] listening", path);
3131

3232
server_handle_ = GetLoop()->resource<uvw::pipe_handle>(false);
3333
server_handle_->on<uvw::listen_event>([this, path](const uvw::listen_event &event, uvw::pipe_handle &) {
34-
logger_->Log("[%s] new client", path.c_str());
34+
logger_->Log("[{}] new client", path);
3535
ResetBuffers();
3636

3737
/* ipc = false -> pipe will be used for handle passing between processes? no */
3838
connection_handle_ = GetLoop()->resource<uvw::pipe_handle>(false);
3939

4040
connection_handle_->on<uvw::end_event>([this, path](const uvw::end_event &, uvw::pipe_handle &) {
41-
logger_->Log("[%s] disconnected", path.c_str());
41+
logger_->Log("[{}] disconnected", path);
4242
StopAsync();
4343
});
4444
connection_handle_->on<uvw::data_event>([this](const uvw::data_event &event, uvw::pipe_handle &) {
4545
OnRecv(event);
4646
});
4747
connection_handle_->on<uvw::error_event>([this, path](const uvw::error_event &event, uvw::pipe_handle &) {
48-
logger_->Log("[%s] pipe error: %s", path.c_str(), event.what());
48+
logger_->Log("[{}] pipe error: {}", path, event.what());
4949
StopAsync();
5050
});
5151

5252
server_handle_->accept(*connection_handle_);
53-
logger_->Log("[%s] connected", path.c_str());
53+
logger_->Log("[{}] connected", path);
5454
connected_ = true;
5555
connection_handle_->read();
5656
});
5757
server_handle_->on<uvw::error_event>([this, path](const uvw::error_event &event, uvw::pipe_handle &) {
58-
logger_->Log("[%s] bind error: %s", path.c_str(), event.what());
58+
logger_->Log("[{}] bind error: {}", path, event.what());
5959
StopAsync();
6060
});
6161

test/TestSleepTimes.cpp

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <vector>
77
#include <algorithm>
88
#include <numeric>
9+
#include <Logger.hpp>
910

1011
TEST_CASE("Sleep times") {
1112
const int sleep_duration_ms = 2;
@@ -14,7 +15,8 @@ TEST_CASE("Sleep times") {
1415
std::vector<long long> sleep_times;
1516
sleep_times.reserve(num_iterations);
1617

17-
printf("Benching std::this_thread::sleep_for(std::chrono::milliseconds(%i));\n", sleep_duration_ms);
18+
auto logger = std::static_pointer_cast<Logger>(std::make_shared<ConsoleLogger>(""));
19+
logger->Log("Benching std::this_thread::sleep_for(std::chrono::milliseconds({}));", sleep_duration_ms);
1820
auto start_time = std::chrono::high_resolution_clock::now();
1921
while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start_time).count() < benchmark_duration_sec) {
2022
auto iteration_start_time = std::chrono::high_resolution_clock::now();
@@ -31,7 +33,7 @@ TEST_CASE("Sleep times") {
3133
const double avg_time_ms = static_cast<double>(std::accumulate(sleep_times.begin(), sleep_times.end(), 0LL)) / num_samples / 1000;
3234
const double p1_time_ms = static_cast<double>(sleep_times[p1_index]) / 1000;
3335
const double p99_time_ms = static_cast<double>(sleep_times[p99_index]) / 1000;
34-
printf("p1: %.3lf ms %.3lf tps\n", p1_time_ms, 1e3 / p1_time_ms);
35-
printf("avg: %.3lf ms %.3lf tps\n", avg_time_ms, 1e3 / avg_time_ms);
36-
printf("p99: %.3lf ms %.3lf tps\n", p99_time_ms, 1e3 / p99_time_ms);
36+
logger->Log("p1: {:.3f} ms {:.3f} tps", p1_time_ms, 1e3 / p1_time_ms);
37+
logger->Log("avg: {:.3f} ms {:.3f} tps", avg_time_ms, 1e3 / avg_time_ms);
38+
logger->Log("p99: {:.3f} ms {:.3f} tps", p99_time_ms, 1e3 / p99_time_ms);
3739
}

test/common/TestBridgeClient.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
void TestLogTrackerAdded(std::shared_ptr<Logger> logger, const messages::ProtobufMessage& message) {
44
if (!message.has_tracker_added()) return;
55
messages::TrackerAdded tracker_added = message.tracker_added();
6-
logger->Log("tracker added id %i name %s role %i serial %s",
6+
logger->Log("tracker added id {} name {} role {} serial {}",
77
tracker_added.tracker_id(),
8-
tracker_added.tracker_name().c_str(),
8+
tracker_added.tracker_name(),
99
tracker_added.tracker_role(),
10-
tracker_added.tracker_serial().c_str()
10+
tracker_added.tracker_serial()
1111
);
1212
}
1313

@@ -21,7 +21,7 @@ void TestLogTrackerStatus(std::shared_ptr<Logger> logger, const messages::Protob
2121
{ messages::TrackerStatus_Status_BUSY, "BUSY" },
2222
};
2323
if (status_map.count(status.status())) {
24-
logger->Log("tracker status id %i status %s", status.tracker_id(), status_map.at(status.status()).c_str());
24+
logger->Log("tracker status id {} status {}", status.tracker_id(), status_map.at(status.status()));
2525
}
2626
}
2727

@@ -127,7 +127,7 @@ void TestBridgeClient() {
127127
for (const auto& [id, sum] : latency_nanos_sum) {
128128
auto avg_latency_nanos = static_cast<int>(latency_nanos_count[id] ? sum / latency_nanos_count[id] : -1);
129129
auto avg_latency_ms = duration_cast<duration<double, std::milli>>(nanoseconds(avg_latency_nanos));
130-
logger->Log("avg latency for tracker %i: %.3fms", id, avg_latency_ms.count());
130+
logger->Log("avg latency for tracker {}: {:.3f}ms", id, avg_latency_ms.count());
131131
}
132132

133133
if (invalid_messages) FAIL("Invalid messages received");

0 commit comments

Comments
 (0)