Qt c++ 实现大型的项目工程日志管理 .txt日志和tar解压缩,不同的日志等级

Qt 项目日志管理模块,可以为一个大型的项目工程提供一个实时监控,自动分配内存解压缩打包LOG和删除LOG日志模块
依然是代码
Tracelog.h

#ifndef _TRACELOGDEF_HPP_
#define _TRACELOGDEF_HPP_
/*****************************************************************************/
/*                                                                           */
/*    Copyright (C) -        Intelligent Equipment - All rights reserved     */
/*                                                                           */
/*****************************************************************************/
/*                                                                           */
/*  Except if expressly provided in a dedicated License Agreement, you are   */
/*  not authorized to:                                                       */
/*                                                                           */
/*  1. Use, copy, modify or transfer this software component, module or      */
/*  product, including any accompanying electronic or paper documentation    */
/*  (together, the "Software").                                              */
/*                                                                           */
/*  2. Remove any product identification, copyright, proprietary notices or  */
/*  labels from the Software.                                                */
/*                                                                           */
/*  3. Modify, reverse engineer, decompile, disassemble or otherwise attempt */
/*  to reconstruct or discover the source code, or any parts of it, from the */
/*  binaries of the Software.                                                */
/*                                                                           */
/*  4. Create derivative works based on the Software (e.g. incorporating the */
/*  Software in another software or commercial product or service without a  */
/*  proper license).                                                         */
/*                                                                           */
/*  By installing or using the "Software", you confirm your acceptance of the*/
/*  hereabove terms and conditions.                                          */
/*                                                                           */
/*****************************************************************************/


/*****************************************************************************/
/*  History:                                                                 */
/*****************************************************************************/
/*  Date       * Author          * Changes                                   */
/*****************************************************************************/
/*             *                 *                                           */
/*****************************************************************************/


/*****************************************************************************/
/*                                                                           */
/*  Include Files                                                            */
/*                                                                           */
/*****************************************************************************/
#include <stdio.h>
#include <string.h>



/*****************************************************************************/
/*                                                                           */
/*  Definitions                                                              */
/*                                                                           */
/*****************************************************************************/
// disable trace output
//#define NO_TRACE_LOG

// slash or backslash to split directories in __FILE__ macro
#if defined(_WIN32)
#define SLASH_BACKSLASH     '\\'
#else
#define SLASH_BACKSLASH     '/'
#endif

// trace log message level
#define LEVEL_FATAL         0x10
#define LEVEL_ERROR         0x08
#define LEVEL_HIGH          0x04
#define LEVEL_MED           0x02
#define LEVEL_LOW           0x01

// Max time string length + NULL
#define MSG_TIME_LEN 32
// Max file name length + NULL
#define MSG_FILE_LEN 32
// Max function name length + NULL
#define MSG_FUNC_LEN 64
// Max len of format string + NULL
#define MSG_FMT_LEN  512

// Structure packed with message information
typedef struct
{
    char time[MSG_TIME_LEN];            // time of the message sent
    char file[MSG_FILE_LEN];            // Holds source file name
    unsigned int line;                          // Line number in source file
    char func[MSG_FUNC_LEN];            // Function name
    char fmt[MSG_FMT_LEN];              // printf formated string
    unsigned int level;                         // message level
} STMsgType;

/*****************************************************************************/
/*                                                                           */
/*  Variable Declarations                                                    */
/*                                                                           */
/*****************************************************************************/

