C++ Logger 记录日志到文件

1.获取当前日期 / 获取当前时间
#include
#include
#include
static std::string get_data()
{
// 基于当前系统的当前日期/时间
time_t t=time(0);
struct tm *now = localtime(&t);
std::stringstream ss;
ss<< 1900 + now->tm_year <<’
<< 1 + now->tm_mon <<"
"
<tm_mday;
return ss.str();
}

static std::string get_time()
{
time_t t=time(0);
struct tm* now = localtime(&t);
std::stringstream ss;
ss<<get_data()<<’ ‘;
ss<tm_hour<<’:’
<tm_min<<’:’
<tm_sec;
return ss.str();

}

2.日志打开/写日志/关闭接口

#define loge(...) \
    writeLog("[",__func__ ,"][Line ", __LINE__,"]:", __VA_ARGS__)
#define logd(...) \
    writeLog("[",__func__ ,"][Line ", __LINE__,"]:", __VA_ARGS__)
#define logw(...) \
    writeLog("[",__func__ ,"][Line ", __LINE__,"]:", __VA_ARGS__)
#define logi(...) \
    writeLog("[",__func__ ,"][Line ", __LINE__,"]:", __VA_ARGS__)
    
------------------------------------------------------------------

#include "timeUtil.h"
#include "typeUtil.h"
#include <direct.h>
#include <string>
#include <sstream>
#include <fstream>
static fstream log_file;

    template <typename T,typename...Args>
    static int writeLog(const T &contentItem,const Args&...contentItems)
    {
        std::stringstream ss;
        to_string(ss, contentItem, contentItems...);//日志名字为当天时间
        log_file<<"["<<get_time()<<"]"<<ss.str()<<std::endl;
        return 0;
        // std::cerr<<ss.str()<<std::endl;
    }

    static int log_open(){
        char logPath[200];
        getcwd(logPath, 200);
        std::string path = logPath;
        path += '/';
        path += get_data(); //日志名字为
        log_file.open(path,std::ios::out|std::ios::app);
        return 0;
    }

    static int log_close(){
        log_file.close();
        return 0;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值