I have basic logging process. When an error occured in the program, it has to been logging to a .txt file. I use following code for this:
#include <fstream>
fileName = "logs/error_log.txt";
ofstream myfile;
myfile.open (fileName,fstream::app);
myfile << serialized_string << endl;
myfile.close();
When an error occured it goes to error_log.txt file successfully. But when program crashed and is restarted afterward, new logs are not logged as append. As expected the way I am using creates a new file which has same name existed file and write on it. Can someone explain me how should I write older logs as well?
Edit: These are steps I have faced: I am using raspbian and I compile with following:
g++ main.cpp -lwiringPi -lpthread -lcurl -o test
That is the whole function.
int putLog(const char* process, int logType, string logData) {
isLoggerBusy = true;
string fileName;
std::string color;
switch (logType) {
case 0:
fileName = "logs/error_log.txt";
// color = "\033[0;31m";
break;
case 1:
fileName = "logs/info_log.txt";
// color = "\033[0;36m";
break;
case 2:
fileName = "logs/state_log.txt";
// color = "\033[1;33m";
break;
}
if (process == "WebSocket") {
color = "\033[1;32m";
}
json j = {
{"Process", process}, {"Time", currentDateTime()}, {"Log", logData}};
string serialized_string = j.dump();
fix_utf8_string(serialized_string);
ofstream myfile;
myfile.open(fileName, fstream::app);
cout << color << serialized_string << '\n';
myfile << serialized_string << endl;
myfile.close();
isLoggerBusy = false;
cout << "\033[0m" << endl;
return 0;
}
- I started the program. It write downs these lines to the state_logs.txt
{"Log":"Incoming Message{\"Action\":\"Heartbeat\",\"Data\":null}","Process":"WebSocket","Time":"2018-08-16.14:53:52"}
{"Log":"GSM Setup Finished","Process":"SMSService","Time":"2018-08-16.14:54:13"}
- Stopped the program with CTRL-C and control the state_logs.txt and I can see now two lines there.
- Restart the program and interrupt with CTRC-C again in 10 seconds (before a new line logging.)
- I check the state_logs.txt again and now I can not see nothing. Re-did this process but this time waiting a bit more before interrupt program(just a bit more to get only one line of log.). So now I can see only one and timestamps has been changed.