/*****************************************************************************/
/*                                                                           */
/*  Function Declarations                                                    */
/*                                                                           */
/*****************************************************************************/
#if defined (__cplusplus)
extern "C"
{
#endif

#ifdef NO_TRACE_LOG
#define LOG_FATAL(...)
#define LOG_ERROR(...)
#define LOG_HIGH(...)
#define LOG_MED(...)
#define LOG_LOW(...)
#else
extern long pXXX_Handle;
#define HANDLE_MODLE pXXX_Handle 

#define MSG_FATAL(...) \
    do { \
        STMsgType Msg; \
        char* p = (char *)strrchr(__FILE__, SLASH_BACKSLASH); \
        if(!p) \
            p = (char*)(__FILE__); \
        else \
            p++; \
        memset(&Msg, 0x00, sizeof(Msg)); \
        snprintf(Msg.file, sizeof(Msg.file)-1, "%s", p); \
        Msg.line = __LINE__; \
        snprintf(Msg.func, sizeof(Msg.func)-1, "%s", (char*)(__FUNCTION__)); \
        snprintf(Msg.fmt, sizeof(Msg.fmt)-1, __VA_ARGS__); \
        Msg.level = LEVEL_FATAL; \
        LOG_Write(HANDLE_MODLE, Msg); \
    } while(0)
#define MSG_ERROR(...) \
    do { \
        STMsgType Msg; \
        char* p = (char *)strrchr(__FILE__, SLASH_BACKSLASH); \
        if(!p) \
            p = (char*)(__FILE__); \
        else \
            p++; \
        memset(&Msg, 0x00, sizeof(Msg)); \
        snprintf(Msg.file, sizeof(Msg.file)-1, "%s", p); \
        Msg.line = __LINE__; \
        snprintf(Msg.func, sizeof(Msg.func)-1, "%s", (char*)(__FUNCTION__)); \
        snprintf(Msg.fmt, sizeof(Msg.fmt)-1, __VA_ARGS__); \
        Msg.level = LEVEL_ERROR; \
        LOG_Write(HANDLE_MODLE, Msg); \
    } while(0)
#define MSG_HIGH(...) \
    do { \
        STMsgType Msg; \
        char* p = (char *)strrchr(__FILE__, SLASH_BACKSLASH); \
        if(!p) \
            p = (char*)(__FILE__); \
        else \
            p++; \
        memset(&Msg, 0x00, sizeof(Msg)); \
        snprintf(Msg.file, sizeof(Msg.file)-1,  "%s", p); \
        Msg.line = __LINE__; \
        snprintf(Msg.func, sizeof(Msg.func)-1,  "%s", (char*)(__FUNCTION__)); \
        snprintf(Msg.fmt, sizeof(Msg.fmt)-1, __VA_ARGS__); \
        Msg.level = LEVEL_HIGH; \
        LOG_Write(HANDLE_MODLE, Msg); \
    } while(0)
#define MSG_MED(...) \
    do { \
        STMsgType Msg; \
        char* p = (char *)strrchr(__FILE__, SLASH_BACKSLASH); \
        if(!p) \
            p = (char*)(__FILE__); \
        else \
            p++; \
        memset(&Msg, 0x00, sizeof(Msg)); \
        snprintf(Msg.file, sizeof(Msg.file)-1, "%s",p); \
        Msg.line = __LINE__; \
        snprintf(Msg.func, sizeof(Msg.func)-1, "%s", (char*)(__FUNCTION__)); \
        snprintf(Msg.fmt, sizeof(Msg.fmt)-1, __VA_ARGS__); \
        Msg.level = LEVEL_MED; \
        LOG_Write(HANDLE_MODLE, Msg); \
    } while(0)
#define MSG_LOW(...) \
    do { \
        STMsgType Msg; \
        char* p = (char *)strrchr(__FILE__, SLASH_BACKSLASH); \
        if(!p) \
            p = (char*)(__FILE__); \
        else \
            p++; \
        memset(&Msg, 0x00, sizeof(Msg)); \
        snprintf(Msg.file, sizeof(Msg.file)-1, "%s", p); \
        Msg.line = __LINE__; \
        snprintf(Msg.func, sizeof(Msg.func)-1, "%s", (char*)(__FUNCTION__)); \
        snprintf(Msg.fmt, sizeof(Msg.fmt)-1, __VA_ARGS__); \
        Msg.level = LEVEL_LOW; \
        LOG_Write(HANDLE_MODLE, Msg); \
    } while(0)
#endif

// path: log存放的路径
// name_prefix: log文件名前缀,如xxx20180703_001.log,xxx为log文件名前缀
// day_saved:日志保存天数
// line_max:每个log文件的最大行数
// file_max:一天中产生的最大文件数,超过将循环写入
// level:日志等级
extern int LOG_Init(char *path, char *name_prefix, unsigned int day_saved,
		             unsigned int line_max, unsigned int file_max, 
		             unsigned int level, long *pHandle);
extern int LOG_Deinit(long pHandle);
extern void LOG_GetDLLVersion(char Version[32]);
extern void LOG_Write(long pHandle, STMsgType Msg);


#if defined (__cplusplus)
} // end of extern "C"
#endif


#endif //_TRACELOGDEF_HPP_


traceLogAPI.cpp

