A few days ago, I was asking about operator overloading to my Logger project. Now I have another problem which I'm not able to solve - probably due to my low experience.
First - my Logger
object (which is designed as a Singleton object) should write to a file created in the same directory as the source code. Desired use looks this way:
logger << "log message text";
So I have created a singleton object logger
, but I need to make some controls before the first logger
use, e.g. if the file already exists, if it is empty, etc. All the member functions which provide that I've already created or I will.
What's the point? I need somehow to check all these things before the first and every use of the logger
. And I want them to be made automatically, so the possible user won't have to do that manually.
So, let´s summarize... let's say I want to use it for the first time, so I put this line to my code:
logger << "Log something";
Before it will make the log itself, I need the Logger
class to check if:
- the log file already exists
- if no, create one
- if yes, find the end and continue on the next line.
CodePudding user response:
Where does your Logger
open the file to begin with? Why aren't you doing these checks at the point where the file is being opened?
This sounds like something you should be handling in your Logger
's constructor, for instance.
And, rather than defining a global logger
object, consider defining a static
method in your Logger
class instead, eg:
class Logger {
private:
Logger() {
// perform checks here...
// open/create log file as needed...
}
public:
~Logger() {
// close log file...
}
static Logger& GetLogger() {
static Logger logger;
return logger;
}
// other methods/operators as needed...
};
...
Logger::GetLogger() << "Log something";
Then the Logger
constructor won't run until the first time GetLogger()
is called.