Scarlet
Scarlet

Reputation: 151

How to write variable argument logger function which does actual logging in c++

i am writing a logger class in c++ i want to redirect all the logs from different files to a function which decides where to write the log.

for example,

func A()
{
int a =10;
std::string b = "test";
cout<<"printing"<<a<<b<<endl;
}

func B()
{
unsigned long t = 6700;
cout<<t<<endl;
}

Instead of cout i want to have a function which takes variable arguments and sent to common function which finally prints or writes into a file or used syslog.

Upvotes: 1

Views: 745

Answers (1)

NicholasM
NicholasM

Reputation: 4673

What if you tried something simple, like this?

std::unique_ptr<std::ostream> g_ostream_ptr;


std::ostream& log() {
    return *g_ostream_ptr;
}

void initialize_log() { 
    // initialize `g_ostream_ptr` based on environment variable
    // or other configuration information.
    const char* filename = std::getenv("LOG_FILE");
    if (!filename)
        filename = "/dev/stdout"

    g_ostream_ptr = std::make_unique<std::ostream>(filename);
}

Then you could use it like this:

void f() {
    log() << “f called.” << std::endl;
}

You would have to ensure that initialize_logis called at some point, perhaps using std::call_once, or perhaps by simply calling it in main().

Upvotes: 1

Related Questions