Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions include/lemlog/logger/sinks/sd-card.hpp
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
#pragma once

#include "lemlog/logger/logger.hpp"
#include <vector>

namespace logger {
/**
* @brief SD card class. Outputs all data to the SD card connected to the brain.
*/
class SDCard : public Sink {
public:
SDCard(std::string filename = ".log", bool logTimestamp = true);
SDCard(std::string filename = ".log", bool logTimestamp = true,
int cacheSize = 10);
void send(Level level, std::string topic, std::string message) override;
private:
std::string formatTimestamp(long long ms);

// cache of messages
std::vector<std::string> cache;

std::string filename;
bool logTimestamp;
int cacheSize;
};
}
} // namespace logger
29 changes: 23 additions & 6 deletions src/lemlog/logger/sinks/sd-card.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
#include <fstream>

namespace logger {
SDCard::SDCard(std::string filename, bool logTimestamp) : filename("/usd/" + filename), logTimestamp(logTimestamp) {}
SDCard::SDCard(std::string filename, bool logTimestamp, int cacheSize)
: filename("/usd/" + filename),
logTimestamp(logTimestamp),
cacheSize(cacheSize) {
this->cache = std::vector<std::string>();
}

std::string SDCard::formatTimestamp(long long ms) {
// use the % operator to get the remainder of the division
Expand All @@ -25,8 +30,11 @@ void SDCard::send(Level level, std::string topic, std::string message) {
// output: <time> [LEVEL] (topic) message
std::string output = "";

if (this->logTimestamp) output += this->formatTimestamp((long long) pros::millis());
// if the timestamp is enabled, add it to the message
if (this->logTimestamp)
output += this->formatTimestamp((long long)pros::millis());

// add the level to the message
switch (level) {
case (Level::DEBUG): {
output += " [DEBUG]";
Expand All @@ -48,8 +56,17 @@ void SDCard::send(Level level, std::string topic, std::string message) {

output += " (" + topic + ") " + message + "\n";

std::ofstream file(this->filename);
file << output;
file.close();
// add the message to the cache
this->cache.push_back(output);

// if the cache is full, write it to the file
if (this->cache.size() >= this->cacheSize) {
std::ofstream file(this->filename, std::ios::app);
for (std::string& line : this->cache) {
file << line;
}
file.close();
this->cache.clear();
}
}
}
} // namespace logger
Loading