Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Let's say we have a function like this:

public void myStart()
{
    for (int i = 0; i<10; i++) myFunction(i); 
}


private int myFunction(int a)
{

    a = foo(a);
    a = bar(a);
    return a; 
}

private int foo(int a)
{
    //do something here

    //something gnarly here

    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}

Now for whatever reason, our code isn't working. Perhaps it's throwing an error, perhaps it's returning the wrong value, perhaps it's got stuck in an infinite loop.

The first thing any first year programmer, is print to console/std out, (having learned how to print Hello World before learning to use a debugger).

For example to debug this code they might do the following:

private int myFunction(int a)
{
    print("before foo: a=" + a); 
    a = foo(a);
    print("before bar: a=" + a);
    a = bar(a);

    return a; 
}

private int foo(int a)
{
    //do something here
    print ("foo step1: a=" + a); 

    //something gnarly here
    print ("foo step2: a=" + a + " someOtherValue="+ someOtherValue + " array.length= " + someArray.length()); 
    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}

Now they run the code, they get a big console print out, which they can go through to trace where things are going wrong.

An alternative of course, is to set breakpoints and step through the code at each point.

One major advantage of printing to console, is that the developer can see the flow of the values in one go, without having to click through steps etc.

But the disadvantage is, your code is then riddled with all these print statements that then need to be removed.

(Is it possible perhaps to tell the debugger to print only certain values out to a log?, the breakpoints can then easily be added or removed without actually modifying the code.)

I do still use console printing as a primary debugging method, I'm wondering how common/effective this is in comparison to something else out there.

share|improve this question
1  
You need to learn how to use a debugger and use a proper logging framework. It will make you much happier than printing to the console (that doesn't always exist). –  MichaelT Jan 23 at 22:13
6  
It is important to learn to use debuggers, however, there are many situations you may encounter where printf debugging is the only debugging method available. –  whatsisname Jan 23 at 23:13

3 Answers 3

Print statements and debugger are not mutually exclusive. They are just different tools available to you in order to locate/identify bugs. There are those who will claim how they never touch a debugger and there are those who do not have a single logging/print statement anywhere in the code that they write. My advice is that you do not want to be in either one of those groups.

Instead learn to use logging and learn to use a debugger. With experience you will (almost without having to think about it) pick the right tool and get the job done accurately and efficiently. Without experience, sometimes you'll pick one over the other, and maybe it'll take you a bit longer poking around at the variables or sifting through log files, but that's all part of the learning process.

So, to answer your specific question. Yes. Using prints to trace execution is good and widely used debugging strategy. However...

Instead of using print statements, consider using a logging framework. Logging frameworks have a concept of logging levels so you can add a whole bunch of log messages but pick a level for each one. When your application is running under normal conditions, your level would be ERROR or WARNING so that only important stuff gets reported. However when you are tracing through the code and need to understand execution flow, you can change the logger to INFO or DEBUG and now all those "print" statements that you already have in the code will report additional info.

Using a logging framework...

  1. you won't need to delete all the prints after you are done.
  2. the prints you leave in the code, can help you or any other developer debug that same code in the future
  3. you'll be able to debug this code in the field without having to rebuild it every time just to add the prints that you deleted.
  4. you'll be able to redirect logging messages anywhere you want, not just a console. They could go to a file, syslog, DB, socket... etc

Update: I just noticed at the end you were asking, "Is it possible perhaps to tell the debugger to print only certain values out to a log". Depending on which debugger you use. Many modern debuggers allow you to define an action to invoke when a breakpoint is hit. In some (I've done this in VS and WinDbg), it is possible to specify "print this and resume". Visual Studio calls them "tracepoints" instead of "breakpoints"

share|improve this answer
    
+1 for the first paragraph. Debuggers and logs solve two very different problems. –  Blrfl Jan 23 at 23:09
1  
But don't you agree that leaving the log statements in the code uglys it up? –  dwjohnston Jan 24 at 0:15
1  
depends what kind of log statements you leave in place. I just found and removed this one: "logger.error("WHAT")". Otherwise, I treat logging code just like the rest of my code. Format it, make it look nice and make it informative. Yeah, sprinkling a print statement every other line is a bit too much and there were times I had to resort to that. But generally, having 10-20 log statements in the entire file (files/classes being reasonably sized and not gigantic) is not bad at all. –  DXM Jan 24 at 0:22
    
I get that leaving some log statements in might be useful, for example if you have a production system you might want to be logging various important variables as they're used so if some error does crop up you can see immediately what happened in your production environment. However, for the context of development it seems messy. For example, you're writing your parsing function, and you haven't quite got your regex right - so you put in a series of log statements just to check what's going on, and eventually sort it out. I don't think it adds value going forward to leave them in. –  dwjohnston Jan 24 at 0:27
1  
@Izkata: that would all depend on the specifics of your specific bug and on how much logging your code already does. Point I'm trying to get across is that there is always value of having logging statements and having them at different levels: ERR -> WARN ... -> DEBUG. If you need more for something very specific, sure by all means start adding print statements. But my answer to someone who uses "print" as a logging statement, will always be switch to a framework and start using that. –  DXM Jan 24 at 1:15

Loging/printing and debuggers are complementary techniques that have different strenghts and weaknesses - it's best to use both. But overall, I'd say that debuggers are the superior tool in most cases and should be used first, with logging/printing only used for the things it's actually better at.

Advantages of debuggers:

  • You can inspect the entire program state, not just the values you thought to print out in advance. This can massively speed up the debugging process by reducing the feedback cycle to less than a second. Especially important when it takes some time to reach the bug.
  • You can see where calls came from and even inspect values up the stack trace.
  • You can (to some degree that depends on the language/platfrom) debug code that you cannot easily modify because you only have the compiled binary or byte code.

Advantages of Logging/printing:

  • It doesn't require a special debug build or configuration. It always works.
  • Can be used to analyze errors that are hard to reproduce and occur rarely
  • Can be used to analyze timing-dependant errors where the pause caused by a debugger can easily make the bug disappear.
  • Gives you permanent information that you can analyze at your leisure. You can jump back and forth between output at different points in the program flow.
share|improve this answer
    
Another advantage of logging is when you only run into the problem on the umpteenth pass through your code and really could use some backtrace of how you got there. Most debuggers do not have a reverse button, but logging what the values a higher-level function was called with will work, and often at least get you closer to a small reproducible case. –  Christopher Creutzig Jan 25 at 23:59

Printing to standard output in a way can be a good strategy to debug your code, for instance

  • i use a lot of print statements to see what is going on in different levels of my code especially if i don't fully understand the error

  • or maybe the error does not have any detailed information that might point me to what part of the code exactly is causing the problem.

However you need to get used to debugging tools, there are lots out there depending on what language or platform you use.

Also another method is logging, i log errors all the time when working on Android applications, also with exception handling, one can easily log a stack trace or error message of the exception being raised.

share|improve this answer
3  
this post is rather hard to read (wall of text). Would you mind editing it into a better shape? –  gnat Jan 24 at 3:03
    
I made it a bit readable. Sorry for the previous! –  Plaix Jan 24 at 12:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.