【发布时间】:2025-12-07 14:55:02
【问题描述】:
我已经编写了以下代码来在我的日志文件中写入日志。 这段代码可以很好地记录消息,但现在我必须将它集成到多个文件中,我需要调用者的文件路径、调用者函数名称和行号。
请帮助我实现这一目标。
#include "Source.h"
bool CLogManager::fileOpenError = false;
std::string CLogManager::logFileName = "";
CLogManager* CLogManager::logManager = NULL;
FILE* CLogManager::file = NULL;
CLogManager :: CLogManager(){}
CLogManager :: ~CLogManager()
{
if (file)
fclose(file);
}
CLogManager* CLogManager::getInstance()
{
if(logManager==NULL)
{
logManager = new CLogManager();
logFileName = currentDateTime();
}
return logManager;
}
const std::string CLogManager::currentDateTime()
{
time_t now = time(0);
char currTime[30];
strftime(currTime, sizeof(currTime), "Log_%Y_%m_%dT%H_%M_%S.xml", localtime(&now));
return currTime;
}
void CLogManager::Log (char *message)
{
file = fopen(logFileName.c_str(), "a+");
if(file == NULL)
{
if(fileOpenError == false)
{
std::cout << "There was an error While opening Log File."<<std::endl;
fileOpenError = true;
}
return;
}
fputs(message, file);
fputs("\n", file);
}
int main ()
{
CLogManager::getInstance();
CLogManager::Log("Sorry some error occured");
CLogManager::Log("Please try again");
CLogManager::Log("Wait");
return 0;
}
【问题讨论】:
-
y 不使用 log4net 进行日志记录,而不是创建自己的类? log4net 还会为您提供函数名称和其他一些详细信息。不确定行号。您可以从 Log4net C# 制作一个 dll 并在您的 C++ 代码中使用它
-
我知道的唯一方法是使用宏。像::
#define log(msg) CLogManager::Log(std::string(msg) + " " + __FILE__ + "[" + std::to_string(__LINE__) + "]"). -
读取*.com/questions/353180/…获取函数名
标签: c++ error-logging