C++ 最简单的日志类

最近搞一个 C++ 项目的二次开发,没玩过 C++,可谓步履维艰。自己写个简单的日志类都被各种坑折磨。终于搞定了。

参考了这篇博客,并且进一步简化:https://www.cnblogs.com/DswCnblog/p/5459539.html

 

代码如下:

#pragma once

#include <ctime>  
#include <iostream>  
#include <fstream>  
#include <direct.h>

using namespace std;

#ifndef __EASYLOG_PIPI_0813
#define __EASYLOG_PIPI_0813

class EasyLog
{
public:
    static void Write(std::string log) {  
        try
        {    
            std::ofstream ofs;  
            time_t t = time(0);  
            char tmp[64];  
            strftime(tmp, sizeof(tmp), "[%Y-%m-%d %X]", localtime(&t));  
            ofs.open("D:\\PipeLog.log", std::ofstream::app);  
            
            ofs << tmp << " - ";  
            ofs.write(log.c_str(), log.size());  
            ofs << std::endl;  
            ofs.close();         
        }
        catch(...)
        {
        } 
    }
};

#endif

 

使用也很简单:

EasyLog::Write("hello Log");

 

发个博客记一下,省得忘了。

 

posted @ 2018-08-13 19:03  小浩叔叔  阅读(5062)  评论(0编辑  收藏  举报