log4cxx-是否可以使用来自配置文件的自定义参数来配置自定义附加程序? [英] log4cxx -- is it possible to configure a custom appender with custom arguments from a config file?
问题描述
我需要在log4cxx中编写一个自定义附加程序. 此答案描述了如何执行此操作.在Java中,在log4j中,自定义附加程序可以设计自定义参数.我添加了一个属性以及一个getter和setter:
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; }
然后我可以在配置文件中使用myParameter
,并且框架以某种方式知道如何使用它配置我的附加程序.
Then I can use myParameter
in configuration file, and the framework somehow knows how to configure my appender with it.
问题:log4cxx是否具有类似的功能?对我来说,只要获得具有属性的地图map<string, string>
就足够了.
Question: does log4cxx have a similar capability? For me it is enough if I get a map map<string, string>
with properties.
推荐答案
好,我自己想出了答案.您需要重写成员函数setOption
.它将被调用多次:每个读取选项一次.然后,您将覆盖函数activateOptions
并在处理完所有选项后调用它.它可以用作触发器,以使用读取的参数初始化附加器.
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.
不如映射到getter/setter那样方便,但是它可以完成工作:
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);
}
};
这篇关于log4cxx-是否可以使用来自配置文件的自定义参数来配置自定义附加程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!