-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogging_ram.h
57 lines (52 loc) · 1.75 KB
/
Logging_ram.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#pragma once
#include "Logging_file.h"
#include <streambuf>
#include <string>
#include <streambuf>
#include <sstream>
#include <memory>
namespace logging {
class Ram_Buffer : public std::streambuf // derive because std::streambuf constructor is protected
{
public:
Ram_Buffer(char* start, size_t size, Logger& logger) : _logger{ &logger } { setp(start, start + size); }
void empty_buffer() { setp(pbase(), epptr()); }
auto start() const { return pbase(); }
auto pos() const { return pptr(); }
private:
int_type overflow(int_type ch) override {
_logger->flush();
sputc(ch);
return std::char_traits<char>::not_eof(0);
}
Logger* _logger;
};
/// <summary>
/// Logs to RAM and flushes to file when ram-buffer is full.
/// Mirrors to the provided ostream - typcally cout.
/// </summary>
template<typename MirrorBase = Logger>
class RAM_Logger : public File_Logger<MirrorBase> {
public:
RAM_Logger(uint16_t ramFile_size, const std::string& fileNameStem, Flags initFlags, Streamable& ostream = std::clog);
Streamable& stream() override { return _stream; }
void flush() override;
private:
std::unique_ptr<char[]> _ramFile;
Ram_Buffer _ramBuffer;
Streamable _stream;
};
template<typename MirrorBase>
RAM_Logger<MirrorBase>::RAM_Logger(uint16_t ramFile_size, const std::string& fileNameStem, Flags initFlags, Streamable& ostream)
: File_Logger<MirrorBase>{ fileNameStem, initFlags, ostream }
, _ramFile{ std::make_unique<char[]>(ramFile_size) }
, _ramBuffer{ _ramFile.get(), ramFile_size, *this }
, _stream{ &_ramBuffer } {}
template<typename MirrorBase>
void RAM_Logger<MirrorBase>::flush() {
for (char* c = _ramBuffer.start(); c < _ramBuffer.pos(); ++c) {
File_Logger<MirrorBase>::stream() << *c;
}
_ramBuffer.empty_buffer();
}
}