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

 运行效果图

原文地址:https://www.cnblogs.com/itdef/p/4971527.html