omer
omer

Reputation: 1442

How can I add the console (stdout) as a sink in g3log?

I am new to g3log. I compiled and ran one of the examples I found in the repo, but was not able to ,modify it to print the log messages to the console rather than a file. The following lines from the example set the logger:

   auto worker = g3::LogWorker::createLogWorker();
   auto handle= worker->addDefaultLogger(argv[0], path_to_log_file);
   g3::initializeLogging(worker.get());

Where the line in the middle sets the prefix of the log and gives the path where the log file should be created. How can I modify this code to print to the console\both the console and the file?

Thanks,

Omer.

Upvotes: 2

Views: 1397

Answers (2)

Houcheng
Houcheng

Reputation: 2894

You could define a customized sink class with a message receiver function that forward the stripped message to console without formatting. Below is simplest form of the implementation:

class CustomSink {
public:
    void forwardLogToStdout(g3::LogMessageMover logEntry) {
        std::cout << logEntry.get().message() << std::endl;
    }
};

So, in your code, you only need to replacing the worker->addDefaultLogger(...) by this snippet:

auto handle = worker->addSink(std::make_unique<CustomSink>(), &CustomSink::forwardLogToStdout);

Upvotes: 1

Max Star
Max Star

Reputation: 16

from g3log github to implement colored console output you need:

struct ColorCoutSink {

// Linux xterm color
// http://stackoverflow.com/questions/2616906/how-do-i-output-coloured-text-to-a-linux-terminal

enum FG_Color {YELLOW = 33, RED = 31, GREEN=32, WHITE = 97};

    FG_Color GetColor(const LEVELS level) const 
    {
        if (level.value == WARNING.value) { return YELLOW; }
        if (level.value == DEBUG.value) { return GREEN; }
        if (g3::internal::wasFatal(level)) { return RED; }

        return WHITE;
    }

    void ReceiveLogMessage(g3::LogMessageMover logEntry)
    {
        auto level = logEntry.get()._level;
        auto color = GetColor(level);

        std::cout << "\033[" << color << "m" << logEntry.get().toString() << "\033[m" << std::endl;
    }
};

// in main.cpp, main() function

auto sinkHandle = logworker->addSink(std::make_unique<CustomSink>(),
                                 &CustomSink::ReceiveLogMessage);

So if you remove color "things", the logger will output to console

Upvotes: 0

Related Questions