/*****************************************************************************/
/*                                                                           */
/*    Copyright (C) -                              - All rights reserved     */
/*                                                                           */
/*****************************************************************************/
/*                                                                           */
/*  Except if expressly provided in a dedicated License Agreement, you are   */
/*  not authorized to:                                                       */
/*                                                                           */
/*  1. Use, copy, modify or transfer this software component, module or      */
/*  product, including any accompanying electronic or paper documentation    */
/*  (together, the "Software").                                              */
/*                                                                           */
/*  2. Remove any product identification, copyright, proprietary notices or  */
/*  labels from the Software.                                                */
/*                                                                           */
/*  3. Modify, reverse engineer, decompile, disassemble or otherwise attempt */
/*  to reconstruct or discover the source code, or any parts of it, from the */
/*  binaries of the Software.                                                */
/*                                                                           */
/*  4. Create derivative works based on the Software (e.g. incorporating the */
/*  Software in another software or commercial product or service without a  */
/*  proper license).                                                         */
/*                                                                           */
/*  By installing or using the "Software", you confirm your acceptance of the*/
/*  hereabove terms and conditions.                                          */
/*                                                                           */
/*****************************************************************************/


/*****************************************************************************/
/*  History:                                                                 */
/*****************************************************************************/
/*  Date       * Author          * Changes                                   */
/*****************************************************************************/
/*  2018-07-03 * Dajiang.lu      * Creation of the file                      */
/*             *                 *                                           */
/*****************************************************************************/
/*****************************************************************************/
/*                                                                           */
/*  Include Files                                                            */
/*                                                                           */
/*****************************************************************************/
#include "TraceLog.h"
#include <QMutex>

#if defined (__cplusplus)
extern "C"
{
#endif
/*****************************************************************************/
/*                                                                           */
/*  Definitions                                                              */
/*                                                                           */
/*****************************************************************************/
#define MAJOR_VERSION 0x01
#define MINOR_VERSION 0x00


/*****************************************************************************/
/*                                                                           */
/*  Variable Declarations                                                    */
/*                                                                           */
/*****************************************************************************/
//static CMutex LOGMutex;
static QMutex LOGMutex;
static CTraceLog *pTraceLog[20];
static int count_handle = 0;

/*****************************************************************************/
/*                                                                           */
/*  Function Declarations                                                    */
/*                                                                           */
/*****************************************************************************/
int LOG_Init(char *path, char *name_prefix, unsigned int day_saved,
             unsigned int line_max, unsigned int file_max, 
             unsigned int level, long *pHandle)
{    
    int nRet = ERROR_FAILURE;
    *pHandle = count_handle;
    pTraceLog[*pHandle] = new CTraceLog();
    if(pTraceLog[*pHandle] != NULL)
    {
        // init trace log
        pTraceLog[*pHandle]->init(path, name_prefix, day_saved, 
                                 line_max, file_max, level);
        count_handle++;
        nRet = ERROR_NONE;
    }
    return nRet;
}

int LOG_Deinit(long pHandle)
{
    int nRet = ERROR_FAILURE;
    if((pHandle < count_handle) 
        && (pTraceLog[pHandle] != NULL))
    {
        // delete trace log instance
        delete pTraceLog[pHandle];
        pTraceLog[pHandle] = NULL;
        nRet = ERROR_NONE;
    }
    return nRet;
}

void LOG_Write(long pHandle, STMsgType Msg)
{
//    LOGMutex.take();
    LOGMutex.lock();
    if((pHandle < count_handle) 
        && (pTraceLog[pHandle] != NULL)
        && (Msg.level & pTraceLog[pHandle]->unLevelConf)) {  
        pTraceLog[pHandle]->getcurrentTime(Msg.time);
        pTraceLog[pHandle]->LogMsgEnqueue(Msg);
    }
    LOGMutex.unlock();
//    LOGMutex.release();
}

void LOG_GetDLLVersion(char Version[32])
{   
//    LOGMutex.take();
    LOGMutex.lock();
    sprintf(Version,"AVPT-LOG-DLL-%02x-%02x",MAJOR_VERSION,MINOR_VERSION);
    LOGMutex.unlock();
//    LOGMutex.release();
}

#if defined (__cplusplus)
} // end of extern "C"
#endif



TraceLog.h

