How do I create a custom Layout for log4cplus - c++

After searching for what feels far too long, I decided to ask this simple question on stackoverflow:
How do I create a custom Layout for log4cplus (1.1.2)?
The closest related question is How do I add a custom filter in log4cplus? where the author adds the new class directly into the log4cplus directory (or uses log4cplus namespace?). I do not have this option as the log4plus headers and libraries are installed independently (and simply setting the namespace to log4cplus does not work either.
What I tried is a minimal example inheriting from log4cplus::PatternLayout:
namespace myNameSpace {
class LOG4CPLUS_EXPORT MyPatternLayout: public ::log4cplus::PatternLayout {
public:
MyPatternLayout(const log4cplus::tstring& pattern);
MyPatternLayout(const log4cplus::helpers::Properties& properties);
~MyPatternLayout();
private:
// Disallow copying of instances of this class
MyPatternLayout(const MyPatternLayout&);
MyPatternLayout& operator=(const MyPatternLayout&);
};
}
I expect that LOG4CPLUS_EXPORT takes care of registering my class to the log4cplus framework so I can use it in the configuration file. However, adding
log4cplus.appender.STDOUT.layout=myNameSpace::MyPatternLayout
results in an error:
log4cplus:ERROR Cannot find LayoutFactory: "myNameSpace::MyPatternLayout"
So how do I register a custom Layout/Appender?

After trying many things, it boils down to one simple entry that has to be put after log4cplus::initialize(); and before log4cplus::PropertyConfigurator::doConfigure("<path to config file");.
If you want to add the new Layout in the log4cplus namespace you can simply
//example1
log4cplus::initialize();
// register our stuff
log4cplus::spi::LayoutFactoryRegistry& reg = log4cplus::spi::getLayoutFactoryRegistry();
LOG4CPLUS_REG_LAYOUT(reg, MyPatternLayout);
log4cplus::PropertyConfigurator::doConfigure(Logger::mConfigFile);
or, if you want to use your own namespace
//example2
log4cplus::initialize();
// register our stuff
log4cplus::spi::LayoutFactoryRegistry& reg = log4cplus::spi::getLayoutFactoryRegistry();
LOG4CPLUS_REG_PRODUCT (reg, "myNamespace::", MyPatternLayout, myNamespace::, log4cplus::spi::LayoutFactory);
log4cplus::PropertyConfigurator::doConfigure(Logger::mConfigFile);
You can then use the layout in the config as
log4cplus.appender.STDOUT.layout = log4cplus::MyPatternLayout #example 1
or
log4cplus.appender.STDOUT.layout = myNamespace::MyPatternLayout #example 2
Simple enough, right? I wish the log4cplus had a documentation closer to the .log4j one

Related

load config file for game, singleton or passing down the tree or anything else?

I'm trying to create simple game in C++. At one point I want to have some setting, save and load from config file.
The config file should be read from the beginning, and should be accessible anywhere it needed.
So far I only see Singleton pattern as a solution.
Another way is to create an object an pass it down, but it can mess
up the current code.
I've also search and found something called Dependency Injection.
Is dependency injection useful in C++
Which design patterns can be applied to the configuration settings problem?
But I don't quite understand it, you still have to create an object in main and pass it down, right?
Singleton is quite simple, but some consider it antipattern, while pass it down the tree can mess up my current code. Is there any other Patterns?
P/S: I'm also curious how games load their setting.
I would suggest something simple as the following example, which circumvents any singleton-related or initialization order issue:
struct global_state
{
config _config;
};
struct game_state
{
global_state& _global_state;
};
int main()
{
global_state globals{load_config_from_file()};
game_state game{globals};
game.run();
}
Since _global_state is a member of game_state, it can be used in member functions without the need of explicitly passing it as a parameter:
void game_state::update_ui()
{
const float text_size = _global_state._config.get_float("text_size");
_some_text.set_size(text_size);
}

Can't use MFC CObject class in VS 2017 application

I need to use MFC Serialization mechanism to serialize objects of class Product:
class Product : public CObject
{
protected:
string name;
int expiring;
double price;
public:
Product();
~Product();
virtual void input_data();
virtual void print_data();
};
This is simple Windows Console Application. I got an error on CObject: not a class or struct name.
I tried to make MFC Console Application following the instruction in this comment: https://stackoverflow.com/a/50320168/6543699. Now I got a lot of errors (identifier not found or identifier not declared). The text of errors is in Russian, so I don't copy them here. This is how it looks:
I don't know anything about MFC using and can't find guide where it described clearly. My questions are:
1) Is it possible to use CObject in console application (non-MFC) and how?
2) If not, what should I do to be able to use MFC serialazation? Maybe include some headers or some components were just missing while installation?
You can just adjust a console app in a couple of steps to use MFC. First is to include afx.h, like:
#include <iostream>
#include <afx.h>
Then you will want to link with the MFC dynamic libraries.
Project Properties > Configuration Properties > Advanced > Use MFC
Select: Use MFC in a Shared DLL
It should now compile with CObject.
My note, I would not use MFC serialization, at the least use Boost Serialization I gave up using any serialization a long time ago because of the constant need to maintain versioning. I found it a night mare. Unless you see that your object structure will remain fairly static, I would recommend using XML to database your objects. It is a little more work to get going but way more often than not, you don't need to worry about versioning as you make changes.

