Page 1 of 1

Using Logger in C++ class

Posted: 30 Sep 2012, 17:46
by jshanab
I am just getting started using Poco on a project. They used it a lot at my previous job (Schneider Electric)
The performance recommendation is to cache the reference and reuse it, but I am not sure how to do that when it returns a ref and not a pointer.
My normal mode would be to declare a boost::shared_ptr<logger> in the class members and then assign it in the ctor. So How do I use a reference in a c++ class without calling getLogger over and over again?

Get it in main and pass it into the CTOR?

PS why is the example for a C++ class a C-like example.

Re: Using Logger in C++ class

Posted: 30 Sep 2012, 23:09
by rakesh
Why not declare a static Logger reference in your class and initialise it like any other static instance?

In your header: static Logger& logger;
In your implementation: Logger& MyClass::logger = Logger::get( "MyClassLogger" );

Re: Using Logger in C++ class

Posted: 01 Oct 2012, 00:06
by jshanab
That will work fine.
In the mean time i have used log4cplus that I already had built for another project. I liek the configuration file and the act that it can react to changes in that file. Does the poco logger class have that kind of functionality ? ie I can change the loglevel of classes and redirect the logs without shutting down my app

Re: Using Logger in C++ class

Posted: 01 Oct 2012, 01:29
by guenter
You can also have a non-static reference to your class's Logger:

Code: Select all

class MyClass
        // ...

    // ...

    Poco::Logger& _logger;

You can change the log level of an existing logger with setLevel(). There are two variants of this method - one that works on the instance level (_logger.setLevel(Poco::Message::PRIO_INFORMATION)) and a static one that works on a complete hierarchy, e.g. setLogger("MyLogger", Poco::Message::PRIO_INFORMATION).
This is multithreading-safe. You could also change the channel assigned to a logger with setChannel(), but this is not multithreading-safe and not recommended.