C++ 实现简单的日志记录器

#include <iostream>
#include <Mutex>
#include <ctime>

std::mutex mt;

//时间间隔类
class Duration
{
public:
    explicit Duration() : m_start(clock()){}
    
    double duration()
    {
        m_finish = clock();
        double d = (double)(m_finish - m_start) / CLOCKS_PER_SEC;   
        return d;
    }

private:
    clock_t m_start, m_finish; 
};

//日志记录器
class DLogger
{
public:
    enum Log_Grade
    {
        Debug = 0,
        Info,
        Warn,
        Error,
        Fatal
    };

public:
    explicit DLogger(const std::string& fileName = "unknow")
    {
        if(fileName == "unknow")
        {
            char buf[64];
            time_t now = time(0);
            tm* ltm = localtime(&now);

            sprintf(buf, "%d-%d-%d.log", ltm->tm_year + 1900, ltm->tm_mon + 1, ltm->tm_mday);

            m_fileName = buf;
        }
        else
        {
            m_fileName = fileName;
        }
    }
    
    void log(const char* msg, Log_Grade grade = Info);

private:
    std::string m_fileName;     
};

void DLogger::log(const char* msg, Log_Grade grade)
{
    mt.lock();

    FILE* fp = ::fopen(m_fileName.data(), "a+");
    char buf[1024];
    ::sprintf(buf, "%s, %s, %s, %d, %s, %d\n", __DATE__, __TIME__, __FILE__, __LINE__, msg, grade);
    ::fwrite(buf, sizeof(char),strlen(buf), fp);
    ::fclose(fp);

    mt.unlock();
}

//运行测试类
class Worker
{
public:
    explicit Worker(DLogger *logger = nullptr) : m_pLogger(logger){}
    ~Worker()
    { 
        if(m_pLogger)
        {
            delete m_pLogger;
            m_pLogger = nullptr;
        }
    }

    void run()
    {
        if(nullptr == m_pLogger)
        {
            std::cout << "nullptr == m_pLogger" << std::endl;
            return;
        }
        Duration d;
        for(int i = 0; i < 1000; ++i)
        {
            m_pLogger->log("work message", DLogger::Warn);
        }
        std::cout << "duration: " << d.duration() << " seconds" << std::endl;
    }


private:
    DLogger *m_pLogger;
};


int main()
{
    Worker w(new DLogger);

    w.run();

    return 0;
}

转载于:https://www.cnblogs.com/chengjundu/p/11276689.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值