Skip to content

Instantly share code, notes, and snippets.

@jupp0r
Last active March 28, 2017 03:36
Show Gist options
  • Save jupp0r/2d68dd843dcba7eb9a9bcad0d1f18c47 to your computer and use it in GitHub Desktop.
Save jupp0r/2d68dd843dcba7eb9a9bcad0d1f18c47 to your computer and use it in GitHub Desktop.
Structured logging adapter for C++
#pragma once
#include <vector>
#include <string>
#include <iostream>
class LogContext
{
public:
template <typename T>
LogContext With(const std::string&, T) const;
friend std::ostream& operator<<(std::ostream&, const LogContext&);
private:
std::vector<std::pair<<std::string, std::string>> metadata;
};
template <typename T>
inline LogContext LogContext::With(const std::string& key, T value) const
{
auto ctx = *this;
std::stringstream ss;
ss << std::boolalpha << value;
ctx.metadata.push_back({key, ss.str()});
return ctx;
}
template <>
inline LogContext LogContext::With(const std::string& key, uint8_t value) const
{
auto ctx = *this;
ctx.metadata.push_back({key, std::to_string(value)});
return ctx;
}
inline std::ostream& operator<<(std::ostream& os, const LogContext& ctx)
{
for(const auto& kvPair : ctx.metadata) {
os << kvPair.first << "=";
bool valueContainsSpaces = kvPair.second.find(' ') != std::string::npos;
if (valueContainsSpaces) {
os << '"';
}
os << kvPair.second;
if (valueContainsSpaces) {
os << '"';
}
os << ' ';
}
return os;
}
#include <iostream>
#include "LogContext.h"
int main(int argc, char** argv) {
auto ctx = LogContext().With("connectionId", "abcdef").With("sessionId", 1235123).With("outbound", true);
std::cout << ctx.With("msg", "this is a test message") << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment