python-injector / python-injector/injector
Injecting named logger objects
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.5k
- Forks
- 94
- PR merge metrics
- No merged PRs in 30d
Description
In an attempt to abstract away the concrete logger implementation, I'd like to inject logger objects into my classes. However, I would also like the name of the injected logger objects to correspond to the module name in which the class with the @inject attribute is located.
Example (foo.py):
class Bar:
@inject
__init__(self, logger: AbstractLogger)
assert logger.name == "foo"
I have managed to put together a super hacky @provider that accomplishes this like so:
@provider
def get_logger(self) -> AbstractLogger:
calling_frame = inspect.currentframe().f_back
module = calling_frame.f_locals['self']._stack[0][0].__module__
return ConcreteLogger(module)
Clearly, this is a very brittle approach as it depends on certain internals of the injector framework being stable. It's also very obscure.
It would be nice if the provider had access to an InjectionContext of some sort that would contain information about the class for which the logger object is being created. Then I could write my provider like this (as an example):
@provider
def get_logger(self, ctx: InjectionContext) -> AbstractLogger:
module = ctx.requesting_class.__module__
return ConcreteLogger(module)
Would something like that be possible? I know Guice will automatically inject named loggers but I would prefer to control the type of the injected object, without having to resort to something like logging.setLoggerClass(MyLogger) as that will affect 3rd party code as well.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the @inject and @provider entry points to understand how provider arguments and requesting classes are currently resolved. Define what an InjectionContext should expose, then verify that a provider can use the requesting class to create a logger named for its module; no specific source files or tests are identified in the issue.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100