问题
i am using glog for logging purpose when i use :
LOG(INFO) << "something";
it works as expected but when i use multiple logs like below it will not log until the program is stopped .when programm stops it will log everything as expected.
LOG(INFO) <<"111111111111111";
LOG(INFO) <<"222222222222222";
LOG(INFO) <<"333333333333333";
LOG(INFO) <<"444444444444444";
But what is confusing here is when i use LOG(WARNING) multiple times it works perfectly , i.e, it will log everything even when the program is running unlike the previous case when everything was logged when program stopped.
LOG(WARNING) <<"111111111111111";
LOG(WARNING) <<"222222222222222";
LOG(WARNING) <<"333333333333333";
LOG(WARNING) <<"444444444444444";
**any help on this behavior is greatly appreciated **
回答1:
The Problem is fairly simple. glog by default uses one log file for each severity to prevent two streams opening the same file. If you open the same file in c++
by different streams one of those (the first one to open the file) gets prioritized to write to the file. The other one can only start writing to that file, when the first stream was closed.
You either have to declare different log files for each severity or to have all log messages in one file you could simply write your own little logging library.
It seems that especially the INFO stream needs to be flushed using google::FlushLogFiles(google::INFO)
. To do that after each info you want to log I would define myself a macro to call the flush function like so:
#define log(severity, msg) LOG(severity) << msg; google::FlushLogFiles(google::severity);
This ensures that the stream will be flushed and all your messages will appear in the log file
回答2:
Although the above answer was accepted and probably helped to solve the problem, I am not sure it is the right way and even the right explanation to the problem.
If you check glog's code, you will find:
'''
define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
'''
So in the original question, LOG(INFO) will be defined as something like '''
define COMPACT_GOOGLE_LOG_INFO google::LogMessage(FILE, LINE, google::GLOG_INFO).stream()
'''
which will create a temporary stream object, and the logging content will be written to that stream object. After that, the destructor of LogMessage LogMessage::~LogMessage() will be called. Inside that destructor, Flush() will actually be called to flush the logging content to I/O device.
That is to say, for each LOG(INFO) statement, a temporary stream object will be created and destroyed, and Flush() will be called before it is destroyed. So IMHO, no additional calls to google::LogMessage::Flush() or even google::FlushLogFiles(google::INFO) should be necessary.
来源:https://stackoverflow.com/questions/35572073/logging-with-glog-is-not-working-properly