gpt4 book ai didi

c++ - 在C++中获取调用函数的名称、行号和文件名

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:18 34 4
gpt4 key购买 nike

我已经编写了以下代码来在我的日志文件中写入日志。这段代码可以很好地记录消息,但现在我必须将它集成到多个文件中,我需要调用者的文件路径、调用者函数名称和行号。

请帮助我实现这一目标。

#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;
}

最佳答案

从 C++ 20 开始,您可以使用 std::source_location

来自 CPPReference.com 上的示例:

#include <iostream>
#include <string_view>
#include <source_location>

void log(const std::string_view message,
const std::source_location location =
std::source_location::current())
{
std::cout << "file: "
<< location.file_name() << "("
<< location.line() << ":"
<< location.column() << ") `"
<< location.function_name() << "`: "
<< message << '\n';
}

template <typename T> void fun(T x)
{
log(x);
}

int main(int, char*[])
{
log("Hello world!");
fun("Hello C++20!");
}

输出:

file: main.cpp(23:8) `int main(int, char**)`: Hello world!
file: main.cpp(18:8) `void fun(T) [with T = const char*]`: Hello C++20!

关于c++ - 在C++中获取调用函数的名称、行号和文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27120494/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com