RyanCheu
RyanCheu

Reputation: 3552

Log in Java with variable name?

In a previous job, I was working in C++, and the company internal library had a logging macro where I could simply write LOG(somevariable), and it would output to standard out:

"variablename: variablevalue"

Does anyone know if there's a way to do this in Java?

I never thought to look at their code so I don't know how it was done. It was really useful though!

Upvotes: 5

Views: 14664

Answers (4)

Simon
Simon

Reputation: 9365

If you use Eclipse you can use the "Watch Expression"-View to watch not only variables but also Method calls. See this.

If you just want to print a variable's value, you can use an Eclipse Template. Go to Windows->Preferences and look for the entry Java->Editor->Templates. Add a new template and call it for example "printvar". Add the following to the templates body:

System.out.println("${variable} = "+ ${variable});

Typing printvar during coding and then pressing CTRL+Space will generate the entered code using ${variable} as placeholder for the variable name. You will have to type the variable name only once, which saves time and typing.

BTW: The reason why you can create macros permitting syntactic sugar like LOG(variable_name) in C++, is beacuse C++ has a preprocessor: Java has none. There are implementations for Java preprocessors, but I think using one would be too much effort for such a simple problem like printing a variable's name followed by its value.

Upvotes: 2

jco.owens
jco.owens

Reputation: 535

You don't have MACRO's in java, but you could do something like this with a static method on some class.. does not have the variable name but does have the class type.

class DebugUtil
{
  public void static LOG(Object obj)
  {
    LOG(System.out, obj.getClass().getName(), obj);
  }

  public void static LOG(String name, Object obj)
  {
    LOG(System.out, name, obj);
  }

  public void static LOG(PrintStream ps, String name, Object obj)
  {
    ps.println(name + ":" + obj);
  }
}

then for usage

String foo = "bar";
Debug.Util.LOG(foo);
Debug.Util.LOG("foo", foo);

Upvotes: 0

bmargulies
bmargulies

Reputation: 100196

The typical technique is to use log4j, or logback, or something. Perhaps as mediated by slf4j. This required, typically, a static variable per class, which in turn causes the log messages to tell you where they are coming from.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533930

If you type soutv + TAB on Intellij and Netbeans it will give you a list of variables you might want to print.

enter image description here

I copied this and changed it to use the logger instead with logv + TAB

enter image description here

Upvotes: 2

Related Questions