fabregaszy
fabregaszy

Reputation: 506

Poco Logger change Message parameters

I'm using Poco::Logger to trace logs in my application.

Now I want to trace a value of a variable in all of my logs. Since I do not want to change every line where I output the line before. I want to make it something default in the format.

I checked the documents and tutorial of Poco logging system, and found:

  • A message can store an arbitrary number of name-value pairs.
  • Names and values can be arbitrary strings.
  • Message parameters can be referenced in a formatter.

which looks like exactly what I'm looking for. But I cannot found detailed information about this and it seems that Poco::logger creates a Poco::Message itself.

Is there any way to achieve what I want to do? Thanks.

Upvotes: 1

Views: 1656

Answers (1)

Alex
Alex

Reputation: 5330

#include "Poco/Logger.h"
#include "Poco/AutoPtr.h"
#include "Poco/PatternFormatter.h"
#include "Poco/FormattingChannel.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/Message.h"

using namespace Poco;

int main()
{
    Message msg;
    msg.setSource("MySource");
    msg.setText("My message text");
    msg["myParam"] = "My Param";

    AutoPtr<FormattingChannel> pFCConsole = new FormattingChannel(new PatternFormatter("%s: %[myParam], %t"));
    pFCConsole->setChannel(new ConsoleChannel);
    pFCConsole->open();

    Logger& consoleLogger = Logger::root(); // or whatever your logger is
    consoleLogger.setChannel(pFCConsole);
    consoleLogger.log(msg);

    return 0;
}

Run:

$ ./Logger
MySource: My Param, My message text

Only std::string custom parameters are currently supported, so you will have to do the conversion if the value is numeric.

Upvotes: 3

Related Questions