Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×
Programming Bug Technology

Printf Debugging Revisited 59

gsasha writes "After long nights spent in debugging, w e have developed a C++ logging facility geared for debugging - and an article that describes our debugging methodology. The article consists of two parts: the first one describes the basics of the method, and the second one presents advanced techniques (to be completed if there is enough reader interest).
Happy debugging!"
This discussion has been archived. No new comments can be posted.

Printf Debugging Revisited

Comments Filter:
  • Looks primitive. (Score:2, Insightful)

    by Anonymous Coward

    First look at the code... looks rather primitive[0]. Guess I have to read the paper to figure out what's new here?

    Don't think I will.

    [0] Which isn't necessarily a bad thing, but you'd wonder why it's here to begin with.

    • You exactly missed the point. Everyone can write a logger, and ours is not an unusually smart one. The point is though, that *if you use loggers consistently, it'll be easy to debug*.
      But oh well, why did I expect a Slashdot reader to RTFA.
      • Look, friend - first you're responding to an Anonymous Coward. Expecting an AC to RTFA is wishful thinking.

        Second, he's right - your code is rather primitive, as you admit. Why not start with a much more advanced logging utility, and then speak about using the logging consistently?

        Third, if your whole point was about a methodology, then talk about the methodology. Reading your article, it doesn't read like that - it reads much more like a User's Manual for how to use your code.

        Fourth, what makes you t
        • Re:Looks primitive. (Score:2, Interesting)

          by gsasha ( 550394 )
          Ok then.

          First: my fault ;)

          Second: because you don't need a much more advanced logging facility for the intended use.

          Fourth: Whoa! That's easy: #define LOG(x) if (false) os. But actually, yes, I do ask people to not throw logging out once it's there. The reason it's not expensive when not used is that the branches in the "if(is_active())" do not change throughout the program, and thus are predicted very well and cost very little. I actually did measurements about the overhead of the mechanism and found

          • First: fair enough. =)

            Second: I would actually argue that your code is far more complicated than it needs to be, for the intended use.

            Third: Apparently there is no third. =)

            Fourth: Sure, I could change your code to make it go away, but I think it would be much better if your code had its own mechanism for going away. I would tend to agree that anything inside "if (false)" should mostly compile away - so that's fair. I'd like to see a "#ifdef DEBUG" or somesuch in your code for that case.

            Fifth: It's
            • Second: The complexity sits where it is actually necessary - you need powerful control of what and when is printed (see below). The critical path of the code, the printing itself, is quite straightforward.

              Fourth: Well, I could add some "#ifdef LOG_DISABLE". On the second thought, I'll do exactly that.

              Your new point: you are close. Yes, it would be prohibitive, both space-wise and performance-wise, to print everything (in the case I describe, it can easily be 100K per cycle at maximal output).

              But the p

  • by Anonymous Coward

    What's wrong with a simple link to the article? It already contains download links and links to the authors' websites. Splitting words up into multiple links isn't just annoying, but confuses people who use screen readers and Google. Editors, it's your job to massage submissions into a decent format.

    • That's assuming the editors are paying attention. Given dupes and the horrid IT color scheme (with LOTS of complaints and no action taken), it's likely they are not. I'll consider getting a subscription IF these types of issues are resolved. Until then, why bother?
  • Some comments (Score:5, Insightful)

    by Cthefuture ( 665326 ) on Sunday September 26, 2004 @03:08PM (#10356187)
    I didn't read the paper, but I looked at the code (for me this is usually more telling).

    The first thing that jumps out at me is the coding style. Very junior programmer-ish. College student maybe? The style has that "everything crammed together" very diffcult to read feel. When I dug deeper I found the system to be over-designed and not well implemented.

    Nice try though, get some experience then try again.

    I've found that a simple C based logging facility is much more versatile. It can be used from C or C++ plus most programming languages and applications support calling external C libraries also.
    • The first thing that jumps out at me is the coding style. Very junior programmer-ish. College student maybe? The style has that "everything crammed together" very diffcult to read feel.

      The first thing that jumps out at me about your post is that you make snap judgements about people's experience and background based on how much whitespace they use. Very junior programmer-ish of you. Are you a college student, maybe?
      • Re:Some comments (Score:4, Insightful)

        by Brandybuck ( 704397 ) on Sunday September 26, 2004 @04:45PM (#10356737) Homepage Journal
        Actually my experience is that you can tell how junior a programmer is by their style. While their styles will vary greatly, old timers will almost uniformly prefer an easy-for-others-to-read style. There are of course exceptions. Some junior programmers have been exposed to professors/managers/reviewers who won't accept unreadable code, and some senior programmers got tagged as "heroes" and have never had to maintain someone elses code.
        • I don't know about this. I am probably an intermediate C+ programmer at best, programming for about 2 years now. From the start, I made sure to define a style and keep it. At first, I did have some trouble trying to remember all my style rules, but now I make very few style mistakes. However, I also have never attended a programming class and have learned from books and guides.
          • by SamBeckett ( 96685 ) on Sunday September 26, 2004 @06:27PM (#10357252)
            Can you please point me to a good C+ compiler... gcc keeps complaining about my .cp files.
          • But it is a good standard? In particular, in order of importance, is the A) the standard everyone else on the project uses, and B) a common standard used by other successfull projects?

            I have my own personal preferred coding standard. It is fairly close to B, but it fails in A at work. I get into a lot of trouble over this, and I'm wrong. Even though if I showed both (the company and my) standards to the world most programmers are likely to prefer mine (just a guess, but based on various style guides)

        • Re:Some comments (Score:3, Interesting)

          by jeif1k ( 809151 )
          While their styles will vary greatly, old timers will almost uniformly prefer an easy-for-others-to-read style.

          Easy-to-read for whom? Easy to read for an absolute beginner? Easy to read for an expert programmer?

          There is no style that works for every reader--a style that makes code easy to read for beginners can obscure patterns and shorthands that make code easy to read for expert programmers.
        • Sadly, the "experience yields more readable" code idea is not generally true.

          The most experienced (in terms of years of experience: more than 20 to be precise) (ex-)coder on my current project prefers an absolutely horrible coding style if you let him do as he pleases. Utterly unreadable for anyone but him (endless lines that wrap on even the widest of screens; NO blank lines; the weirdest indentation convention I ever saw; countless "this was/is experimental or old code" sections that have been commented

          • Was he one of the exceptions I mentioned? No rule of thumb is ever 100% accurate, but my personal experience tells me that the more experienced the coder the more likely it is that their code will be readable. This is experience in coding, not mere longevity. My boss who was coding twenty years ago but hasn't coded in the last fifteen doesn't count.
            • Of course he may be one of the exceptions. All I wanted to say is that I've seen from personal experience that experienced coders can do things so horrible that one wouldn't believe them possible. This guy did spend all those years coding, by the way.
        • For those of us just setting out to get that experience, is there a style guide of some good starting points to follow? Also, can you point me towards some good code that I can try to learn from? I've found that identifying hard to read code is easy, but figuring out how to correct it is hard.
    • Re:Some comments (Score:3, Interesting)

      If you look at the links, you can see they are both PhD students in the Technion institute of technology.
      It's actually pretty strange the coding style is like this, specifically the hard coded functions like get_enabled1 or set_red instead of variables and constants like get_enabled(unsigned num) and set_color(Logger::color col).
      I'm particularly surprised because I study in the same institute and faculty as they do and the programming courses we have are pretty demanding and specifically point to code reusa
      • Re:Some comments (Score:1, Interesting)

        by Anonymous Coward
        The manipulators are particularly awful. They're a bunch of little functions that are copy/pasted just to change a string literal. Some of them don't even change the literal!

        std::ostream& set_dark_white(std::ostream& os)
        {
        if (!LoggerConfig::is_nocolor()) {
        const char* buf = "\x1b[0;37;40m";
        os.write(buf, strlen(buf));
        }
        return os;
        }
        std::ostream& set_gray(std::ostream& os)
        {
        if (!LoggerConfig::is_nocolor()) {
        const char* buf = "\x1b[0;37;40m";
        os.write(buf, strlen(buf
        • moreover, why double not?
          as in !LoggerConfig::is_nocolor()... it's much clearer to have it LoggerConfig::isColor().
          Another thing:
          won't it work just to do
          os "\x1b[0;37;40m";
          instead of those 2 lines?
          I might be wrong here, if someone can correct me.
          • He needs the length of the buffer to pass the size to the .write() method. By calling strlen() he avoids the problem created by defining the literal in once place and the length of the literal in another.

            Now, why he didn't simply use the << operator on the literal string allowing the functionality of strlen() to be encapsulated by the routine that actually cares about the string's length is beyond me... :-) Oh, I bet that's exactly what you were trying to say but you didn't encode the < charact

    • Re:Some comments (Score:2, Interesting)

      by gsasha ( 550394 )
      Well, if you didn't RTFA, then you missed the point. The article is not about "oh, we wrote this wonderful logging mechanism". It's about the *methodology* of debugging almost exclusively by logging (as opposed to *sometimes* doing postmortem analysis by looking at the logs).
      It's about leaving the logging code inside and improving it, rather than throwing it out shortly after it's used.
    • Very junior programmer-ish

      Indeed. Without wishing to be derogatory, another thing that sucks of junior programmer is that the author considers this insignificant hack important enough to be worthy of being on slashdot. The delusions of grandeur go with the territory.

      Yes, it's mildly interesting but the fact that it badly reinvents a wheel already invented many times over makes it less so.
  • log4c++ (Score:3, Insightful)

    by Hard_Code ( 49548 ) on Sunday September 26, 2004 @03:14PM (#10356223)
    Hasn't this wheel already been invented many many times?

    How about Log4C++ [fsf.org], a port of the canonical Log4J logging package for Java.
    • > Hasn't this wheel already been invented many many times?

      No big deal, I write a new logger for every project I write, it's a simple 5 minute hack.
      • Re:log4c++ (Score:5, Interesting)

        by Mysteray ( 713473 ) on Sunday September 26, 2004 @07:24PM (#10357538)
        we have developed a C++ logging facility geared for debugging

        My first reaction to this was, who hasn't?

        I agree with some of the other posters that their code has some, well, "interesting" features. I have to say it never would have occurred to me to use strcmp on a compile-time constant in a member initialization.

        That they use, but don't derive from, std::ostream for this is another example. It's not exactly trivial to do so, but it's also hard to argue against not doing it for something like this without good reason. But since there's not a single comment in the source files except some revision control macros we're just left to wonder.

  • C++ makes it hard (Score:5, Interesting)

    by YGingras ( 605709 ) <ygingras@ygingras.net> on Sunday September 26, 2004 @03:34PM (#10356342) Homepage
    It's hard to do a good printing debugger in C++. The lack of introspection throws most of the work in the hands of the pre-processor/developper.

    When I learned Common Lisp, the first macro I did was for printing debugging. It reads the expresions it is debugging, prints it (and shortens it with "..." if needed), evaluates it, prints the results and returns the results.

    What a monster you might say. Lets fist see an example of it's use:
    CL-USER> (+ 16 34 (- 6 7 8) (/ (* 3 (expt 4 1/2)) 2 3))
    42.0
    CL-USER> (dbg (+ 16 34 (dbg (- 6 7 8)) (dbg (/ (* 3 (dbg (expt 4 (/ 1 2)))) 2 3))))
    (- 6 7 8): -9
    (EXPT 4 (/ 1 2)): 2.0
    (/ (* 3 (DBG (EXPT 4 (/ 1 2)))) 2 3): 1.0
    (+ 16 34 (DBG (- 6 7 [...] 4 (/ 1 2)))) 2 3))): 42.0
    42.0
    It's done like that (and it's actually readable when indented properly):
    (defmacro dbg (expr)
    `(let ((val ,expr)
    (repr (format nil "~A" ',expr)))
    (if (> (length repr) 50)
    (format t "~A [...] ~A: ~A~%"
    (subseq repr 0 20)
    (subseq repr (- (length repr) 20))
    val)
    (format t "~A: ~A~%" repr val))
    val))
    Most of the hard work is taken away by the ability of the program to read itself, by dynamic typing and by the notion that there are no statements, only expressions. That being said, I don't claim that you should never use C++, just that it lacks introspection and that it makes printing debuging a lot harder.
    • You might want to bind *print-length* and *print-level* fairly low when you're printing repr; that may eliminate some of the [...]s. For that matter, you may want to wrap that whole thing in a with-standard-io-syntax, in case some print variables happen to have funky values when it's called.

      Me, I tend to use (print `(foo before processing -> ,foo)) instead, but everybody's got their own style.

  • by devphil ( 51341 ) on Sunday September 26, 2004 @04:44PM (#10356734) Homepage


    why not a link to a more professional and better-designed debugging library [sourceforge.net] instead? The author has made insane efforts to handle all kinds of error conditions which it looks like these kids haven't even thought of.

  • This is a pretty standard technique, which has been used by all sorts of software sytems for decades now.
  • Here we have it folks, a hardcore stand-up programming topic and only 19 comments. Is Slashdot overwhelmingly populated with posers?

  • by pyrrhonist ( 701154 ) on Sunday September 26, 2004 @08:51PM (#10358301)
    Don't reinvent the wheel. These facilities already handle logging better:
  • by museumpeace ( 735109 ) on Sunday September 26, 2004 @10:56PM (#10359281) Journal
    Virtually every project of 10 or more engineers that I have been on in my 30 years of software dev has cooked up its own logging facility. You are on the back of a very crowded bus here. Depending on whether memory, disk i/o resources or realtime and multithread requirements reign in your application, rather different logging approaches are applicable. Being able to dump the Nth occurance is a nice feature but so many more are needed. THE BIGGEST DIFFERENCE I SEE between your logger kit and some I have used/written is that you published the code. A partial feature checklist I would be looking for:
    • []has both compile time and run time mechanism to set severity thresholds.
    • [] idenifies the process/thread from which the logging call is issued
    • [] can generate some kind of event ID so context can be deduced even when the same message occurs many times.
    • []timestamping: this can give you a poor man's perfmon with added programability.
    • [] supports detection of recursion by indenting printouts that are called as you go deeper on the stack
    • [] NOMENCLATURE REGULARITY: a syntax for timestamps, severity, function name from which print is called, etc so that you can automate [eg with AWK etc ] the sorting and dredging for clues in a long output run.
    • []when not in use, can be "turned off" with no compile or run time overhead but still present as comments.
    ...there are more, believe me.
  • by Anonymous Coward on Monday September 27, 2004 @01:23AM (#10360025)
    As many have said, this has been done before. One of their main macros isn't even correct. Ie.,

    #define LOG(logger) if ((logger).is_active()) (logger).os()

    This will break if one writes:

    if (value == 0)
    LOG(xxx) "hello" endl;
    else ...

    The "else" gets interpreted as being attached to the "if" inside the LOG macro when it shouldn't.

    It should be written as:

    #define LOG(logger) if (!(logger).is_active()) ; else (logger).os()

    For a much more expansive trace/log system see OSE at:

    http://ose.sourceforge.net

    and specifically

    http://ose.sourceforge.net/browse.php?group=librar y-manual&entry=logger.htm

    and

    http://ose.sourceforge.net/browse.php?group=librar y-manual&entry=tracer.htm

    The OSE library has had this stuff for over ten years now.
  • My own thoughts (Score:1, Informative)

    by Anonymous Coward
    As many other, I once wrote quite an extensive logging library.

    You can find it here along with an article I wrote what I though logging should support:

    http://www.bluefish.se/aquarium/lime.html
  • PURE EVIL (Score:5, Informative)

    by Viking Coder ( 102287 ) on Monday September 27, 2004 @11:26AM (#10362799)
    // Constructor:
    Logger(const Logger& enable2 = *(Logger*)0);


    (Trimmed to trick the lameness filter.)

    Pure. Evil.

    And don't go telling me "that's perfectly valid," cause you know what? I don't care if the C++ compiler accepts it, and I don't care if you do it in your code. That is just pure evil.
  • IMHO, a more general (and interesting) technique is meta-programming. You can automatically add code. See http://mozart-dev.sourceforge.net/pi-tracer.html [sourceforge.net] for an example.
    • That's interesting, but what does that do for exception handling? It seems to me that it could interfere with exceptions thrown deep in the code that are expected to be caught at a level much farther up?

      I'm not a Java guy, so maybe I'm not catching all the nuances of the try/finally construct. It just looks like it could cause unwanted behavior.

Our business in life is not to succeed but to continue to fail in high spirits. -- Robert Louis Stevenson

Working...