Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Creating an application logger

 
Ranch Hand
Posts: 41
Python Angular Framework Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have built a Java Spring Boot application, and I am using "log4j" for logging,
And in order to use the logger class, I do this:


But I think this is a mistake because I better encapsulate away all the "log4j" stuff inside a logger class and inject that class to other classes.

For example, I need to be able to do this:



This logger should print the "ExampleController" class name on the logs.

How can I implement the "AppLogger" so that it gets the correct class name without having to pass it through the constructor?
 
Redan Hassoun
Ranch Hand
Posts: 41
Python Angular Framework Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Found a solution in this article:
https://dzone.com/articles/logger-injection-with-springs-injectionpoint
 
Bartender
Posts: 1944
13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may want to try org.slf4j.Logger and org.slf4j.LoggerFactory.
The code should be:
 
Redan Hassoun
Ranch Hand
Posts: 41
Python Angular Framework Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Himai Minh wrote:You may want to try org.slf4j.Logger and org.slf4j.LoggerFactory.
The code should be:


I am already using log4j, but I prefer injecting it instead of creating it manually.
One of the reasons is unit/integration testing, if I want to test my code, I want to be able to inject a mock logger instead of writing real logs.
 
Marshal
Posts: 3180
466
Android Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its easy to do with JakartaEE/MicroProfile using CDI - not sure how to do something similar with Spring.

 
Destroy anything that stands in your way. Except this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic