google / google/guice

Best Practice for Logger using Guice Injection

Open
#1,134 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
12.7k
Forks
1.7k
Avg merge
11m
Merged PRs (30d)
2

Description

I have read the guice documentation and its [recommendation](https://github.com/google/guice/wiki/Injections#static-injections) to avoid static injection.

However, usually Logger instances are initialized as static final - as it makes sense to retain them per class and references to the logger instances remain unchanged till end.

Is there an alternate mechanism if requestStaticInjection is not recommended?

```
public class Application {

@InjectLogger
private static Logger logger;

@Inject
private static Application application;

public static void main(String[] args) throws Exception {
Module loggingInjector = new AbstractModule() {
@Override
protected void configure() {
bindListener(Matchers.any(), new Log4JTypeListener());
requestStaticInjection(Application.class);
}
};
Injector injector = Guice.createInjector(loggingInjector);
logger.info("Succesfully initiallized Logger");
}
}
```
Initially I was getting null pointer exception for the logger instance since I have not assigned requestStaticInjection for the class. After adding this, logger instance is initialized properly. But I hope it is not good idea to keep requesting for all classes which uses

```
@InjectLogger
static Logger logger
```

What is the best practice for such Logging scenarios?

Contributor guide

Open the contributing guide

Research direction

Start with the Guice static-injection documentation linked in the issue and the Application.main example using requestStaticInjection. Determine what guidance should replace or clarify the static logger pattern, and consider whether the recommendation belongs in the documentation; done means the logging best practice and its limitations are clearly documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.