c++日志练习

使用ostream流创建写入log日志文件

使用宏 配置文件大小和间隔时间  当创建文件时间间隔或文件大小大于指定数字 则创建新文件

文件名由时间自动命名

/**************************************************************
技术博客 

技术交流群
群号码:324164944

欢迎c c++ windows驱动爱好者 服务器程序员沟通交流
**************************************************************/
复制代码
#include "stdafx.h"
#include "StreamLog.h"
#include <sstream>


namespace DEFTOOLS {
    LogFile::LogFile():pOfsLogFile_(NULL){
        filePath_ = "";
        fileName_ = filePath_ + MakeFileName();
    }

    LogFile::LogFile(const std::string& filePath): pOfsLogFile_(NULL){
        filePath_ = filePath;
        fileName_ = filePath_ + MakeFileName();
    }

    const std::string LogFile::MakeFileName() {
        struct tm t = tm_.GetCurrentDataTime();
        std::stringstream s;
        std::string str;
        s << t.tm_year + 1900 << "_" << t.tm_mon + 1 << "_"
            << t.tm_mday << "_" << t.tm_hour << "_" <<
            t.tm_min << "_" << t.tm_sec << ".log";
        s >> str;
        return str;
    }
    bool LogFile::CreateFile() {
        bool bRet = false;
        try {
            pOfsLogFile_ = new std::ofstream(fileName_.c_str(), std::ios_base::app);
            if (NULL == pOfsLogFile_ || pOfsLogFile_->bad())
            {
                pOfsLogFile_ = NULL;
                std::exception e("open ofstream error");
                throw e;
            }
            tm_.SetBeginTime();
            bRet = true;
        }
        catch (const std::exception& error)
        {
            std::cerr << error.what() << std::endl;
        }

        return bRet;
    }


    bool LogFile::InitFunc() {
        return CreateFile();
    }

    LogFile::~LogFile(){
        if (NULL != pOfsLogFile_)
        {
            pOfsLogFile_->close();
            delete pOfsLogFile_;
        }
    }

    void LogFile::CheckFile() {
        tm_.SetEndTime();
        if ((tm_.GetDeltaTime() > DEFAULT_DELTA_TIME) ||
            GetFileSize() > DEFAULT_FILE_SIZE) {
            if (NULL != pOfsLogFile_) {
                pOfsLogFile_->close();
                delete pOfsLogFile_;
                pOfsLogFile_ = NULL;
            }
            fileName_ = filePath_ + MakeFileName();
            CreateFile();
        }
    }

    const std::string LogFile::GetCurrentTimeString()
    {
        struct tm t = tm_.GetCurrentDataTime();
        std::stringstream s;
        std::string str;
        std::string strTime;
        s << t.tm_year + 1900 << "-" << t.tm_mon + 1 << "-"
            << t.tm_mday;
        s >> str;
        s.clear();
        s << t.tm_hour << ":" <<
            t.tm_min << ":" << t.tm_sec << "\t\t";
        s >> strTime;

        str += " ";
        str += strTime;
        return str;
    }

    std::string  LogFile::GetLevelString(const WriteLevel wl) {
        std::string levelStr;
        switch (wl)
        {
        case NORMAL_L:
            levelStr = "[normal ]\t";
            break;
        case WARNING_L:
            levelStr = "[warning]\t";
            break;
        case ERROR_L:
            levelStr = "[error  ]\t";
            break;
        case UNKNOWN_L:
            levelStr = "[unknown]\t";
            break;
        default:
            levelStr = "[???????]\t";
            break;
        }
        return levelStr;
    }

    bool LogFile::WriteLog( std::string wrtieStr, const WriteLevel wl) {
        bool bRet = false;
        CheckFile();
        if (!pOfsLogFile_) {
            return bRet;
        }
        (*pOfsLogFile_) << GetCurrentTimeString() << GetLevelString(wl) << wrtieStr << std::endl;
        bRet = true;
        return bRet;
    }


}//namespace DEFTOOLS 
View Code
复制代码
复制代码
#pragma once

#include <time.h> 
#include <string>
#include <fstream>
#include <iostream>
#include <string>


namespace DEFTOOLS {
#define DEFAULT_DELTA_TIME            (60*2)    //日志切换时间
#define DEFAULT_FILE_SIZE            (1024*1024*1024)        //日志切换文件大小

    typedef enum WRITE_LEVEL
    {
        NORMAL_L = 0,
        WARNING_L,
        ERROR_L,
        UNKNOWN_L
    }WriteLevel;

    // Time 管理时间及时间差 以及年月日
    class LogTime {
    public:
        LogTime() :timeBegin_(time(NULL)), timeEnd_(time(NULL)) {
            time_t t = time(NULL);
            localtime_s(&tm_, &t);
        }

        void SetBeginTime() { timeBegin_ = time(NULL); }
        void SetEndTime() { timeEnd_ = time(NULL); }

        time_t GetBeginTime() { return timeBegin_; }
        time_t GetEndTime() { return timeEnd_; }
        time_t GetDeltaTime() { return timeEnd_ - timeBegin_; }
        struct tm GetCurrentDataTime() {
            time_t t = time(NULL);
            localtime_s(&tm_, &t);
            return tm_;
        };
    private:
        time_t timeBegin_;
        time_t timeEnd_;
        struct tm tm_;
    };


    class LogFile {
    public:
        LogFile();
        LogFile(const std::string& filePath);
        virtual ~LogFile();
        bool InitFunc();
        std::streampos GetFileSize() { if (!pOfsLogFile_) { return 0; }return pOfsLogFile_->tellp(); };
        void CheckFile();
        bool WriteLog(const std::string wrtieStr, const WriteLevel wl = NORMAL_L);
        //============================
        void WriteFileTest() {
            CheckFile();
            if (!pOfsLogFile_){ 
                return; 
            } 
            (*pOfsLogFile_) << "测试1234" << std::endl;
        }
        //============================
    private:
        bool CreateFile();
        const std::string GetCurrentTimeString();
        const std::string MakeFileName();
        std::string  LogFile::GetLevelString(const WriteLevel wl);
        std::string fileName_;
        std::string filePath_;
        std::ofstream* pOfsLogFile_;
        LogTime    tm_;
    };




}//namespace DEFTOOLS 
View Code
复制代码

 运行效果图

posted on   itdef  阅读(328)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示