idiotprogrammer
idiotprogrammer

Reputation: 146

Java modifying console outputs for debugging

I've lately been overwhelmed by a large amount of messages being printed out to my console and not knowing where they are coming from.

is there any way to easily make a custom class similar to system.out.println that will print out a custom message along with

Upvotes: 0

Views: 61

Answers (3)

mushfek0001
mushfek0001

Reputation: 3935

Is there any way to easily make a custom class similar to system.out.println that will print out a custom message along with

print the location of code the message is coming from
be toggleable by importance level
not be a pain to use
other helpful stuff?

You basically just described the usefulness of a logger. Java has pretty good logging frameworks like log4j, logback etc. Go with any one of those with a facade like sl4j. Using sl4j logging is as easy as System.out.println().

Just create a logger instance

private static final Logger log = LoggerFactory.getLogger(YourClassName.class);

And then print log like this

log.debug("Some log");

You can also write parameterized log messages with different levels (levels are used to denote importance level)

log.debug("Username={}", username);
log.trace("Username={}", username);
log.warn("Username={}", username);

This might be a good place to get started http://www.javacodegeeks.com/2012/04/using-slf4j-with-logback-tutorial.html

Upvotes: 1

Ruddy Garcia
Ruddy Garcia

Reputation: 1

maybe you can use a OuputStream where you customize the output in the console

Upvotes: 0

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

Apache, does provide a logging class, along with its different levels. when using these you can actually specify the level you need to be printed and it would also help you identify the location from where it got invoked.

take the below line for example,

[2015-03-31 12:51:29,426] DEBUG {org.springframework.beans.factory.support.DefaultListableBeanFactory} - Retrieved dependent beans for bean '(inner bean)#1b534211#2': [org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0] {org.springframework.beans.factory.support.DefaultListableBeanFactory}

It says, it got logged on 31st march at 12:51 hrs. The logger was used to debug some logic and it was invoked from org.springframework.beans.factory.support.DefaultListableBeanFactory class.

Upvotes: 1

Related Questions