#ifndef _TRACELOG_HPP_
#define _TRACELOG_HPP_
/*****************************************************************************/
/*                                                                           */
/*    Copyright (C) -        Intelligent Equipment - All rights reserved     */
/*                                                                           */
/*****************************************************************************/
/*                                                                           */
/*  Except if expressly provided in a dedicated License Agreement, you are   */
/*  not authorized to:                                                       */
/*                                                                           */
/*  1. Use, copy, modify or transfer this software component, module or      */
/*  product, including any accompanying electronic or paper documentation    */
/*  (together, the "Software").                                              */
/*                                                                           */
/*  2. Remove any product identification, copyright, proprietary notices or  */
/*  labels from the Software.                                                */
/*                                                                           */
/*  3. Modify, reverse engineer, decompile, disassemble or otherwise attempt */
/*  to reconstruct or discover the source code, or any parts of it, from the */
/*  binaries of the Software.                                                */
/*                                                                           */
/*  4. Create derivative works based on the Software (e.g. incorporating the */
/*  Software in another software or commercial product or service without a  */
/*  proper license).                                                         */
/*                                                                           */
/*  By installing or using the "Software", you confirm your acceptance of the*/
/*  hereabove terms and conditions.                                          */
/*                                                                           */
/*****************************************************************************/


/*****************************************************************************/
/*  History:                                                                 */
/*****************************************************************************/
/*  Date       * Author          * Changes                                   */
/*****************************************************************************/
/*             *                 *                                           */
/*****************************************************************************/


/*****************************************************************************/
/*                                                                           */
/*  Include Files                                                            */
/*                                                                           */
/*****************************************************************************/
//#include "timer.h"
//#include <vector>
#include "TraceLogDef.h"
#include <QQueue>
#include <QMutex>
#include <QThread>
#include <QSemaphore>
#include <QList>
//#include <queue>
//#include <mutex>
//#include <semaphore.h>
//#include <thread>
/*****************************************************************************/
/*                                                                           */
/*  Definitions                                                              */
/*                                                                           */
/*****************************************************************************/
#define ERROR_NONE                   0
#define ERROR_FAILURE                1

typedef struct
{
    char filename[30];
} StdateLog;

/*****************************************************************************/
/* Class Description:                                                        */
/*****************************************************************************/
/*   Class packed trace log functions                                        */
/*                                                                           */
/* CAUTION!!!:                                                               */
/*   Only one single instance of this class is allowed to exist              */
/*                                                                           */
/*****************************************************************************/
class CTraceLog : public QThread
{
    public:

        /*********************************************************************/
        /*                     Constructor & Destructor                      */
        /*********************************************************************/
        CTraceLog();
        ~CTraceLog();


        /*********************************************************************/
        /*                            Variables                              */
        /*********************************************************************/
        unsigned int unLevelConf;           // the configuration of the trace log level
                                    // to allow trace output


        /*********************************************************************/
        /*                            Functions                              */
        /*********************************************************************/
		// file_max < 1000
		// line_max < 65535
        void init(char *path, char *name_prefix, unsigned int day_saved,
                  unsigned int line_max, unsigned int file_max,
                  unsigned int level);

        void getcurrentTime(char m_time[32]);
        void LogMsgEnqueue(STMsgType &pMsg);
        bool LogMsgDequeue(STMsgType &pMsg);

    private:

        /*********************************************************************/
        /*                            Variables                              */
        /*********************************************************************/
        QSemaphore semSync;         // semaphore to syncronous thread begin and
        volatile bool stopped;      // flag to indicate trace log thread 
                                    // stopped
        QMutex mtxLogMsgQ;
        QQueue<STMsgType*> LogMsgQ; // log message queue

        int cur_mday;
        char *log_path;
        char *log_name_prefix;
        char *log_name;
		
        unsigned int m_day_saved;
        unsigned int log_line_max;
        unsigned int log_file_max;
        unsigned int file_count;
        unsigned int NBLineReportFile;

        QList<StdateLog> dateLog;

        /*********************************************************************/
        /*                            Functions                              */
        /*********************************************************************/
        void stop();

    protected:

        /*********************************************************************/
        /*                            Variables                              */
        /*********************************************************************/


        /*********************************************************************/
        /*                            Functions                              */
        /*********************************************************************/
        void run();


};


/*****************************************************************************/
/*                                                                           */
/*  Variable Declarations                                                    */
/*                                                                           */
/*****************************************************************************/


/*****************************************************************************/
/*                                                                           */
/*  Function Declarations                                                    */
/*                                                                           */
/*****************************************************************************/


#endif //_TRACELOG_HPP_


traceLog.cpp

/*****************************************************************************/
/*                                                                           */
/*    Copyright (C) -        Intelligent Equipment - All rights reserved     */
/*                                                                           */
/*****************************************************************************/
/*                                                                           */
/*  Except if expressly provided in a dedicated License Agreement, you are   */
/*  not authorized to:                                                       */
/*                                                                           */
/*  1. Use, copy, modify or transfer this software component, module or      */
/*  product, including any accompanying electronic or paper documentation    */
/*  (together, the "Software").                                              */
/*                                                                           */
/*  2. Remove any product identification, copyright, proprietary notices or  */
/*  labels from the Software.                                                */
/*                                                                           */
/*  3. Modify, reverse engineer, decompile, disassemble or otherwise attempt */
/*  to reconstruct or discover the source code, or any parts of it, from the */
/*  binaries of the Software.                                                */
/*                                                                           */
/*  4. Create derivative works based on the Software (e.g. incorporating the */
/*  Software in another software or commercial product or service without a  */
/*  proper license).                                                         */
/*                                                                           */
/*  By installing or using the "Software", you confirm your acceptance of the*/
/*  hereabove terms and conditions.                                          */
/*                                                                           */
/*****************************************************************************/


/*****************************************************************************/
/*  History:                                                                 */
/*****************************************************************************/
/*  Date       * Author          * Changes                                   */
/*****************************************************************************/
/*             *                 *                                           */
/*****************************************************************************/


/*****************************************************************************/
/*                                                                           */
/*  Include Files                                                            */
/*                                                                           */
/*****************************************************************************/
#include "TraceLog.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#if defined(_WIN32)
#include<io.h>
#endif
#include <sys/types.h>
#include <dirent.h>

using namespace std;


/*****************************************************************************/
/*                                                                           */
/*  Definitions                                                              */
/*                                                                           */
/*****************************************************************************/


/*****************************************************************************/
/*                                                                           */
/*  Variable Declarations                                                    */
/*                                                                           */
/*****************************************************************************/

/*****************************************************************************/
/*                                                                           */
/*  Function Implementations                                                 */
/*                                                                           */
/*****************************************************************************/

/*****************************************************************************/
/*                                                                           */
/*  Function Implementations                                                 */
/*                                                                           */
/*****************************************************************************/
/*****************************************************************************/
/* Function Description:                                                     */
/*****************************************************************************/
/*   Constructor                                                             */
/*                                                                           */
/*****************************************************************************/
/* Parameters:                                                               */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
/* Return Values:                                                            */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
CTraceLog::CTraceLog()
    :unLevelConf(LEVEL_FATAL | LEVEL_ERROR | LEVEL_HIGH | LEVEL_MED | LEVEL_LOW)
{
//
    stopped = false;
    cur_mday = 0;
    log_path = NULL;
    log_name_prefix = NULL;
    log_name = NULL;
    log_line_max = 1000;
    log_file_max = 500;
    file_count = 1;
    NBLineReportFile = 0;

}

/*****************************************************************************/
/* Function Description:                                                     */
/*****************************************************************************/
/*   Destructor                                                              */
/*                                                                           */
/*****************************************************************************/
/* Parameters:                                                               */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
/* Return Values:                                                            */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
CTraceLog::~CTraceLog()
{
    if(log_name != NULL)
    {
        delete []log_name;
        log_name = NULL;
    }

    if(log_name_prefix != NULL)
    {
        delete []log_name_prefix;
        log_name_prefix = NULL;
    }

    if(log_path != NULL)
    {
        delete []log_path;
        log_path = NULL;
    }

//    if (getExitCode() == RUNNING) {
//        stop();
//        join();
//    }
}

/*****************************************************************************/
/* Function Description:                                                     */
/*****************************************************************************/
/*   Initialise the module                                                   */
/*                                                                           */
/*****************************************************************************/
/* Parameters:                                                               */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
/* Return Values:                                                            */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
void CTraceLog::init(char *path, char *name_prefix, unsigned int day_saved,
                     unsigned int line_max, unsigned int file_max, unsigned int level)
{
    if(path != NULL)
    {

        int length_path = strlen(path);
        if(log_path == NULL)
        {
            log_path = new char[length_path+2];
            if(log_path != NULL)
            {
                memcpy(log_path, path, length_path+1);
//                if(path[length_path-1] != '\')
//                {
//                    log_path[length_path] = '\';
//                    log_path[length_path+1] = '\0';
//                }

                if(name_prefix != NULL)
                {
                    int length_name = strlen(name_prefix);
                    if(log_name_prefix == NULL)
                    {
                        log_name_prefix = new char[length_name+1];
                        if(log_name_prefix != NULL)
                        {
                            memcpy(log_name_prefix, name_prefix, length_name+1);
                            if(log_name == NULL)
                            {
                                log_name = new char[length_path+length_name+20];
                            }
                        }
                        else
                        {
                            printf("new log_name_prefix failure!\n");
                        }
                    }
                }
                else
                {
                    printf("name_prefix is empty\n");
                }
            }
            else
            {
                printf("new log_path failure!\n");
            }
        }
    }
    else
    {
        printf("path is empty\n");
    }

    if(log_name_prefix != NULL)
    {
        log_line_max = line_max;
        log_file_max = file_max;
        unLevelConf = level;
        // day saved
        m_day_saved = day_saved;

        // create log dir
        if(access(log_path, 0) != 0)
        {
            int len = strlen(log_path);
            char cmdOS[len+10];
            sprintf(cmdOS, "md %s", log_path);
            system(cmdOS);
        }

        dateLog.clear();

        // create the gate core thread
//        CThread::initInstance((char *)("TraceLog"),
//                          THREAD_DEFAULT_STACK_SIZE,
//                          THREAD_MAX_PRIORITY);

        // start the PCB board validation thread and wait until it's running
        start();
//        waitStarted();


        // wait to syncronous threads
        semSync.acquire();
    }
}

