编程语言
首页 > 编程语言> > android10.0 高通865 平台C++日志调试工具

android10.0 高通865 平台C++日志调试工具

作者:互联网

参考博客:

C++还在用printf/cout进行Debug?学习一下如何自己写日志库吧(上篇)_花狗Fdog的博客-CSDN博客

代码目录结构

fdlog/Android.mk
fdlog/fdoglogconf.conf             //该文件需要手动push到android手机的sdcard目录下
fdlog/fdoglogger.cpp
fdlog/fdoglogger.h
fdlog/filemanagement.cpp
fdlog/filemanagement.h
fdlog/main.cpp

Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE = fdlog

LOCAL_SRC_FILES = main.cpp \
                  fdoglogger.cpp \
                  filemanagement.cpp

LOCAL_C_INCLUDES := $(LOCAL_PATH)

LOCAL_CFLAGS += -Wall -Wno-unused-parameter

LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog

LOCAL_SHARED_LIBRARIES := \
            libcutils \
            liblog \
            libandroidfw \
            libutils

include $(BUILD_EXECUTABLE)


fdoglogconf.conf   //该文件需要通过adb push 到android手动的/sdcard/目录下

#日志开关
logSwitch = on
#是否写入文件
logFileSwitch = off
#是否打印在终端
logTerminalSwitch = on
#是否开启队列策略
logFileQueueSwitch = on
#日志指定等级输出(文件)
logOutputLevelFile = 1,2,3,4,5
#日志指定等级输出(终端)
logOutputLevelTerminal =1,2,3,4,5
#日志文件名字:
logName = fdoglog
#日志文件保存路径:
logFilePath = /sdcard/FdogLog/logs/
#日志文件最大大小(单位为MB 1024MB=1G):
logMixSize = 100
#日志文件达到大小行为(0继续写入,1新文件写入):
logBehavior = 1


fdoglogger.cpp

#ifdef _WIN32
#define _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#endif
#include"fdoglogger.h"

using namespace fdog;

FdogLogger * FdogLogger::singleObject = nullptr;
mutex * FdogLogger::mutex_log = new(mutex);
mutex * FdogLogger::mutex_file = new(mutex);
mutex * FdogLogger::mutex_queue = new(mutex);
mutex * FdogLogger::mutex_terminal = new(mutex);

FdogLogger::FdogLogger(){
    initLogConfig();
}

FdogLogger::~FdogLogger(){

}

FdogLogger* FdogLogger::getInstance(){
    mutex_log->lock();
    if (singleObject == nullptr) {
        singleObject = new FdogLogger();
    }
    mutex_log->unlock();
    return singleObject;
}

