debugging - Equivalent of a debug macro in Java -


this question has answer here:

i'm writing program reads structures file. debugging purposes, convenient if have compile-time toggle prints names , values of read disabled better performance/code size in production version. in c, use preprocessor such accomplish this:

#ifdef debug   #define read(name, in) { name = read(in); printf("#name: %d\n", name); } #else   #define read(name, in) { name = read(in); } #endif  void myreader(mystream_t *in) {     int a, b, c;      read(a, in);     read(b, in);     read(c, in); } 

is there way can reproduce construct? thought this:

private static final boolean debug_enabled = true;  private int debugread(myinputstream in, string name) {     int val = in.read();      if (debug_enabled) {         system.out.println(string.format("%s: %d", name, val));     }     return val; }  public myreader(myinputstream in) {     int a, b, c;      = debugread(in, "a");     b = debugread(in, "b");     c = debugread(in, "c"); } 

however, requires me type name of variables twice storing strings corresponding names on release version. there better approach this?

edit: biggest concern have code verbosity. last thing want have code cluttered debug/print/trace statements obscure actual reading logic.

i'm not sure if apples apples solution, 1 thing that's idiomatic in java use logging framework. it, can execute log.debug wherever might need debugging. slf4j common facade logging frameworks. use jul logging.

usually leave logging code there , configure logger externally either print or not print messages.

if you're using slf4j, debug message this:

log.debug("setting creation timestamp {}", timestamp); 

most loggers can configured tell time, class , method logging message came from.

this has pros , cons compared you're used to.

cons

  • i have admit, take lot of effort learn when want right system.out.println.
    • most of loggers configured on classpath. classpath non-trivial part of java learn will have learn anyway. it's important understand.
  • it won't automatically print out name of variable passed in. afaik, you'll have write detail yourself

pros

  • using logger robust. can leave code there production , dev mode , configure verbosity appropriately
  • it can automatically print out context of class/method , date of message , other things that
  • you can configure output in lots of different ways. example, "output console and log.txt when file becomes > 100mb, rollover old data log2.txt , keep @ 5 log files."

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -