• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Creating an application logger

 
Ranch Hand
Posts: 41
Python Angular Framework Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Found a solution in this article:
https://dzone.com/articles/logger-injection-with-springs-injectionpoint
 
Bartender
Posts: 2264
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 4081
554
Android Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Its easy to do with JakartaEE/MicroProfile using CDI - not sure how to do something similar with Spring.

 
reply
    Bookmark Topic Watch Topic
  • New Topic