0

I am very new in python. I am writing a daemon in python and in my daemon I have a logger class. Logger class is something I need to use all over my daemon. Now rather that making new instance of the class inside each of my classes or passing an object of the logger class, I want to implement a PHP like static class so that it will cache the database connection inside and I can call it from anywhere without instantiating, Like,

Logger::log('This is cool');

How can I do it in python?

Kamrul Khan
  • 2,940
  • 4
  • 24
  • 48
  • checkout: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python – Jason Hu May 12 '16 at 03:13
  • Have you looked into existing Python loggers (e.g. the `logging` module) and/or their implementation? That's probably a better approach for this particular problem to begin with. – deceze May 12 '16 at 03:25

1 Answers1

1

you may try logging module. logging.getLogger ensures

All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application.

For example, at anywhere, when you call logging.getLogger('the-logger-name') you always get the same object.

As you want to write your logs to a database, you need to implement your own handler, which connects to the database, and is hooked with the logger through logger.addHanlder.

When you implement the handler by deriving from logging.Handler, you don't have to override every method - checkout how BufferingHandler does in Python's handlers implementation.

Lei Shi
  • 657
  • 4
  • 8