Tony The Lion
Tony The Lion

Reputation: 63310

c++ macro wrapped in function pointer to put into vector

I have a macro that might look as follows (from boost log library)

#define L_(lvl) BOOST_LOG_USE_LOG_IF_LEVEL(g_l(), g_log_level(), lvl )

Is it possible to wrap this into a boost::function<> object or a function pointer and stick it in a queue or vector of such items?

If it is, how would I do that?

I'm trying to write a mechanism where I have 1 thread to write all logging to log files, and any of the worker threads need to be able to log to it, but dependent on the active log level, I'd only want to log what's configured to be logged. So I would create a queue for any thread to queue the log messages on and then write them to their respective file with a dedicated thread, so as to not slow down my program, when lots of logging is needed. I want to use boost::log library so I have to work with this macro as this writes to the file under the covers.

lvl is a log level that you'd pass to this function. its use would be: L_(debug) << "some log text";

Upvotes: 0

Views: 520

Answers (5)

jyoung
jyoung

Reputation: 5181

Is there a reason why you can not use the Boost implementation of the dedicated thread writer?

typedef logger_format_write< default_, default_, writer::threading::on_dedicated_thread > logger_type;

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

struct LogFunction
{
    LogFunction(int lvl) :lvl_(lvl) {}    

    TYPE operator () () { return L_(lvl_); }
    // Where "TYPE" is whatever type L_ returns
private:
    int lvl_;
};

Upvotes: 1

yasouser
yasouser

Reputation: 5187

void Log(int level)
{
  L_(level);
}

typedef boost::function1<void, int> LogFunction;

std::vector< LogFunction > LogFunctionVector;

LogFunction L3 = Log(3);
LogFunction L5 = Log(5);

LogFunctionVector.push_back(L3);
LogFunctionVector.push_back(L5);

Upvotes: 0

Frerich Raabe
Frerich Raabe

Reputation: 94529

If you have a fixed set of logging levels, you could just call that macro from within a function and use a pointer to that function:

void log() {
  L_(3);
}

void anotherlog() {
  L_(13);
}

You can easily have that in a vector an then call them all:

typedef void (*LogFunction)();
std::vector<LogFunction> logFunctions;
logFunctions.push_back( log );
logFunctions.push_back( anotherLog );

std::vector<LogFunction>::iterator it, end = logFunctions.end();
for ( it = logFunctions.begin(); it != end; ++it )
    (*it)();

Upvotes: 1

Puppy
Puppy

Reputation: 147036

No, you can't put a macro anywhere near a function pointer like that. There's not even any need for a macro like this, you could just use an object-orientated function.

Upvotes: 0

Related Questions