Skip to content

Commit

Permalink
Serialize floating values locale-independent
Browse files Browse the repository at this point in the history
Closes: #281
  • Loading branch information
gjasny committed Jun 25, 2019
1 parent fb64de9 commit 197ff47
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
9 changes: 8 additions & 1 deletion core/src/text_serializer.cc
Expand Up @@ -2,7 +2,9 @@

#include <cmath>
#include <limits>
#include <locale>
#include <ostream>
#include <sstream>

namespace prometheus {

Expand All @@ -16,7 +18,12 @@ std::string ToString(double v) {
if (std::isinf(v)) {
return (v < 0 ? "-Inf" : "+Inf");
}
return std::to_string(v);
std::ostringstream ss;
ss.imbue(std::locale::classic());
ss.setf(std::ios::fixed, std::ios::floatfield);
ss.precision(6);
ss << v;
return ss.str();
}

const std::string& EscapeLabelValue(const std::string& value,
Expand Down
1 change: 1 addition & 0 deletions core/tests/CMakeLists.txt
Expand Up @@ -7,6 +7,7 @@ add_executable(prometheus_test
gauge_test.cc
histogram_test.cc
registry_test.cc
serializer_test.cc
summary_test.cc
utils_test.cc
)
Expand Down
30 changes: 30 additions & 0 deletions core/tests/serializer_test.cc
@@ -0,0 +1,30 @@
#include "prometheus/counter.h"
#include "prometheus/family.h"
#include "prometheus/text_serializer.h"

#include <gmock/gmock.h>
#include <locale>

namespace prometheus {
namespace {

TEST(SerializerTest, shouldSerializeLocaleIndependent) {
Family<Counter> family{"requests_total", "", {}};
auto& counter = family.Add({});
counter.Increment();
const auto collected = family.Collect();

// save and change locale
const std::locale oldLocale = std::locale::classic();
std::locale::global(std::locale("de_DE.UTF-8"));

TextSerializer textSerializer;
const auto serialized = textSerializer.Serialize(collected);
EXPECT_THAT(serialized, testing::HasSubstr("1.0"));

// restore locale
std::locale::global(oldLocale);
}

} // namespace
} // namespace prometheus

0 comments on commit 197ff47

Please sign in to comment.