improve logger function

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
void writeToLog(){
string fileName = "/home/j/s/textFiles/logMPU.txt";
string line = "";
int lines = 0;
ifstream file(fileName.c_str());
string d_txtFileInArray = new string[1002];
bool b_txtFileInArray = true;
if(file.is_open())
{
while(getline(file, line)) {
d_txtFileInArray[LinesInFolder] = line;
lines++;

}
file.close();
}


}

const char *srcFile = fileName.c_str();
ofstream outPrintFile(srcFile, ios::out);

for(int i = 0; i<arrayDepth; i++)
{
outPrintFile << fileInArray[i]; 
outPrintFile << endl;
}

    }


This function designed to save some log to file, but by unknown reason data from file gets removed...
I suppose it accesses the file when its empty and writes it as empty (maybe some other form of double access)
Maybe indent it to start with.

And what does the 2nd part of the code have to do with the first?
Like what's arrayDepth
It is unclear what your goal is here. Are you simply trying to limit the log file to 1002 lines?

Make sure to turn your compiler warnings all the way up. Line 6 should definitely be showing an error.

What is typically done is to open a log file for append using the std::ios::app flag. (You do not need to specify automatic flags.)

1
2
3
4
5
std::ofstream logFile( my_log_file_name.c_str(), std::ios::app );

...

logFile << "stuff" << std::endl;  // automatically written to end of file 


If you want to limit the file size, I recommend you do that at some point when normal logging operations are not happening, either before your program starts or when it properly terminates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void toss_old_log_lines( const std::size_t MAX_NUM_LOG_LINES = 1002 )
{
  std::vector<std::string> lines;
  {
    std::ifstream f( my_log_file_name.c_str() );
    std::string s;
    while (getline( f, s ))
      lines.push_back( s );
  }

  if (lines.count() <= MAX_NUM_LOG_LINES) return;

  std::ofstream f( my_log_file_name.c_str() );  // open file for REWRITE
  auto n = MAX_NUM_LOG_LINES - lines.count();   // skip the lines to toss
  while (n < MAX_NUM_LOG_LINES)                 // write the remainder
    f << lines[n++] << '\n';
}

That is just one (very simple) way to do it. Caveats apply.
Last edited on
Possibly something like which when adding a new line to the log file and the file then contains more then the required number of lines removes earlier lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>

void writeToLog(const std::string& log) {
	static constexpr const char* fileName { "/home/j/s/textFiles/logMPU.txt" };
	static constexpr size_t maxLines {1002};

	if (std::ofstream outFile(fileName, std::ios::app); outFile.is_open())
		outFile << log << '\n';

	if (std::ifstream inFile(fileName); inFile.is_open()) {
		const std::vector<std::string> d_txtFileInArray((std::istream_iterator<std::string>(inFile)), (std::istream_iterator<std::string>()));

		if (inFile.close(); d_txtFileInArray.size() > maxLines) {
			std::ofstream outFile(fileName);

			std::copy(d_txtFileInArray.begin() + (d_txtFileInArray.size() - maxLines), d_txtFileInArray.end(), std::ostream_iterator<std::string>(outFile, "\n"));
		}
	}
}

Last edited on
Doing it with every write would get expensive really fast, tho...
if its anything other than just a dump, eg you are doing fancy stuff like keeping 1000 lines, then keep a line buffer (eg a circular buffer of strings or something else simple) and once it reaches the limit (every line is populated) then open the file, dump your whole buffer to it in binary quick write approach, then close it. If you don't have the whole buffer full, you can either do the same or append to existing, both are plenty efficient.
Instead of re-inventing the wheel, maybe you want to consider using the logging capabilities provided by the system:
https://linux.die.net/man/3/syslog
https://learn.microsoft.com/de-de/windows/win32/api/debugapi/nf-debugapi-outputdebugstringw
https://learn.microsoft.com/en-us/windows/win32/eventlog/event-logging-functions

There also are dedicated logging libraries for C++ available, e.g.:
https://github.com/log4cplus/log4cplus/wiki
Last edited on
Much depends, of course, on the usage of the logger and it's required resilience, multi-threading, loading etc etc etc
Topic archived. No new replies allowed.