0

I need to write a custom appender in log4cxx. This answer describes how to do it. In Java, in log4j, it is possible for a custom appender to devise custom parameters. I add a property and a getter and setter:

 private int myParameter = 0;
 public void setMyParameter(int p) { myParameter = p; }
 public int  getMyParameter() { return myParameter; }

Then I can use myParameter in configuration file, and the framework somehow knows how to configure my appender with it.

Question: does log4cxx have a similar capability? For me it is enough if I get a map map<string, string> with properties.

Community
  • 1
  • 1
Andrzej
  • 5,027
  • 27
  • 36

1 Answers1

0

Ok, figured out the answer myself. You need to override member function setOption. It will get called a number of times: once per each read option. You then override function activateOptions and its get called after all options have been processed. It can be used as a trigger to initialize the appender with the read parameters.

Not as convenient as mapping to getters/setters, but it gets the job done:

class CustomAppender : public AppenderSkeleton
{
  int _myParameter = 0;
  void initialize(int myParameter);
  // ...

public:
  void setOption(LogString const& option, LogString const& value) override
  {
    if (option == "MyParameter") try
    {
      _myParameter = boost::lexical_cast<int>(value);
    }
    catch (boost::bad_lexical_cast const&) {
      // go with default
    }
  }

  void activateOptions(helpers::Pool &) override
  {
    initialize(_myParameter);
  }
};
Andrzej
  • 5,027
  • 27
  • 36
  • Thanks for the tip! Are you using ReSharper? +1 on 2 char tabs. The dangling `try` is weird. – bvj Aug 03 '16 at 06:24