Solved the problem that boost::log will clear the contents of the previous log file when restarting

1. The boost::log log
needs to generate logs while debugging in the application. QT has encapsulated log levels (debug, info...), but in the UOS system, the debug level log cannot be displayed, and boost::log can be more flexible. Set your own log level.

boost::log official documentation

sinkIt is the log receiver of boost::log and is automatically registered to the log core. If no log file is specified, the log information will be output to the console by default
shared_ptr: boost's smart shared pointer make_sharedis its factory function.

//text_ostream_backend 将日志记录化为一个或多个字符流
boost::shared_ptr< boost::log::sinks::text_ostream_backend > m_backend;
m_backend = boost::make_shared< boost::log::sinks::text_ostream_backend >();
m_backend->add_stream(
boost::shared_ptr< std::ostream >( &std::clog, boost::null_deleter()));

The following function is used to use the file corresponding to the path path as a log file object, so that the log information is written to this file.

//下面函数中用到的m_log_path声明在.h文件中,用于保存日志文件对象
boost::filesystem::path m_log_path;

// 设定设定日志文件,并创建文件日志对象。原有对象将被替换成新的。
void  LogMgr::_LogPath(const boost::filesystem::path logpath) {
    
    

    // 如果文件名相同,则直接退出
	if (m_log_path == logpath) {
    
    
        qDebug()<<"m_log_fstream"<<m_log_fstream.get();
		return;
	}
    // 删除原来的日志文件对象,empty路径为空
    if (!m_log_path.empty()) {
    
    
		m_backend->remove_stream(m_log_fstream);

		m_log_fstream->close();
		m_log_fstream = 0;
    }
	m_log_path = logpath;

	if (!fs::exists(logpath.parent_path())) {
    
    
		if (!fs::create_directories(logpath.parent_path())) {
    
    
            throw std::logic_error(("Can't create directory: " + logpath.parent_path().string()).c_str());
		}
	}

	// 添加新的日志文件
	if (!m_log_path.empty()) {
    
    

        /*
         * std::ios_base::app表示写入时从上次结尾处添加;那么重新启动程序时日志文件就不会被清空
         * 那么以下的内容便是make_shared创建一个指向日志文件的指针,并将其添加到sink中
         * 这样新的日志会写入console和m_log_path
         */
        m_log_fstream = boost::make_shared<std::ofstream>(m_log_path.string(),std::ios_base::app);
       qDebug()<<"m_log_fstream"<<m_log_fstream.get();
        m_backend->add_stream(m_log_fstream);
	}
}
``

Guess you like

Origin blog.csdn.net/qq_41104439/article/details/128249438