Reputation: 2243
Well, what good is a logger if it only keeps a record when things go well?
It is a very simple thing, the logger, that I wanted to test before I expanded it:
// Logger.h
class Logger : boost::noncopyable
{
public:
static void write(std::string const& msg, int line, std::string const& file);
private:
Logger();
private:
static std::ofstream m_sOut;
};
#define LOG(msg) Logger::write(msg, __LINE__, __FILE__)
// Logger.cpp
std::ofstream Logger::m_sOut("Logfile");
void Logger::write(const std::string &msg, int line, const std::string &file, Level level /* = Info */)
{
m_sOut << file << ": " << line << ": " << msg << "\n";
}
I fear that this is too simple. If I exit the program normally, it outputs as expected to my logfile. However, if there is a crash, there is no output.
What do I have to do to ensure that it outputs to a log regardless of a crash?
Upvotes: 0
Views: 181
Reputation: 24351
Depends on when it crashes, I would say. If it's during the log output, all bets are off.
First I would make sure that the log output gets flushed after every invocation, so I'd use std::endl
instead of \n
in write()
. You'd also have to verify that this would indeed be sufficient or if you have to take additional steps to ensure that the stream you're using doesn't buffer writes.
Edit: As pointed out in the comments, writing through to the disk without caching/buffering of any sort is slow and expensive. It's a trade off - if you absolutely must have the requirement that you can't lose any log info unless the program crashes during the log statement, you probably have to do it that way. I probably would relax that requirement a little and just rely on the behaviour of std::endl
that should result in the stream being flushed; This still leaves the buffers below the stream like the OS buffers in place but you've got a pretty good chance that you won't lose any log output.
Upvotes: 3
Reputation: 65556
I think this is requires your logging subsystem to be at least in a separately managed process and you should communicate with via a high bandwidth protocol - such as shared memory.
Upvotes: 2
Reputation: 14900
On windows, you can use SetUnhandledExceptionFilter to flush the log file.
Upvotes: 1