user41662
user41662

Reputation: 69

How to use Poco Logger

I am new to Poco, I saw following example in Poco online help:

int main(int argc, char** argv)
{
    AutoPtr<SimpleFileChannel> pChannel(new SimpleFileChannel);
    pChannel->setProperty("path", "sample.log");
    pChannel->setProperty("rotation", "2 K");
    Logger::root().setChannel(pChannel);
    Logger& logger = Logger::get("TestLogger"); // inherits root channel
    for (int i = 0; i < 100; ++i)
        logger.information("Testing SimpleFileChannel");
    return 0;
}

I tried to create a global logger which can be used in other functions and classes in my application as well (sample code is below). In the above example, logger is declared and initialized in main, I can't use it in myClass if I don't pass logger to myFun (I don't want passing logger as a argument, it looks awkward, as I will need to use logger throughout the application, in multiple files); I tried this way: put Logger& logger = Logger::get("TestLogger"); outside main(), as global variable, all the other parts in main remain the same, however this doesn't work, sample.log is not generated after I run the application. I can't do this way: just declare Logger& logger outside the function, then initialize it in main() because logger is a reference which must be initialized when declared. How to do it?

class myClass
{
public:
     myClass() { }
     ~myClass() { }
     myFun() { /*calling logger...*/ } 
};

int main(int argc, char** argv)
{
    AutoPtr<SimpleFileChannel> pChannel(new SimpleFileChannel);
    pChannel->setProperty("path", "sample.log");
    pChannel->setProperty("rotation", "2 K");
    Logger::root().setChannel(pChannel);
    Logger& logger = Logger::get("TestLogger"); // inherits root channel
    logger.information("starting up");

    myClass aClass;
    aClass.myFun();
    return 0;
}

Upvotes: 3

Views: 5821

Answers (1)

Christian Severin
Christian Severin

Reputation: 1831

Doesn't Logger::get() grant access to a global pool of Logger objects, as a singleton?

What happens if you run your code snippet above, i.e. when you initialize your logger in main() and reference it in myClass::myFun() via Logger::get( "TestLogger" )? That should work just fine.

Of course you don't have access to main()s Logger&reference in myClass::myFun(), but you should be able to reach it through Logger::get().

Upvotes: 2

Related Questions