Dynamically create the structure and variables of a class based on user input in c++

I'm new to the site (and to c++) so please forgive me if this is a basic question - I've googled and looked through this site without success so far, so any help anyone can provide would be hugely appreciated.
I'd like to add some functionality to an app, that allows a user to fully define the structure and contents of an object. For example, user would be presented with a configuration screen that allows them to list each property of the object - given my limited knowledge I've assumed this might be achieved by using a class:
Class Name: CustomClassName
Class Property 1: property1Name property1DataType property1DefaultValue
...
Class Property n: propertynName propertynDataType propertynDefaultValue
The user would then be able to hit a button to save their custom configuration, and the program could then reference that configuration as a Class:
class CustomClassName
{
property1DataType property1Name = property1DefaultValue;
...
propertynDataType propertynName = propertynDefaultValue;
}
I'm not even sure this is possible using Classes, so if there's another mechanism that facilitates this I'm open to suggestions!
You can't create classes in runtime, but since dynamic typing is in essence a subset of static typing, you can fake it.
Start with the Property type1:
using Property = variant<int, float, string>;
A simple "dynamic" class could look like this:
class DynamicClass {
std::map<std::string, Property> properties;
public:
Property const& operator[](std::string const&) const
Property operator[](std::string const&);
};
Use:
DynamicClass d;
d["myInt"] = 5;
1 Example implementation. Internals of variant should be tailored for your specific purpose. If you need an open variant, where you don't know all of the possible types beforehand, this gets more complicated, calling for something like any.

loading classes with jodd and using them in drools

