webrtc日志系统的使用
在webrtc的native开发中,除了IDE调试以外,日志调试是不可或缺的手段。本文介绍webrtc日志系统的基本使用方法。
一、日志系统的基本需求
1) 日志分级打印
2) 日志支持输出到控制台,文件,网络
3) 文件日志回滚(控制文件个数和每个文件大小)
4) 文件日志缓存(先写内存,再写磁盘)
5) 日志格式化:如添加时间,tag标志等。
6) 日志输出动态开启,关闭,动态调整优先级。
关于c/c++的开源日志系统很多,如glog, log4cplus, liblogger,EasyLogge,boost log等。遗憾是glog没有控制文件个数,可以使用一个守护进程去删日志(Linux下cron进程来完成),liblogger精简,但功能有限(没有缓存机制,模式只写一个文件,追加模式没有控制文件大小和数字),个人觉得log4cplus算是功能比较全面的一个日志系统。
二、webrtc日志的基本使用
1)最简单的使用方式
RTC_LOG(INFO) << "hello world1";
默认情况,日志打印到控制台,日志级别为INFO。
a)可以通过LogToDebug设置日志级别
rtc::LogMessage::LogToDebug(rtc::LS_INFO);
b)可以通过LogTimestamps设置时间戳
rtc::LogMessage::LogTimestamps(true);
c)打印函数名版本
RTC_LOG_F(INFO) << "hello world2";
当然基于RTC_LOG可以实现各种格式版本
2)日志打印到文件
Webrtc默认日志打印到控制台,如果需要打印到文件或网络,需要自己继承并实现LogSink这个类的接口。即在OnLogMessage 函数里面完成日志的输出(写磁盘文件,写网络socket等)。庆幸的是webrtc中的FileRotatingLogSink类帮助我们实现日志写入磁盘文件,并且FileRotatingLogSink能控制文件大小,文件个数,实现日志文件回滚,同时能控制日志文件缓存等。
class FileRotatingLogSink : public LogSink {public:// |num_log_files| must be greater than 1 and |max_log_size| must be greater// than 0.FileRotatingLogSink(const std::string& log_dir_path,const std::string& log_prefix,size_t max_log_size,size_t num_log_files);~FileRotatingLogSink() override;// Writes the message to the current file. It will spill over to the next// file if needed.void OnLogMessage(const std::string& message) override;void OnLogMessage(const std::string& message,LoggingSeverity sev,const char* tag) override;// Deletes any existing files in the directory and creates a new log file.virtual bool Init();// Disables buffering on the underlying stream.bool DisableBuffering();protected:explicit FileRotatingLogSink(FileRotatingStream* stream);private:std::unique_ptr<FileRotatingStream> stream_;RTC_DISALLOW_COPY_AND_ASSIGN(FileRotatingLogSink);};
a) 基本使用方法:
void main(){rtc::LogMessage::LogToDebug(rtc::LS_INFO);rtc::LogMessage::SetLogToStderr(true);rtc::FileRotatingLogSink ff("C:\\", "test", 1024 * 1024 * 10, 5);ff.Init();unsigned int count = 0;rtc::LogMessage::AddLogToStream(&ff, rtc::LS_INFO);bool loop = true;while (loop){RTC_LOG(INFO) << "hello world count:" << count++;}}
编译后,程序执行,生成日志如下:
从以上可知:FileRotatingLogSink实现日志的回滚(文件数目为5个,每个日志10M),日志缓存(不是每条日志直接写磁盘,而是先写内存,到一定阈值大小才写磁盘,减少磁盘IO)。这里有一个小小需求改进,默认日志文件名没有.log后缀,造成日志查看软件无法识别。由于本人有强迫症,没有文件后缀就是感觉很别扭,还是通过修改日志实现,添加了.log后缀。