/*****************************************************************************/
/* Function Description:                                                     */
/*****************************************************************************/
/*   Implementation function of the trace log thread                         */
/*                                                                           */
/*****************************************************************************/
/* Parameters:                                                               */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
/* Return Values:                                                            */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
void CTraceLog::run()
{
    STMsgType logMsg;
    bool bInitCheck = true;
    bool bFirstCheck = true;
    bool bRet = false;
    char date[9];
    // inform thread started
    semSync.release();

    while(!stopped)
    {
        time_t rawtime;
        struct tm *getTimer;
        time(&rawtime);
        getTimer = localtime(&rawtime);

        sprintf(date, "%04d%02d%02d", getTimer->tm_year+1900,
            getTimer->tm_mon+1, getTimer->tm_mday);
        printf("run ----------------299\n");//add by lzh
        if(cur_mday != getTimer->tm_mday)
        {
            // 使用今天的日期命名压缩文件
            char tempfilename[30] = {0};
            sprintf(tempfilename, "%s%04d%02d%02d.tar", log_name_prefix,
                    getTimer->tm_year+1900, getTimer->tm_mon+1, getTimer->tm_mday);

             // 打包已有的log文件
            char cmd[100];
            sprintf(cmd, "7z.exe a -ttar %s%s %s%s*.log",
                    log_path, tempfilename, log_path, log_name_prefix);
            system(cmd);


            memset(cmd, 0, sizeof(cmd));

            // 打包已有的tar文件
            StdateLog log;
            sprintf(log.filename, "%s%04d%02d%02d.tar.gz", log_name_prefix,
                    getTimer->tm_year+1900, getTimer->tm_mon+1, getTimer->tm_mday);


            sprintf(cmd, "7z.exe a -tgzip %s%s %s%s",
                    log_path, log.filename, log_path, tempfilename);
            system(cmd);

            // 删除log文件和临时的tar文件
            memset(cmd, 0, sizeof(cmd));
            sprintf(cmd, "del %s%s", log_path,tempfilename);
            system(cmd);

            memset(cmd, 0, sizeof(cmd));
            sprintf(cmd, "del %s*.log", log_path);
            system(cmd);
            printf("run ----------------334\n");//add by lzh
            if(cur_mday == 0)
            {
                printf("run ----------------337\n");//add by lzh
                // 获取已有压缩包文件
                DIR *d = opendir(log_path);
                if(d == NULL)
                {
                    printf("opendir error!\n");
                }
                struct dirent *entry;
                while((entry=readdir(d)) != NULL) {
                    int len = strlen(entry->d_name);
                    if((0 != memcmp(entry->d_name, ".", 1))
                        && (0 != memcmp(entry->d_name, "..", 2))
                        && (len == 15)
                        && (entry->d_name[len-2] == 'g')
                        && (entry->d_name[len-1] == 'z'))
                    {
                        //printf("%s\n", entry->d_name);
                        memcpy(log.filename, entry->d_name, len+1);
                        dateLog.push_back(log);
                    }
                }
                closedir(d);
                //printf("dateLog.size = %d==================%s\n", dateLog.size(), dateLog[0].filename);
            }
            else
            {
                dateLog.push_back(log);
            }

            // update cur_mday
            cur_mday = getTimer->tm_mday;
            bInitCheck = true;
//            printf("dateLog.size = %d==================%s\n", dateLog.size(), dateLog[0].filename);

            // 删除n天前的日志
            while(dateLog.size() > m_day_saved)
            {

                // 删除log文件
                printf("run ----------------374\n");//add by lzh
                memset(cmd, 0, sizeof(cmd));
                sprintf(cmd, "del %s%s", log_path, dateLog[0].filename);
                //printf("%s######################34\n", cmd);
                system(cmd);
                printf("run ----------------379\n");//add by lzh
                dateLog.erase(dateLog.begin());
                printf("dateLog.size22 = %d==================%s\n", dateLog.size(), dateLog[0].filename);
                printf("run ----------------382\n");//add by lzh
            }
        }

        // Check to see if the file exists.
        if(bInitCheck)
        {
            bInitCheck = false;

            if(bFirstCheck)
            {
                unsigned int i = 0;

                bFirstCheck = false;
                file_count = 1;

                for(; i<log_file_max; i++)
                {
                    sprintf(log_name, "%s%s%s_%03d.log", log_path, log_name_prefix, date, file_count);
                    printf("log_name = %s\n", log_name);
                    if(access(log_name, 0) == 0)
                    {
                        printf("file exit\n");
                        file_count++;
                        continue;
                    }
                    else {
                        break;
                    }
                }
            }

            if(file_count>log_file_max)
            {
                file_count = 1;
            }

//            // First file
//            sprintf(log_name, "%s%s%s_%03d.log", log_path, log_name_prefix, date, file_count);
//            if(access(log_name, 0) == 0)
//            {
//                // 删除log文件
//                printf("run ----------------421\n");//add by lzh
//                char cmd[100];
//                memset(cmd, 0, sizeof(cmd));
//                sprintf(cmd, "del %s", log_name);
//                system(cmd);
//                printf("run ----------------426\n");//add by lzh
//            }
            file_count++;
            NBLineReportFile = 0;
        }

        // get the trace log message queue
        bRet = LogMsgDequeue(logMsg);
        if(bRet)
        {
            FILE *file_report;
            if(access(log_name, 0) == 0)
            {
                file_report = fopen(log_name,"a");
            }
            else {
                file_report = fopen(log_name,"w");
            }
            if(file_report != NULL)
            {
                // [LEVEL],TIME,FILE(LINE),FUNC,FMT
                fprintf(file_report, "[%02x],%s,%s(%d),%s,%s",
                                      logMsg.level, logMsg.time,
                                      logMsg.file, logMsg.line,
                                      logMsg.func, logMsg.fmt);
                fclose(file_report);
                NBLineReportFile++;
            }

            // Switch files
            if(NBLineReportFile > log_line_max)
            {
                bInitCheck = true;
                NBLineReportFile = 0;
            }
        }
        sleep(1);
    }

//    return SUCCESS;
}

/*****************************************************************************/
/* Function Description:                                                     */
/*****************************************************************************/
/*   Stop the trace log thread                                               */
/*                                                                           */
/*****************************************************************************/
/* Parameters:                                                               */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
/* Return Values:                                                            */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
void CTraceLog::stop()
{
    stopped = true;
}

void CTraceLog::getcurrentTime(char m_time[32])
{
    time_t rawtime;
    struct tm *getTimer;
    time(&rawtime);
    getTimer = localtime(&rawtime);
    struct timeval tv_begin;
    gettimeofday(&tv_begin, NULL);
    sprintf(m_time, "%04d-%02d-%02d %02d:%02d:%02d-%03ld", getTimer->tm_year+1900, getTimer->tm_mon+1,
                getTimer->tm_mday, getTimer->tm_hour, getTimer->tm_min, getTimer->tm_sec,tv_begin.tv_usec/1000);
}

