C/C++ 简单的Log日志
最近写了一个动态链接库提供给C#界面开发的同事调用。为了方便调试输出,用C/C++的标准库API编写了一个Log日志库。
读取本地时间作为Log文件名,一天一个文件,定义一个LOG_LEVEL,一共分为五个级别。
#include <iostream>
#include <fstream>
#include <time.h>
typedef enum enLogLevel {
LOG_DEBUG = 1,
LOG_INFO,
LOG_ERROR,
LOG_WARN,
LOG_FATAL
}LogLevel;
const char LogTip[][8] = { "","Debug","Info","Error","Warn","Fatal" };
void getLogFileName(string &logFileName)
{
time_t t = time(0);
char tmp[32] = { NULL };
strftime(tmp, sizeof(tmp), "%Y-%m-%d", localtime(&t));
strcat(tmp, ".log");
char path[50] = "LogFile/";
strcat(path, tmp);
logFileName = path;
}
void writeLog(int logLevel, const char *pLogFormat)
{
string logFileName;
getLogFileName(logFileName);
std::ofstream OsWrite(logFileName, std::ofstream::app);
char logTxt[2048];
memset(logTxt, 0, sizeof(logTxt));
time_t t = time(0);
char date[32] = { NULL };
strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&t));
sprintf(logTxt, "%s : [%s] %s\n", date, LogTip[logLevel], pLogFormat);
OsWrite << logTxt;
OsWrite << std::endl;
OsWrite.close();
}
使用方法:
int main(){
writeLog(LOG_DEBUG, "debug...!");
writeLog(LOG_ERROR, "error....!");
writeLog(LOG_WARN, "warnning...!");
writeLog(LOG_FATAL, "fatal!...");
writeLog(LOG_INFO, "info!...");
}
return 0;