I am developing a C++ class that uses the Poco library in order to log some messages.
I have split the class in 2 files MyClass.h (for declaration) and MyClass.cpp (for definition).
This is the .h file content:
#include "MyClass.h"
class MyClass {
protected:
static Poco::AutoPtr<Poco::ConsoleChannel> packetChannel;
static Poco::Logger& logger;
}
I have made the logger and the channel static to make them common for all objects.
And this is the .cpp file content:
Poco::AutoPtr<Poco::ConsoleChannel> GenericSensor::packetChannel = new Poco::ConsoleChannel;
Poco::Logger& GenericSensor::logger = Poco::Logger::get("SensorsChannel");
Poco::Logger& GenericSensor::logger.setChannel(packetChannel);
The first 2 lines are ok. But the third line is generating an error,
saying: expected a ';'
I know that the error is most probably because in the .cpp file we can have only definitions.
And I know that I can set the logger's channel in the constructor, but in that way, it will be set each time I have a new object of type MyClass.
Is there a method to set it just one time?
Edit 1: I have one suggestion.
I propose to define a new method in the .cpp file. It takes the channel as a parameter, initializes a new logger, then sets the channel to the new logger, and finally, it returns the new logger. As follows:
Poco::Logger& getLoggerWithAChannel(Poco::AutoPtr<Poco::ConsoleChannel> channelToSet) {
Poco::Logger& logger = Poco::Logger::get("SensorsChannel");
logger.setChannel(channelToSet);
return logger;
}
And then we can define the channel, the logger, and set the logger's channel in 2 lines as follows:
Poco::AutoPtr<Poco::ConsoleChannel> MyClass::packetChannel = new ConsoleChannel;
Logger& MyClass::logger = getLoggerWithAChannel(packetChannel);