Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I've written a little command-line utility for filtering log files. It's like grep, except instead of operating on lines it operates on log4j-style messages, which may span multiple lines, with the first line always including the logging level (TRACE, DEBUG etc.)

Example usage on a file short.log with contents like this:

16:16:12 DEBUG - Something happened, here's a couple lines of info:
 debug line
 another debug line
16:16:14 - I'm being very verbose 'cause you've put me on TRACE
  trace info
16:16:15 TRACE - single line trace
16:16:16 DEBUG - single line debug

logrep -f short.log DEBUG produces

16:16:12 DEBUG - Something happened, here's a couple lines of info:
 debug line
 another debug line
16:16:16 DEBUG - single line debug

I think the main loop of the program could probably be simplified with some sort of parse and filter. Here it is:

  file = fileinput.input(options.file)
  try:
    line = file.next()
    while True:
      if any(s in line for s in loglevels):
        if filter in line:
          sys.stdout.write(line)
          line = file.next()
          while not any(s in line for s in loglevels):
            sys.stdout.write(line)
            line = file.next()
          continue
      line = file.next()
  except StopIteration:
    return
share|improve this question

closed as unclear what you're asking by Jamal Dec 16 '13 at 2:37

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

1  
Shouldn't you consider the log level only if it is at the beginning of the line? A line could contain info without being the first line of an info log. (Also you should log on a single line and use other separators if its spans on multiple "lines" but that is just my point of view because I handle huge quantities of logs) –  Josay Sep 24 '13 at 22:45
    
The level isn't at the beginning of the line, it's after a timestamp. I could parse it to ensure the level is where I expect it to be, but I'm trying to be robust to minor changes in logging format. –  MikeFHay Sep 24 '13 at 23:17

Browse other questions tagged or ask your own question.