C++ 记录每个函数和参数值

标签 c++ logging

我想记录我的 C++ 应用程序中的每个函数调用和参数值。 下面是我想出的代码:

头文件:

#pragma once
class Deneme1
{
public:
    Deneme1(void);
    ~Deneme1(void);
    int Deneme1::foo1(double &a);
    int Deneme1::foo2(double &a);

    struct Logger
    {};

    template <typename T>
    struct LogReturner
    {
        T* ptrReturnValue;
        Logger& theLog;
        LogReturner(Logger& log, T* retVal) : theLog(log), ptrReturnValue(retVal) { }
        ~LogReturner() { /**/ }
    };

    #define EXPAND_ARGS(...) __VA_ARGS__;
    #define LOG_FUNCTION_CALL(x, logger, varName, ar) x varName; LogReturner<x> LR(logger, &varName); FuncCall(__FUNCTION__, EXPAND_ARGS ar);

    Logger globLogger;
};

Cpp文件:

#include "Deneme1.h"
#include "FuncCall.h"

Deneme1::Deneme1(void)
{
}

Deneme1::~Deneme1(void)
{
}

int Deneme1::foo1(double &a)
{
    LOG_FUNCTION_CALL(int, globLogger, returnValue,EXPAND_ARGS());
    Deneme1 c;
    double d = 5;
    c.foo2(d);
    return returnValue;
}

int Deneme1::foo2(double &a)
{
    LOG_FUNCTION_CALL(int, globLogger, returnValue);
    return returnValue;
}

.h文件负责处理日志功能:

#pragma once

#include <stdio.h>
#include <cstdarg>
#include <iostream>

class FuncCall
{

public:

    FuncCall(const char * lpszFuncName, ...) { 

        printf(lpszFuncName);printf("\n"); 
        va_list arguments;                 
        double sum = 0;
        int num = 1;
        va_start ( arguments, num );            
        for ( int x = 0; x < num; x++ )          
            std::cout << va_arg ( arguments, double ) << std::endl;
        va_end ( arguments ); 

    }

   ~FuncCall() { printf("func return ");printf("\n"); }
};

但是编译器提示说在“LOG_FUNCTION_CALL”中找不到“EXPAND_ARGS”。 其实我不知道如何正确调用“LOG_FUNCTION_CALL”。

谢谢。

最佳答案

对于自由函数,这可能要简单得多:

template <typename F, typename ...Args>
auto function_call_impl(F f, char const * fname, Args &&... args)
-> decltype(f(std::forward<Args>(args)...))
{
    std::cout << "Calling function '" << fname << "'\n";
    return f(std::forward<Args>(args)...);
}

#define CALL(function, ...) function_call_impl(function, #function, __VA_ARGS__)

用法:

int foo(double, char, bool);

int main()
{
    return CALL(foo, 0.5, 'x', false);
}

通过一些额外的工作,您也可以打印出参数。

关于C++ 记录每个函数和参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379972/

相关文章:

C++11 Lambda 表达式作为回调函数

c - 将数据从 C 传递到 R

java - 以编程方式更改 log4j2 ROOT 记录器,添加 AppenderRef + ThreadContextMapFiler 值

c++ - 特定 type_trait vector 的类特化

c++ - 'delete' 函数之前的预期 Unqualified-Id

java - Spring项目部署抛出org.apache.commons.logging.Log的ClassNotFoundException

asp.net - IIS6日志文件报告大块,当映射为通过asp.net引擎处理所有请求时,作为pdf文件的完整下载

java - 通过 ssh 文件传输从服务器自动下载日志到本地计算机

c++ - 运行时检查失败 #2 - 变量 'db' 周围的堆栈已损坏。 c++ (帮助)

c++ - 确定在向左/向右转弯后沿直线行进的方向?