What is the best Design Pattern for Java Logger

Asked

Viewed 409 times

1

I would like to know which is the best choice to implement Java Loggers.

Currently I have used dependency inversion as the following example:

@Controller
@RequestMapping("/");
public class HomeController
{
    private final LoggerImpl logger;

    @Autowired
    public HomeController(LoggerImpl logger){
        this.logger = logger;
    }

    @GetMapping
    public ModelAndView home(){
        this.logger.log(new LogBean("Ação"));
        return new ModelAndView("index");
    }
}

Then follows the interface:

public interface Loggable
{
    void log(LogBean logBean);
}

And its implementation:

@Component
public class LoggerImpl implements Loggable
{
    private final LoggerRepository repository;

    @Autowired
    public LoggerImpl(LoggerRepository repository){
        this.repository = repository;
    }

    public void log(LogBean logBean){
        ...
        this.repository.save(logBean);
        ...
    }
}

The way it works, but... I find this model very repetitive. I wish someone could shed some light on what can be done or improved.

  • 1

    I have the impression that it is difficult to answer that question without incurring an opinion. But any solution that requires creating a member in a type to do something that’s not directly related to the type, I’m out, that’s a mistake. I know some people think differently. For me it’s insane to do more than your responsibility.

  • Thank you for the reply bigown, when to what you said occurs exactly with your statement that the question incurs opinion. And for noting that the model implemented is not according to my taste and ideology I came to try some opinion.

  • 1

    The log needs to be everywhere but it is orthogonal to your application. If you remove all the log it still works. Reading the logging source code shouldn’t be relevant to understanding the application, so the more transparent it is, the better. In short: don’t soil the constructors with logger injection, leave your log ignorant API. Get the logger of a static method, like log4j or SLF4J, sort of like this: private static final Logger logger = LoggerFactory.getLogger(MinhaClasse.class);

  • Hello Caffé, in case you suggest me a Loggerfactory?

  • 1

    Yes. But I wouldn’t implement Factory, nor the logger itself. I use log4j as a logger implementation and SLF4J to abstract it, so as to facilitate integration with the log issued by libraries or frameworks that use other log implementations (some frameworks use for example the native Java implementation).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.