I am working on a system that uses drools to evaluate certain objects. However, these objects can be of classes that are loaded at runtime using jodd. I am able to load a file fine using the following function:
public static void loadClassFile(File file) {
try {
// use Jodd ClassLoaderUtil to load class into the current ClassLoader
ClassLoaderUtil.defineClass(getBytesFromFile(file));
} catch (IOException e) {
exceptionLog(LOG_ERROR, getInstance(), e);
}
}
Now lets say I have created a class called Tire and loaded it using the function above. Is there a way I can use the Tire class in my rule file:
rule "Tire Operational"
when
$t: Tire(pressure == 30)
then
end
Right now if i try to add this rule i get an error saying unable to resolve ObjectType Tire. My assumption would be that I would somehow need to import Tire in the rule, but I'm not really sure how to do that.
Haven't use Drools since version 3, but will try to help anyway. When you load class this way (dynamically, in the run-time, no matter if you use e.g. Class.forName() or Jodd), loaded class name is simply not available to be explicitly used in the code. I believe we can simplify your problem with the following sudo-code, where you first load a class and then try to use its name:
defineClass('Tire.class');
Tire tire = new Tire();
This obviously doesn't work since Tire type is not available at compile time: compiler does not know what type you gonna load during the execution.
What would work is to have Tire implementing some interface (e.g. VehiclePart). So then you could use the following sudo-code:
Class tireClass = defineClass('Tire.class');
VehiclePart tire = tireClass.newInstance();
System.out.println(tire.getPartName()); // prints 'tire' for example
Then maybe you can build your Drools rules over the interface VehiclePart and getPartName() property.
Addendum
Above make sense only when interface covers all the properties of dynamically loaded class. In most cases, this is not a valid solution: dynamically loaded classes simply do not share properties. So, here is another approach.
Instead of using explicit class loading, this problem can be solved by 'extending' the classloader class path. Be warn, this is a hack!
In Jodd, there is method: ClassLoaderUtil.addFileToClassPath() that can add a file or a path to the classloader in the runtime. So here are the steps that worked for me:
1) Put all dynamically created classes into some root folder, with the respect of their packages. For example, lets say we want to use a jodd.samples.TestBean class, that has two properties: number (int) and a value (string). We then need to put it this class into the root/jodd/samples folder.
2) After building all dynamic classes, extend the classloaders path:
ClassLoaderUtil.addFileToClassPath("root", ClassLoader.getSystemClassLoader());
3) load class and create it before creating KnowledgeBuilder:
Class testBeanClass = Class.forName("jodd.samples.TestBean");
Object testBean = testBeanClass.newInstance();
4) At this point you can use BeanUtils (from Jodd, for example:) to manipulate properties of the testBean instance
5) Create Drools stuff and add insert testBean into session:
knowledgeSession.insert(testBean);
6) Use it in rule file:
import jodd.samples.TestBean;
rule "xxx"
when
$t: TestBean(number == 173)
then
System.out.println("!!!");
end
This worked for me. Note that on step #2 you can try using different classloader, but you might need it to pass it to the KnowledgeBuilderFactory via KnowledgeBuilderConfiguration (i.e. PackageBuilderConfiguration).
Another solution
Another solution is to simply copy all object properties to a map, and deal with the map in the rules files. So you can use something like this at step #4:
Map map = new HashMap();
BeanTool.copy(testBean, map);
and later (step #5) add a map to Drools context instead of the bean instance. In this case it would be even better to use defineClass() method to explicitly define each class.

Managed C++ - Importing different DLLs based on configuration file

I am currently writing an application that will serve a similar purpose for multiple clients, but requires adaptations to how it will handle the data it is feed. In essence it will serve the same purpose, but hand out data totally differently.
So I decided to prodeed like this:
-Make common engine library that will hold the common functionalities of all ways and present the default interface ensuring that the different engines will respond the same way.
-Write a specific engine for each way of functioning....each one compiles into its own .dll.
So my project will end up with a bunch of libraries with some looking like this:
project_engine_base.dll
project_engine_way1.dll
project_engine_way2.dll
Now in the configuration file that we use for the user preferences there will an engine section so that we may decide which engine to use:
[ENGINE]
Way1
So somewhere in the code we will want to do:
If (this->M_ENGINE == "Way1")
//load dll for way1
Else If (this->M_ENGINE == "Way2")
//load dll for way2
Else
//no engines selected...tell user to modify settings and restart application
The question is...How will I import my dll(s) this way? Is it even possible? If not can I get some suggestions on how to achieve a similar way of functioning?
I am aware I could just import all of the dlls right at the start and just choose which engine to use, but the idea was that I didn't want to import too many engines for nothing and waste resources and we didn't want to have to ship all of those dlls to our customers. One customer will use one engine another will use a different one. Some of our customer will use more than one possibly hence the reason why I wanted to externalize this and allow our users to use a configuration file for engine switching.
Any ideas?
EDIT:
Just realized that even though each of my engine would present the same interface if they are loaded dynamically at runtime and not all referenced in the project, my project would not compile. So I don't have a choice but to include them all in my project don't I?
That also means they all have to be shipped to my customers. The settings in the configuration would only dictate with class I would use to initialize my engine member.
OR
I could have each of these engines be compiled to the same name. Only import one dll in my main project and that particular engine would be used all the time. That would render my customers unable to use our application for multiple clients of their own. Unless they were willing to manually switch dlls. Yuck
Any suggestions?
EDIT #2:
At this point seeing my options, I could also juste make one big dll containing the base engine as well as all the child ones and my configuration to let the user chose. Instead of referencing multiple dlls and shipping them all. Just have one huge one and ship/reference that one only. I am not too fond of this either as it means shipping one big dll to all of my customers instead of just one or two small ones that suit there needs. This is still the best solution that I've come up with though.
I am still looking for better suggestions or answers to my original question.
Thanks.
Use separate DLLs for each engine and use LoadLibrary in your main project to load the specific engine based on the configuration.
Have your engine interface in some common header file that all engines will derive from and this interface will be used in your main project aswell.
It might look like this:
// this should be an abstract class
class engine {
public:
virtual void func1() = 0;
virtual void func2() = 0;
...
};
In each different engine implementation export a function from the DLL, something like this:
// might aswell use auto_ptr here
engine* getEngine() { return new EngineImplementationNumberOne(); }
Now in your main project simply load the DLL you're interested in using LoadLibrary and then GetProcAddress the getEngine function.
string dllname;
if (this->M_ENGINE == "Way1")
dllname = "dllname1.dll";
else if (this->M_ENGINE == "Way2")
dllname = "dllname2.dll";
else
throw configuration_error();
HMODULE h = LoadLibraryA(dllname.c_str());
typedef engine* (*TCreateEngine)();
TCreateEngine func = (TCreateEngine)GetProcAddress(h, "getEngine");
engine* e = func();
The name of the exported function will probably get mangled, so you could either use DEF files or extern "C" in your DLLs, also don't forget to check for errors.
The solution I came to is the following:
Engine_Base^ engine_for_app;
Assembly^ SampleAssembly;
Type^ engineType;
if (this->M_ENGINE == "A")
{
SampleAssembly = Assembly::LoadFrom("path\\Engine_A.dll");
engineType = SampleAssembly->GetType("Engine_A");
engine_for_app = static_cast<Engine_Base^>(Activator::CreateInstance(engineType, param1, param2));
}
else
{
SampleAssembly = Assembly::LoadFrom("path\\Engine_B.dll");
engineType = SampleAssembly->GetType("Engine_B");
engine_for_app = static_cast<Engine_Base^>(Activator::CreateInstance(engineType, param1, param2, param3, param4));
}
I used the answer from Daniel and the comments that were made on his answer. After some extra research I came across the LoadFrom method.