/*****************************************************************************/
/* Function Description:                                                     */
/*****************************************************************************/
/*   Enqueue trace log messages                                              */
/*                                                                           */
/*****************************************************************************/
/* Parameters:                                                               */
/*****************************************************************************/
/*   pMsg[in]:              structure stored message                         */
/*                                                                           */
/*****************************************************************************/
/* Return Values:                                                            */
/*****************************************************************************/
/*   none                                                                    */
/*                                                                           */
/*****************************************************************************/
void CTraceLog::LogMsgEnqueue(STMsgType &pMsg)
{
    STMsgType *pTempPtr = new STMsgType;

    mtxLogMsgQ.lock();
    if(pTempPtr != NULL)
    {
        memcpy(pTempPtr, &pMsg, sizeof(STMsgType));
        // enqueue message
        LogMsgQ.enqueue(pTempPtr);
    }
    mtxLogMsgQ.unlock();
}

/*****************************************************************************/
/* Function Description:                                                     */
/*****************************************************************************/
/*   Dequeue trace log messages                                              */
/*                                                                           */
/*****************************************************************************/
/* Parameters:                                                               */
/*****************************************************************************/
/*   pMsg[out]:             structure to store message                       */
/*                                                                           */
/*****************************************************************************/
/* Return Values:                                                            */
/*****************************************************************************/
/*   true - a message dequeued ok                                            */
/*   false - no message available                                            */
/*                                                                           */
/*****************************************************************************/
bool CTraceLog::LogMsgDequeue(STMsgType &pMsg)
{
    bool bRet = false;

    // dequeue log message
    STMsgType * pTempPtr = NULL;
    printf("LogMsgDequeue ----------------1\n");//add by lzh
    // dequeue log message
    if(LogMsgQ.size() > 0)
    {
        pTempPtr = LogMsgQ.dequeue();
    }
    if(pTempPtr != NULL)
    {
        printf("LogMsgDequeue ----------------2\n");//add by lzh
        memcpy(&pMsg, pTempPtr, sizeof(STMsgType));
        delete pTempPtr;
        pTempPtr = NULL;
        bRet = true;
    }

    return bRet;
}


使用:

1.定义一个全局的句柄,如TVM:long pTVM_Handle;
2.将TraceLogDef.h中的pXXX_Handle全部替换成刚才定义的句柄
3.调用初始化LOG_Init()
4.在代码中添加日志,根据实际情况添加相应的日志
   MSG_FATAL("测试1\n")
   MSG_ERROR("测试2\n")
   MSG_HIGH("测试3\n")
   MSG_MED("测试4\n")
   MSG_LOW("测试5\n")

   每一个管理模块建议如下实现,这样就可以在pro工程文件中控制该模块的日志输出,如BNR管理模块
   BNRManager.cpp中定义:
   #if defined(TRACE_BNR_MANAGER)
   #define LOG_FATAL MSG_FATAL
   #define LOG_ERROR MSG_ERROR
   #define LOG_HIGH MSG_HIGH
   #define LOG_MED MSG_MED
   #define LOG_LOW MSG_LOW
   #else
   #define LOG_FATAL(...)
   #define LOG_ERROR(...)
   #define LOG_HIGH(...)
   #define LOG_MED(...)
   #define LOG_LOW(...)
   #endif
   
   代码中添加日志:
   LOG_FATAL("测试1\n";
   LOG_ERROR("测试2\n";
   LOG_HIGH("测试3\n";
   LOG_MED("测试4\n";
   LOG_LOW("测试5\n";

   pro工程中控制输出的部分:
   DEFINES += TRACE_BNR_MANAGER
   
   配置文件xml
   <!-- Trace Log Module -->
    <module name="TraceLog">
	    <item name="Path">./</item>
		<item name="Name_prefix">APP</item>
		<item name="TraceLogLevel">0x1f</item>       <!-- TraceLogLevel:
                                                         0x10 - fatal level message enable mask
                                                         0x08 - error level message enable mask
                                                         0x04 - high level message enable mask
                                                         0x02 - mid level message enable mask
                                                         0x01 - low level message enable mask -->
		<item name="Day_saved">30</item>
		<item name="Line_max">30000</item>
		<item name="File_max">100</tem>        
    </module>
5.程序退出时需要调用LOG_Deinit()

完结,撒花~

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值