Best way to set a channel for a logger in a class in C++

Viewed 84

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);
1 Answers

What do you think this line is supposed to do:

Poco::Logger& GenericSensor::logger.setChannel(packetChannel);

It's neither a variable declaration nor a function declaration (no datatype on the parameter passed).

Edits after the discussion with the OP. He's trying to execute code, but you can't do that this way. This is bad code.

What he needs to do is create a static method that executes this code (without the weird non-variable declaration part) and call it from the constructor. The static method should keep track of whether it's already been done and only do it if necessary.

Related