Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ log every function and parameter values

Tags:

c++

logging

I want to log every function call and parameter values in my C++ app. Below is the code I came up with:

Header file :

#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 file:

#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 file responsible for handling log functions :

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

But compiler complains that in "LOG_FUNCTION_CALL" it cannot find "EXPAND_ARGS". Actually I don't know how to call "LOG_FUNCTION_CALL" properly.

Thanks.

like image 638
uahakan Avatar asked Oct 04 '22 16:10

uahakan


1 Answers

For free functions this could be much simpler:

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__)

Usage:

int foo(double, char, bool);

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

With a bit of extra work you can print out the arguments, too.

like image 95
Kerrek SB Avatar answered Oct 07 '22 19:10

Kerrek SB