Skip to content

Instantly share code, notes, and snippets.

@trevershick
Last active February 7, 2019 03:40
Show Gist options
  • Save trevershick/a6d451d225fa3ddb0484f655e1758950 to your computer and use it in GitHub Desktop.
Save trevershick/a6d451d225fa3ddb0484f655e1758950 to your computer and use it in GitHub Desktop.
test.cpp
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
class MyBuf : public std::streambuf {
public:
MyBuf(int maxLength, std::function<void(const char *, int)> callbackFn);
virtual ~MyBuf();
int overflow(int_type) override;
protected:
void callbackAndClear();
private:
int m_maxLength;
std::vector<char> m_buffer;
std::function<void(char *, int)> m_callbackFn;
};
class LoggerCallback {
public:
explicit LoggerCallback();
virtual ~LoggerCallback() = default;
void onLine(const char *, int);
unsigned long logged() { return m_logged; }
unsigned long ignored() { return m_ignored; }
private:
void ignore() { m_ignored++; }
void log() { m_logged++; }
private:
unsigned long m_logged;
unsigned long m_ignored;
};
LoggerCallback::LoggerCallback() : m_logged(0), m_ignored(0) {}
void LoggerCallback::onLine(const char *c, int n) {
std::string s(c, n);
#define LEVEL_EQ_LEN 6
bool isLogStatement = s.find("level=", 0) == 0;
if (!isLogStatement) {
return ignore();
}
int idx = s.find(" ", 0);
if (idx == std::string::npos) {
return ignore();
}
std::string level = s.substr(LEVEL_EQ_LEN, idx - LEVEL_EQ_LEN);
idx = s.find(" ", LEVEL_EQ_LEN + 1);
std::string content = s.substr(idx + 1, s.length() - idx);
log();
std::cout << "(" << m_logged << "," << m_ignored << ") <- level=" << level
<< " content=" << content << std::endl;
}
MyBuf::MyBuf(int maxLength, std::function<void(const char *, int)> callbackFn)
: m_maxLength(maxLength), m_callbackFn(callbackFn) {}
MyBuf::~MyBuf() { callbackAndClear(); }
void MyBuf::callbackAndClear() {
if (m_buffer.size()) {
m_callbackFn(m_buffer.data(), m_buffer.size());
m_buffer.clear();
}
}
int MyBuf::overflow(int ch) {
if (std::isprint(ch)) {
m_buffer.push_back(ch);
}
if (ch == '\n' || m_buffer.size() == m_maxLength ||
ch == std::char_traits<int>::eof()) {
callbackAndClear();
}
return 0;
}
int main() {
using namespace std::placeholders;
LoggerCallback lb;
MyBuf mb(256, std::bind(&LoggerCallback::onLine, &lb, _1, _2));
std::ostream os(&mb);
os << "level=info Test";
os << "Madeline Rocks\n";
os << "Trever\n";
os << "level=warn Test this out\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment