Daniel Fortunov
Daniel Fortunov

Reputation: 44393

What is the idiomatic way to share a logger instance between modules in my Python script?

I have created my own simple logger class which uses COM interop to redirect to a company-standard logger. I would like to create logger instance near the beginning of my script and then use this logger to allow all modules in my script to log centrally.

Is there an idiomatic way to share this logger instance between all modules, without specifically adding a logger parameter to the constructor of every class that needs to log?

Should I use a global variable, or a singleton, or is there another recommended way to shar the logger between modules?

Upvotes: 6

Views: 3762

Answers (2)

Vinay Sajip
Vinay Sajip

Reputation: 99465

Why don't you use Python standard logging and write a handler to interface with your company-standard logging system? Python logging is specifically designed so you don't need to pass logger instances between layers of your code - Python loggers are essentially singletons already.

Handlers for stdlib logging are pretty easy to write, too - there are many examples of third party handlers.

Disclosure: I'm the maintainer of Python's standard library logging package.

Upvotes: 7

bluefoot
bluefoot

Reputation: 10580

I would use a module instead of a class, since a python module is already singleton.

Several approaches here.

Upvotes: 1

Related Questions