1. 程式人生 > >c++日誌記錄模塊

c++日誌記錄模塊

stream extern ext lose test def created fda space

C++ 日誌記錄模塊

該模塊從實際項目中產生,通過extern聲明的方式,可在代碼不同模塊中生成日誌,日誌文件名稱為隨機碼加用戶指定名稱,采用隨機碼是為了避免日誌文件可能被覆蓋的問題。

願意的話你也能自己構建個人的日誌記錄模塊,本次分享的模塊實現方法比較簡單,可能有些地方沒考慮清楚。

源碼:

//
// Created by jerry on 2/12/16.
//

#include <iostream>
#include <string>
#include <fstream>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>

namespace lg{
    class Log {
    private:
        std::string m_log_file_path;
        std::ofstream m_log_file;
        bool m_cout_flag;
    public:
        Log(const std::string file_path = "run.log", const bool cout_flag = true);
        ~Log();

        void close();
        template<class T>
        Log & operator << (T &log_data)
        {
            m_log_file << log_data;
            m_log_file << std::flush;
#if ((defined _RM_DEC_PRINT) && (defined _RM_DEC_LOG_PRINT))
            if(m_cout_flag)
                std::cout << log_data << std::flush;            
#endif      
            return *this;
        }
    };

    extern Log run_log;
}
//
// Created by jerry on 2/12/16.
//

#include "Log.h"

namespace lg{

    Log run_log;
    
    Log::Log(const std::string file_path, const bool cout_flag)
    {
        m_cout_flag = cout_flag;
        // system("mkdir $HOME/data/log");
        
        struct timeval tv;     
        gettimeofday(&tv,NULL);
        std::random_device rd;  
        std::default_random_engine e(rd());  
        std::uniform_int_distribution<> u(0,1000000);
        usleep(u(e));
        
        std::string home = getenv("HOME"); 
        
        std::string log_file_path = home + "/data/log/" +
                                std::to_string((tv.tv_sec * 1000) % 1000000 + tv.tv_usec / 1000) +
                                std::to_string(u(e)) +
                                file_path;
        m_log_file_path = log_file_path;
        m_log_file.open(m_log_file_path, std::ios::app);
    }

    Log::~Log()
    {
        m_log_file.close();
        std::cout << "-- Log Destructor successfully!" << std::endl;
    }

    void Log::close()
    {
        m_log_file.close();
    }

}

例程:

下述log_information為用戶需要記錄的日誌信息。

//file test1.cpp
#include "Log.h"
//...   your code here
//...   your code here
lg::run_log << /***log_information1 here***/ << "\n";
//file test2.cpp
#include "Log.h"
//...   your code here
//...   your code here
lg::run_log << /***log_information2 here***/ << "\n";

最終日誌輸出為:

#file (rand_code)run.log
log_information1
log_information2

c++日誌記錄模塊