void FdogLogger::initLogConfig(){
#ifdef __linux__
    coutColor["Error"] = "\e[1;31m";
    coutColor["Warn"] = "\e[1;35m";
    coutColor["Info"] = "\e[1;34m";
    coutColor["Debug"] = "\e[1;32m";
    coutColor["Trace"] = "\e[1;37m";
#elif _WIN32
	coutColor["Error"] = "";
	coutColor["Warn"] = "";
	coutColor["Info"] = "";
	coutColor["Debug"] = "";
	coutColor["Trace"] = "";
#endif

    map<string, string *> flogConfInfo;
    flogConfInfo["logSwitch"] = &this->logger.logSwitch;
    flogConfInfo["logFileSwitch"] = &this->logger.logFileSwitch;
    flogConfInfo["logTerminalSwitch"] = &this->logger.logTerminalSwitch;
    flogConfInfo["logFileQueueSwitch"] = &this->logger.logFileQueueSwitch;
    flogConfInfo["logName"] = &this->logger.logName;
    flogConfInfo["logFilePath"] = &this->logger.logFilePath;
    flogConfInfo["logMixSize"] = &this->logger.logMixSize;
    flogConfInfo["logBehavior"] = &this->logger.logBehavior;
    flogConfInfo["logOutputLevelFile"] = &this->logger.logOutputLevelFile;
    flogConfInfo["logOutputLevelTerminal"] = &this->logger.logOutputLevelTerminal;
	
	bool isOpen = true;
    string str;
    ifstream file;
    char str_c[100]={0};
#ifdef __linux__
    file.open("/sdcard/fdoglogconf.conf");
#elif _WIN32
	file.open("fdoglogconf.conf");
#endif
    if(!file.is_open()){
		isOpen = false;
        cout<<"File open failed" <<endl;
    }
    while(getline(file, str)){
        if(!str.length()) {
            continue;
        }
        string str_copy = str;
        int j = 0;
        for(int i = 0; i < str.length(); i++){
            if(str[i]==' ')continue;
            str_copy[j] = str[i];
            j++;
        }
        str_copy.erase(j);
        if(str_copy[0]!='#'){
            sscanf(str_copy.data(),"%[^=]",str_c);
            auto iter = flogConfInfo.find(str_c);
            if(iter!=flogConfInfo.end()){
                sscanf(str_copy.data(),"%*[^=]=%s",str_c);
                *iter->second = str_c;
            } else {
            }
        }
    }
    file.close();

    bindFileCoutMap("5", fileType::Error);
    bindFileCoutMap("4", fileType::Warn);
    bindFileCoutMap("3", fileType::Info);
    bindFileCoutMap("2", fileType::Debug);
    bindFileCoutMap("1", fileType::Trace);

    bindTerminalCoutMap("5", terminalType::Error);
    bindTerminalCoutMap("4", terminalType::Warn);
    bindTerminalCoutMap("3", terminalType::Info);
    bindTerminalCoutMap("2", terminalType::Debug);
    bindTerminalCoutMap("1", terminalType::Trace);

    string filePashAndName = getFilePathAndName();
    string filePash = getFilePash();
	cout << filePashAndName << " : " << filePash << endl;
    if(logger.logFileSwitch == SWITCH_ON){
        //检查路径
        filemanagement.createFilePash(filePash);
        //检测文件有效性
        if(!filemanagement.verifyFileExistence(filePashAndName)) {
            filemanagement.createFile(filePashAndName);
        } else {
            long fileSize = filemanagement.verifyFileSize(filePashAndName);
            if (fileSize > (long)atoi(logger.logMixSize.data()) * MEGABYTES && logger.logBehavior == "1"){
                string newFileName = getFilePathAndNameAndTime();
                filemanagement.fileRename(filePashAndName, newFileName);
                filemanagement.createFile(filePashAndName);
            }
        }
    }
	if (isOpen) {
		ConfInfoPrint();
	}
    return;
}

void FdogLogger::releaseConfig() {

}

void FdogLogger::ConfInfoPrint() {
#ifdef __linux__
    for(int i = 0; i < logger.logFilePath.size() + 15; i++){
        cout << GREEN << "-";
        if(i == (logger.logFilePath.size() + 15)/2){
            cout << "FdogLogger";
        }
    }
    cout << DEFA << endl;
    cout << GREEN << ::left<<setw(25) << "  日志开关  " << logger.logSwitch << DEFA << endl;
    cout << GREEN << ::left<<setw(25) << "  文件输出  " << logger.logFileSwitch << DEFA << endl;
    cout << GREEN << ::left<<setw(25) << "  终端输出开关" << logger.logTerminalSwitch << DEFA << endl;
    cout << GREEN << ::left<<setw(25) << "  文件输出等级" << logger.logOutputLevelFile << DEFA << endl;    
    cout << GREEN << ::left<<setw(25) << "  终端输出等级" << logger.logOutputLevelTerminal << DEFA << endl;
    cout << GREEN << ::left<<setw(25) << "  日志队列策略" << logger.logFileQueueSwitch << DEFA << endl;    
    cout << GREEN << ::left<<setw(25) << "  日志文件名称" << logger.logName << ".log" << DEFA << endl;
    cout << GREEN << ::left<<setw(25) << "  日志保存路径" << logger.logFilePath << DEFA << endl;
    cout << GREEN << ::left<<setw(25) << "  日志文件大小" << logger.logMixSize << "M" << DEFA << endl;
    for(int i = 0; i < logger.logFilePath.size() + 25; i++){
        cout << GREEN << "-" << DEFA;
    }
    cout << endl;
#elif _WIN32
	for (int i = 0; i < logger.logFilePath.size() + 15; i++) {
		cout << "-";
		if (i == (logger.logFilePath.size() + 15) / 2) {
			cout << "FdogLogger";
		}
	}
	cout << endl;
	cout << ::left << setw(25) << "  日志开关  " << logger.logSwitch << endl;
	cout << ::left << setw(25) << "  文件输出  " << logger.logFileSwitch << endl;
	cout << ::left << setw(25) << "  终端输出开关" << logger.logTerminalSwitch << endl;
	cout << ::left << setw(25) << "  文件输出等级" << logger.logOutputLevelFile << endl;
	cout << ::left << setw(25) << "  终端输出等级" << logger.logOutputLevelTerminal << endl;
	cout << ::left << setw(25) << "  日志队列策略" << logger.logFileQueueSwitch << endl;
	cout << ::left << setw(25) << "  日志文件名称" << logger.logName << ".log" << endl;
	cout << ::left << setw(25) << "  日志保存路径" << logger.logFilePath << endl;
	cout << ::left << setw(25) << "  日志文件大小" << logger.logMixSize << "M" << endl;
	for (int i = 0; i < logger.logFilePath.size() + 25; i++) {
		cout << "-";
	}
	cout << endl;
#endif
}

