C++自定义简要日志类

该类的作用

  1. 选择性打印输出到控制台(通过宏定义控制)
  2. 将需要的相关日志信息保存到文件中,方便查看程序运行状态和可能发生的错误

代码

// log.hpp
#ifndef __LOG__
#define __LOG__
#include <mutex>
#include <string>
#include <iostream>
#include <sstream>
#include <mutex>
#include <ctime>
#include <cstdio>
#include <cstring>

using namespace std;
//#define __DEBUGE__   //控制台输出控制


class Log{
public:
    Log(string logFilePath,string logType){
        pfile = fopen(logFilePath.c_str(),"w");
        if(pfile == nullptr){
            printf("open log file error\n");
            return;
        } 
        this->logType = logType;
    }
    ~Log(){
        if(pfile){
        fclose(pfile);
        pfile = nullptr;
    }
    }
public:
    static string getCurrentTime(){
        std::time_t now = std::time(nullptr);
        char buf[20];
        std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
        return std::string(buf);
    }
    string getlogType(){
        return this->logType;
    }
public:
    template<typename T>
    Log& operator <<(const T& message){
        if(pfile == nullptr){
            printf("error:not exist log file\n");
        }
        logLock.lock();
        std::ostringstream msgStream;
        msgStream << message;
        std::string msgStr = msgStream.str();
        fwrite(msgStr.c_str(),1,msgStr.size(),pfile);
    #ifdef __DEBUGE__
        printf("%s",msgStr.c_str());
    #endif
        logLock.unlock();
        return *this;
    }
private:
    FILE* pfile;
    string logType;
    mutex logLock;
};
#endif

使用示例

// main.cpp
#include"log.hpp"
int main(){
    Log errorlog("../log/error.log","error");
    Log infolog("../log/info.log","info");
    errorlog<<"this is a error message,you can find this log in ../log/error.log"<<"\n";
    infolog<<"this is a info message,you can find this log in ../log/info.log"<<"\n";
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值