一、定义类
class FileLog : public rtc::LogSink {
public:
FileLog(const std::string& LogPath)
:logfile_(NULL),
log_path_(LogPath){}
virtual ~FileLog() {
if (logfile_) {
fclose(logfile_);
logfile_ = NULL;
}
}
inline void FileDate() {
char logdate[125];
time_t curtm;
struct tm* tm_info;
curtm = time(NULL);
tm_info = localtime(&curtm);
strftime(logdate, sizeof(logdate), "%Y-%m-%d_%H-%M-%S", tm_info);
logfileName_ = log_path_+"webrtc_"+logdate+".log";
}
inline size_t Size()
{
size_t size = 0;
if (logfile_ != NULL) {
size = filelength(fileno(logfile_));
}
return size;
}
inline void Start(void)
{
#define MAX_LOG_FILE_SIZE (1024*1024)
if (NULL == logfile_) {
FileDate();
logfile_ = fopen(logfileName_.c_str(), "w");
}
else if (Size() > MAX_LOG_FILE_SIZE)
{
Close();
FileDate();
logfile_ = fopen(logfileName_.c_str(), "w");
}
}
inline void Close(void)
{
if(logfile_) {
fclose(logfile_);
logfile_ = NULL;
}
}
virtual void OnLogMessage(const std::string& message) {
rtc::CritScope lock(&log_crit_);
Start();
if (NULL == logfile_)
return;
if(fwrite(message.c_str(), 1, message.length(), logfile_) < 0) {
Close();
} else if(fflush(logfile_) < 0) {
Close();
}
}
private:
FILE* logfile_;
const std::string log_path_;
std::string logfileName_;
rtc::CriticalSection log_crit_;
};
二、调用类
rtc::LoggingSeverity min_sev = rtc::LS_ERROR;
switch (webrtc_log_level)
{
case 1 :
min_sev = rtc::LS_ERROR;
break;
case 2 :
min_sev = rtc::LS_WARNING;
break;
case 3 :
min_sev = rtc::LS_INFO;
break;
}
FileLog* _LogStream = new FileLog("logs");
rtc::LogMessage::AddLogToStream(_LogStream, min_sev);