1

I have a simple if condition in which I use System.out.println. I would like to know how can I modify the code in order to replace this usage of a system.out by a logger ?

if(myVar.getDate().equals(20141127) && myVar.getNumber().equals(1)) {
                System.out.println("");
}

Any suggestions ?

Thanks

hacks4life
  • 691
  • 5
  • 16
  • 38

1 Answers1

3

You can use some logger utility to log the details.

Have a look at Apache Log4j

The logging is as simple as

log.debug("This is an debug message");

where log is an instance of logger

For sample code you can look into this tutorial

dasrohith
  • 533
  • 2
  • 8
  • 21
  • Should I create my logger outside of the `if` condition or inside ? – hacks4life Nov 27 '14 at 10:03
  • @hacks4life Could you please look into the tutorial I have mentioned. I have made an edit to the answer – dasrohith Nov 27 '14 at 10:05
  • Done. I do not get what's in the `getLogger()` method. What am I supposed to put inside ? My own class right ? – hacks4life Nov 27 '14 at 10:12
  • @hacks4life Yes, put your class name there. It means that the logger is specific for your class. – dasrohith Nov 27 '14 at 10:14
  • There is a simple & straightforward logger built-in (since Java 7): Assuming the Class you are logging from is named "LoggingExample", do this: `Logger logger = Logger.getLogger(LoggingExample.class.getSimpleName()); logger.log(Level.INFO, "Message to log");` You'll need the following imports (some IDEs can auto-import): `import java.util.logging.Level; import java.util.logging.Logger;` – Dut A. Dec 30 '20 at 20:11
  • Cannot resolve method 'debug' in 'Log4j' – Luis Alfredo Serrano Díaz Jan 30 '22 at 13:35
  • How to show message to user when there is an issue in log4j. – Gentleman Sep 16 '22 at 10:17