S_New4/src/logger.cpp

85 lines
1.9 KiB
C++

#include "logger.h"
Logger::Logger(std::string logFilePath)
: filePath(logFilePath)
{
if(openFile(filePath))
exit(234);
}
Logger::~Logger()
{
file.close();
}
std::string Logger::getFilePath()
{
return filePath;
}
int Logger::logCommandLine(std::string logText)
{
std::time_t now = std::time(nullptr);
struct tm *tm_now = localtime(&now);
std::string date(std::to_string(tm_now->tm_mday) + "." + std::to_string(tm_now->tm_mon +1) + "."
+ std::to_string(1900 + tm_now->tm_year) + " - " + std::to_string(tm_now->tm_hour) + ":" + std::to_string(tm_now->tm_min));
return writetoFile(date + ": \"" + logText + "\"");
}
int Logger::logSubLine(std::string line)
{
return writetoFile("\t\t" + line);
}
std::string Logger::getLogText()
{
return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}
int Logger::clearFile()
{
//close it
file.close();
//open it empty + close it
std::ofstream ofs;
ofs.open(filePath, std::ofstream::out | std::ofstream::trunc);
if(!ofs.is_open()) {
perror("Open File for clearing failed");
return 35;
}
ofs.close();
//reopen it
return openFile(filePath);
}
int Logger::writetoFile(std::string t)
{
file << t << std::endl;
return file.good();
}
int Logger::openFile(std::string path)
{
file.open(path, std::ios::in | std::ios::out | std::ios::app);
if(!file.is_open()) {
//Exestiert nicht => Erstelle Datei
std::ofstream ofs(path);
if(!ofs.is_open()) {
perror((" => Error: Konnte LogDatei nicht erstellen: '" + path + "'").c_str());
return (5656);
} else {
ofs.close();
}
file.open(path);
if(!file.is_open()) {
perror((" => Error: Konnte LogDatei nicht öffnen: '" + path + "'").c_str());
return (5657);
}
}
return 0;
}