C++ 簡單的日志類


/* 
簡單的日志記錄類. (日志而已,何必那么復雜!!!) 
W.J.Chang 2013.12.13 
 
說明:(EasyLog.h) 
1, 簡單的單件實現(自動垃圾回收) 
2, 使用方法:EasyLog::Inst()->Log("Run..."); 
3, 日志記錄結果:Run...    [2013.12.13 16:38:42 Friday] 
*/  
#pragma once  
#ifndef EASY_LOG_H_8080  
#define EASY_LOG_H_8080  
#include <memory>  
#include <ctime>  
#include <iostream>  
#include <fstream>  
class EasyLog  
{  
public:  
    static EasyLog * Inst(){  
        if (0 == _instance.get()){  
            _instance.reset(new EasyLog);  
        }  
        return _instance.get();  
    }  
  
    void Log(std::string msg); // 寫日志的方法  
private:  
    EasyLog(void){}  
    virtual ~EasyLog(void){}  
    friend class std::auto_ptr<EasyLog>;  
    static std::auto_ptr<EasyLog> _instance;  
};  
  
std::auto_ptr<EasyLog> EasyLog::_instance;  
  
void EasyLog::Log(std::string loginfo) {  
    std::ofstream ofs;  
    time_t t = time(0);  
    char tmp[64];  
    strftime(tmp, sizeof(tmp), "\t[%Y.%m.%d %X %A]", localtime(&t));  
    ofs.open("EasyLog.log", std::ofstream::app);  
    ofs.write(loginfo.c_str(), loginfo.size());  
    ofs << tmp << '\n';  
    ofs.close();  
}  
#endif  

用法如下:

#include "EasyLog.h"

int main()
{ EasyLog::Inst()
->Log("Run..."); }

不只是main函數中,任何地方只要include頭文件就可以用。

主要是輔助調試,特別是寫dll程序的時候比較實用。可以加個宏控制。在發布的時候關掉日志功能。

#include "EasyLog.h"  
  
#define EASYLOG 1  
  
int main(){  
#if EASYLOG  
    EasyLog::Inst()->Log("Run...");  
#endif  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM