I'm currently making a game using C++. I eventually needed a logger, but I wasn't satisfied with any of the existing solutions. After a while, I wrote my own header called log.h:
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <fstream>
#include <sstream>
class Logger {
private:
std::string logFileName = "log.txt";
bool print = true;
bool save = true;
void log(std::string s, std::string i) {
time_t cuT;
struct tm *loT;
time(&cuT);
loT = localtime(&cuT);
std::stringstream ss;
ss << std::setw(2) << std::setfill('0') << loT->tm_hour << ':';
ss << std::setw(2) << std::setfill('0') << loT->tm_min << ':';
ss << std::setw(2) << std::setfill('0') << loT->tm_sec;
ss << i << s << "\n";
if(save) {
std::ofstream of;
of.open(logFileName, std::ios_base::app | std::ios::out);
of << ss.rdbuf();
}
if(print) {
std::cout << ss.str();
}
}
public:
void configure(std::string logFileName_, bool print_, bool save_) {
this->print = print_;
this->save = save_;
this->logFileName = logFileName_;
}
void note(std::string s) {
log(s, " NOTE: ");
}
void error(std::string s) {
log(s, " ERROR: ");
}
void warn(std::string s) {
log(s, " WARNING: ");
}
};
My library can print the current time as well as other information to the console and save this data into a file. But I did a couple of benchmarks and it turns out that my logging program is a lot slower compared to the normal std::cout.
Since speed is crucial for games, I wanted to ask whether there are ways to optimize my program or, if necessary, to improve it.
const std::string&
to avoid copy 2) add the constructor, which callconfigure
function \$\endgroup\$