log4cxx -- is it possible to configure a custom appender with custom arguments from a config file?
Asked Answered
L

1

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.

Luciano answered 7/4, 2016 at 14:59 Comment(0)
L
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);
  }
};
Luciano answered 8/4, 2016 at 11:34 Comment(1)
Thanks for the tip! Are you using ReSharper? +1 on 2 char tabs. The dangling try is weird.Abebi

© 2022 - 2024 — McMap. All rights reserved.