string FdogLogger::getCoutType(coutType coutType){
    return singleObject->coutTypeMap[coutType];
}

bool FdogLogger::getFileType(fileType fileCoutBool){
    return singleObject->fileCoutMap[fileCoutBool];
}

bool FdogLogger::getTerminalType(terminalType terminalCoutTyle){
    return singleObject->terminalCoutMap[terminalCoutTyle];
}

string FdogLogger::getLogCoutTime(){
    time_t timep;
    time (&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep));
    string tmp_str = tmp;
	return SQUARE_BRACKETS_LEFT + tmp_str + SQUARE_BRACKETS_RIGHT;
}

string FdogLogger::getLogNameTime(){
    time_t timep;
    time (&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d-%H:%M:%S",localtime(&timep));
    return tmp;
}

string FdogLogger::getSourceFilePash(){
#ifdef __linux__
	getcwd(szbuf, sizeof(szbuf) - 1);
#elif _WIN32
	getcwd(szbuf, sizeof(szbuf) - 1);
#endif
    string szbuf_str = szbuf;
    return szbuf_str + SLASH;
}
string FdogLogger::getFilePash(){
    return logger.logFilePath + SLASH;
}

string FdogLogger::getFilePathAndName(){
#ifdef __linux__
    return logger.logFilePath + SLASH + logger.logName + ".log";
#elif _WIN32
	return logger.logFilePath + logger.logName + ".log";
#endif
}

string FdogLogger::getFilePathAndNameAndTime(){
    return logger.logFilePath + logger.logName + getLogNameTime() + ".log";
}

string FdogLogger::getLogCoutProcessId(){
#ifdef __linux__
    return to_string(getpid());
#elif _WIN32
	return to_string(getpid());
//  return GetCurrentProcessId();
#endif
}

string FdogLogger::getLogCoutThreadId(){
#ifdef __linux__
    return to_string(syscall(__NR_gettid));
#elif _WIN32
    return to_string(GetCurrentThreadId());
#endif

}

string FdogLogger::getLogCoutUserName(){
#ifdef __linux__
	struct passwd * my_info;
	my_info = getpwuid(getuid());
	string name = my_info->pw_name;
	return SPACE + name + SPACE;
#elif _WIN32
	const int MAX_LEN = 100;
	TCHAR szBuffer[MAX_LEN];
	DWORD len = MAX_LEN;
	GetUserName(szBuffer, &len);
	
	int iLen = WideCharToMultiByte(CP_ACP, 0, szBuffer, -1, NULL, 0, NULL, NULL);
	char * chRtn = new char[iLen * sizeof(char)];
	WideCharToMultiByte(CP_ACP, 0, szBuffer, -1, chRtn, iLen, NULL, NULL);
	string str(chRtn);
	return " " + str + " ";
#endif

}

bool FdogLogger::logFileWrite(string messages, string message, string line_effd){
    string filePashAndName = getFilePathAndName();

    long fileSize = filemanagement.verifyFileSize(filePashAndName);
    if (fileSize > (long)atoi(logger.logMixSize.data()) * MEGABYTES && logger.logBehavior == "1"){
        string newFileName = getFilePathAndNameAndTime();
        filemanagement.fileRename(filePashAndName, newFileName);
        filemanagement.createFile(filePashAndName);
    }
    if(logger.logFileQueueSwitch == SWITCH_OFF){
        mutex_file->lock();
        ofstream file;
        file.open(filePashAndName, ::ios::app | ios::out);
        file << messages << message << line_effd;
        file.close();
        mutex_file->unlock();
    }else{
        insertQueue(messages + message + line_effd, filePashAndName);
    }
    return 1;
}

bool FdogLogger::insertQueue(string messages, string filePashAndName){
    mutex_queue->lock();
    messageQueue.push(messages);
    if(messageQueue.size() >= 5000){
        mutex_file->lock();
        ofstream file;
        file.open(filePashAndName, ::ios::app | ios::out);
        while(!messageQueue.empty()){
            file << messageQueue.front();
            messageQueue.pop();
        }
        file.close();
        mutex_file->unlock();
    }
    mutex_queue->unlock();
	return true;
}

string FdogLogger::getLogSwitch(){
    return logger.logSwitch;
}

string FdogLogger::getLogFileSwitch(){
    return logger.logFileSwitch;
}

string FdogLogger::getLogTerminalSwitch(){
    return logger.logTerminalSwitch;
}
string FdogLogger::getCoutTypeColor(string colorType){
#ifdef __linux__
	return coutColor[colorType];
#elif _WIN32
	return "";
#endif
}

bool FdogLogger::bindFileCoutMap(string value1, fileType value2){
    if(logger.logOutputLevelFile.find(value1) != std::string::npos) {
        fileCoutMap[value2] = true;
    } else {
        fileCoutMap[value2] = false;
    }
	return true;
}

bool FdogLogger::bindTerminalCoutMap(string value1, terminalType value2){
    if(logger.logOutputLevelTerminal.find(value1)!=std::string::npos) {
        terminalCoutMap[value2] = true;
    } else {
        terminalCoutMap[value2] = false;
    }
	return true;
}


fdoglogger.h

#ifndef FDOGLOGGER_H
#define FDOGLOGGER_H
#include<iostream>
#include<fstream>
#include <sstream>
#include<iomanip>
#include<map>
#include<mutex>
#include<queue>
#include"filemanagement.h"
#ifdef __linux__
#include<unistd.h>
#include<sys/syscall.h>
#include<sys/stat.h>
#include<sys/types.h>
#include <pwd.h>
#elif _WIN32
#include<direct.h>
#include<process.h>
#include<Windows.h>
#endif

using namespace std;

namespace fdog {

#define RED   "\e[1;31m"
#define BLUE  "\e[1;34m"
#define GREEN "\e[1;32m"
#define WHITE "\e[1;37m"
#define PURPLE "\e[1;35m"
#define DEFA  "\e[0m"

#define MEGABYTES 1048576
#define SWITCH_OFF "off"
#define SWITCH_ON  "on"

enum class coutType: int {Error, Warn, Info, Debug, Trace};
enum class fileType: int {Error, Warn, Info, Debug, Trace};
enum class terminalType: int {Error, Warn, Info, Debug, Trace};

struct Logger {
    string logSwitch;           //日志开关
    string logFileSwitch;       //是否写入文件
    string logTerminalSwitch;   //是否打印到终端
    string logFileQueueSwitch;  //是否开启队列策略
    string logName;             //日志文件名字
    string logFilePath;         //日志文件保存路径
    string logMixSize;          //日志文件最大大小
    string logBehavior;         //日志文件达到最大大小行为
    string logOutputLevelFile;  //日志输出等级(file)
    string logOutputLevelTerminal;//日志输出等级
};

class FdogLogger {
public:
    void initLogConfig();

    void releaseConfig();

    void ConfInfoPrint();

    static FdogLogger* getInstance();

    string getCoutType(coutType coutType);

    bool getFileType(fileType fileCoutBool);

    bool getTerminalType(terminalType terminalCoutTyle);

    string getLogCoutTime();

    string getLogNameTime();

    string getSourceFilePash();

    string getFilePash();

    string getFilePathAndName();

    string getFilePathAndNameAndTime();

    string getLogCoutProcessId();

    string getLogCoutThreadId();

    string getLogCoutUserName();
    
    string getLogSwitch();

    string getLogFileSwitch();

    string getLogTerminalSwitch();

    string getCoutTypeColor(string colorType);

    bool logFileWrite(string messages, string message, string LINE);

    bool insertQueue(string messages, string filePashAndName);

    bool bindFileCoutMap(string value1, fileType value2);

    bool bindTerminalCoutMap(string value1, terminalType value2);

	static mutex * mutex_terminal;
private:
    char szbuf[128];
    Logger logger;
    FileManagement filemanagement;
    static FdogLogger * singleObject;
    static mutex * mutex_log;
    static mutex * mutex_file;
    static mutex * mutex_queue;
    map<coutType, string> coutTypeMap;
    map<fileType, bool> fileCoutMap;
    map<terminalType, bool> terminalCoutMap;
    map<string, string> coutColor;
    queue<string> messageQueue;

private:
    FdogLogger();
    ~FdogLogger();
};

#define Error1 __FDOGNAME__(Error)
#define Warn1 __FDOGNAME__(Warn)
#define Info1 __FDOGNAME__(Info)
#define Debug1 __FDOGNAME__(Debug)
#define Trace1 __FDOGNAME__(Trace)


#define SQUARE_BRACKETS_LEFT " ["
#define SQUARE_BRACKETS_RIGHT "] "
#define SPACE " "
#define LINE_FEED "\n"
#define COLON ":"
#define SLASH "/"

#define __FDOGTIME__  FdogLogger::getInstance()->getLogCoutTime()          //时间宏
#define __FDOGPID__   FdogLogger::getInstance()->getLogCoutProcessId()     //进程宏
#define __FDOGTID__   FdogLogger::getInstance()->getLogCoutThreadId()      //线程宏
#define __USERNAME__  FdogLogger::getInstance()->getLogCoutUserName()     //获取调用用户名字
#define __FDOGFILE__  __FILE__          //文件名宏
#define __FDOGFUNC__  __func__          //函数名宏
#define __FDOGLINE__  __LINE__          //行数宏
#define __FDOGNAME__(name) #name        //名字宏


#define COMBINATION_INFO_FILE(coutTypeInfo, message) \
    do{\
        ostringstream oss;\
        streambuf* pOldBuf = std::cout.rdbuf(oss.rdbuf());\
        cout << message;\
        string ret = oss.str();\
        cout.rdbuf(pOldBuf);\
        string messagesAll = __FDOGTIME__ + coutTypeInfo + __USERNAME__ + __FDOGTID__ + SQUARE_BRACKETS_LEFT + \
        __FDOGFILE__  + SPACE +__FDOGFUNC__ + COLON + to_string(__FDOGLINE__) + SQUARE_BRACKETS_RIGHT;\
        FdogLogger::getInstance()->logFileWrite(messagesAll, ret, LINE_FEED); \
    }while(0);

#ifdef __linux__
#define COMBINATION_INFO_TERMINAL(coutTypeInfo, message) \
    do{\
        string color = FdogLogger::getInstance()->getCoutTypeColor(coutTypeInfo);\
        string logFormatCout = __FDOGTIME__ + color + coutTypeInfo + DEFA + __USERNAME__ + __FDOGTID__ + SQUARE_BRACKETS_LEFT + \
        __FDOGFILE__  + SPACE +__FDOGFUNC__ + COLON + to_string(__FDOGLINE__) + SQUARE_BRACKETS_RIGHT;\
		FdogLogger::mutex_terminal->lock(); \
        cout << logFormatCout << message << LINE_FEED;\
		fflush(stdout);\
        FdogLogger::mutex_terminal->unlock(); \
    }while(0);
#elif _WIN32
    do{\
        string color = FdogLogger::getInstance()->getCoutTypeColor(coutTypeInfo);\
        string logFormatCout = __FDOGTIME__ + color + coutTypeInfo +  __USERNAME__ + __FDOGTID__ + SQUARE_BRACKETS_LEFT + \
        __FDOGFILE__  + SPACE +__FDOGFUNC__ + COLON + to_string(__FDOGLINE__) + SQUARE_BRACKETS_RIGHT;\
		FdogLogger::mutex_terminal->lock(); \
        cout << logFormatCout << message << LINE_FEED;\
		fflush(stdout);\
        FdogLogger::mutex_terminal->unlock(); \
    }while(0);
#endif

#define LoggerCout(coutTyle, coutTypeInfo, fileCoutBool, terminalCoutBool, message) \
    do {\
        string coutType = FdogLogger::getInstance()->getCoutType(coutTyle);\
        if( SWITCH_ON == FdogLogger::getInstance()->getLogSwitch()){\
            if (SWITCH_OFF != FdogLogger::getInstance()->getLogFileSwitch()){\
                if (FdogLogger::getInstance()->getFileType(fileCoutBool)) {\
                    COMBINATION_INFO_FILE(coutTypeInfo, message)\
                }\
            }\
            if (SWITCH_OFF != FdogLogger::getInstance()->getLogTerminalSwitch()){\
                if (FdogLogger::getInstance()->getTerminalType(terminalCoutBool)) {\
                    COMBINATION_INFO_TERMINAL(coutTypeInfo, message)\
                }\
            }\
        }\
    }while(0);

#define FdogError(...) \
    do{\
        LoggerCout(fdog::coutType::Error, Error1, fdog::fileType::Error, fdog::terminalType::Error, __VA_ARGS__)\
    }while(0);

#define FdogWarn(...)  \
    do{\
        LoggerCout(fdog::coutType::Warn, Warn1, fdog::fileType::Warn, fdog::terminalType::Warn, __VA_ARGS__)\
    }while(0);

#define FdogInfo(...)  \
    do{\
        LoggerCout(fdog::coutType::Info, Info1, fdog::fileType::Info, fdog::terminalType::Info, __VA_ARGS__)\
    }while(0);

#define FdogDebug(...) \
    do{\
        LoggerCout(fdog::coutType::Debug, Debug1, fdog::fileType::Debug, fdog::terminalType::Debug, __VA_ARGS__)\
    }while(0);

#define FdogTrace(...) \
    do{\
        LoggerCout(fdog::coutType::Trace, Trace1, fdog::fileType::Trace, fdog::terminalType::Trace, __VA_ARGS__)\
    }while(0);

}

#endif



filemanagement.cpp

#ifdef _WIN32
#define _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#endif

#include"filemanagement.h"
#define ONEDAY 24 * 60 * 60

FileManagement::FileManagement(){
}

FileManagement::~FileManagement(){
    //file.close();
}

bool FileManagement::createFilePash(string fileName){
    int len = fileName.length();
    if(!len){
        fileName = "log";
#ifdef __linux__
        if (0 != access(fileName.c_str(), F_OK)){
            if(-1 == mkdir(fileName.c_str(),0)){
                return false;
            }
        }
#elif _WIN32
		if (0 != access(fileName.c_str(), 0)) {
			if (-1 == mkdir(fileName.c_str())) {
				return false;
			}
		}
#endif
	}
    std::string fileName_cy(len,'\0');
    for(int i =0;i<len;i++){
        fileName_cy[i]=fileName[i];
        if(fileName_cy[i]=='/' || fileName_cy[i]=='\\'){
#ifdef __linux__
            if (-1 == access(fileName_cy.c_str(), F_OK)){
                if(0!=mkdir(fileName_cy.c_str(),0)){
                    return false;
                }
            }
#elif _WIN32
			if (-1 == access(fileName_cy.c_str(), 0)) {
				if (0 != mkdir(fileName_cy.c_str())) {
					return false;
				}
			}
#endif
        }
    }
    return true;
}

bool FileManagement::createFile(string fileName) {
    ofstream file;
    file.open(fileName, ::ios::app | ios::out);
    if(!file) {
        cout<<"Failed to create file"<<endl;
        return 0;
    }
    file.close();
    return 1;
}

bool FileManagement::verifyFileExistence(string fileName){
#ifdef __linux__
	return (access(fileName.data(), F_OK) != -1);
#elif _WIN32
	return (access(fileName.data(), 0) != -1);
#endif
}

//bool FileManagement::verifyFileValidityDays(string fileName, string logOverlay){
//#ifdef __linux__
//	struct stat statbuf;
//	timespec time_;
//	if (stat(fileName.data(), &statbuf) == 0) {
//		time_ = statbuf.st_mtim;
//	}
//#elif _WIN32
//	struct stat statbuf;
//	timespec time_;
//	if (stat(fileName.data(), &statbuf) == 0) {
//		time_ = statbuf.st_mtim;
//	}
//#endif
//    long logOverlay_i = (long)atoi(logOverlay.data());
//    long nowtime = getCurrentTime();
//    long difftime =  nowtime - time_.tv_sec;
//
//    if ((logOverlay_i * ONEDAY) >= difftime) {
//        return true;
//    }
//    return false;
//}

bool FileManagement::fileRename(string oldFile, string newFile){
    if(!rename(oldFile.data(), newFile.data())) {
        cout<<"File rename failed"<<endl;
    }
    return 0;
}

long FileManagement::verifyFileSize(string fileName){
    struct stat statbuf;
    if(stat(fileName.data(),&statbuf) == 0) {
        return statbuf.st_size;
    }
    //int size = filelength(fileno(filePash));
    return -1;
}

long FileManagement::getCurrentTime(){
    time_t timep;
    struct tm *p;
    time(&timep);
    p = localtime(&timep);
    timep = mktime(p);
    return timep;
}


filemanagement.h

#ifndef FILEMANAGEMENT_H
#define FILEMANAGEMENT_H
#include<iostream>
#include<string>
#include<fstream>
#include<time.h>
#ifdef __linux__
#include<unistd.h>
#include<sys/syscall.h>
#include<sys/stat.h>
#include<sys/types.h>
#elif _WIN32
#include<io.h>
#include<direct.h>
#endif
using namespace std;

class FileManagement {
public:
    FileManagement();

    ~FileManagement();

    bool createFilePash(string fileName);

    bool createFile(string fileName);

    bool verifyFileExistence(string fileName);

    //bool verifyFileValidityDays(string fileName, string logOverlay);废除

    bool fileRename(string oldFile, string newFile);

    long verifyFileSize(string fileName);

    long getCurrentTime();

};

#endif


main.cpp

#include<iostream>
#include<stdio.h>
#include <utils/Log.h>
#include"fdoglogger.h"  //添加日志库头文件

#define debugprintf 1
#ifdef debugprintf
#define debugpri(mesg, args...) fprintf(stderr, "[NetRate print:%s:%d:] " mesg "\n", __FILE__, __LINE__, ##args)
#else
#define debugpri(mesg, args...)
#endif

using namespace fdog;   //日志库的命名空间

int main(){
    time_t begin,end;
    double ret;
    begin=clock();
    string name = "花狗";
    printf("fdog fdog fdog\n");
    for(int i = 0; i< 10000; i++){
        FdogError("我是" << name << i);
        FdogWarn("我是" << name);
        FdogInfo("我是" << name);
        FdogDebug("我是" << name);
        FdogTrace("我是" << name);
    }
    end=clock();
    ret=double(end-begin)/CLOCKS_PER_SEC;
    cout<<"runtime:   "<<ret<<endl;
    
    debugpri("vclusters 123 vclusters vclusters 123\n");
    return 0;
}

实现后的效果图

 

标签:__,android10.0,return,string,865,C++,FdogLogger,include,define
来源: https://blog.csdn.net/u014630142/article/details/122415536