0

I wrote a python module in c++. All works fine but now I want to add logging. My logger class (3rd party) requires initializtion similar to:

int main()
{
    Logger logger("log.log");
    Logger::Register(&logger);

    DoSomethingAndLog();
    return 0;
}

As you can see logger is created when the program is initialized and destructed when program is terminated.

Where would I create the Logger object so that it would be constructed upon module loading and destructed when the module is unloaded?

Xyand
  • 4,470
  • 4
  • 36
  • 63
  • What about obvious approach with global variables? Do they behave differently in python modules than in usual DLLs or EXEs? – Mikhail Aug 19 '12 at 16:08
  • @Mikhail, I guess it would work. I hope there is more elegant solution. If not, global it is. – Xyand Aug 19 '12 at 16:17
  • @DeadMG, http://docs.python.org/extending/extending.html – Xyand Aug 19 '12 at 17:18

1 Answers1

0

You can wrap the Logger object into a class and declare global instance of that class. This approach has a little advantage over the raw global Logger variable since you can control initialization and deinitialization in constructor and destructor. You can also restrict access to the Logger object.

class TheLogger
{
public:
  TheLogger() { Logger::Register(&_logger); }
  ~TheLogger() { Logger::Unregister(&_logger); }

  Logger& GetLogger() { return _logger; }

private:
  Logger _logger;
};

TheLogger theLogger;

int main()
{
  DoSomethingAndLog();

  theLogger.GetLogger().Log("...");

  return 0;
}
Mikhail
  • 20,685
  • 7
  • 70
  • 146
  • same problem here. Where do I construct and destroy `theLogger`? A singleton pattern could server though. However, `DoSomethingAndLog` uses `Logger` as is. And I wouldn't want to change this code (lots of it) – Xyand Aug 19 '12 at 17:38
  • `theLogger` is constructed automatically since it is a global variable definition. Almost the same as if it was declared locally in function. Constructor of `TheLogger` well be called at the moment module is loaded. The definition of the `Logger` doesn't change, and if your code use some other static methods of `Logger` nothing will change. – Mikhail Aug 19 '12 at 17:49
  • Thank you. The python interface actually provides a kind of initialization function where I could call `Register` . I am really trying to avoid the global definition and achieve better control the destruction. – Xyand Aug 19 '12 at 17:56