Monday, August 27, 2012

Java: Logging in single line for grep

Have you ever tried to grep a java application log? So what do you think about multiline log entries? Yes it's painful.

Here I'll show you my logback configuration useful to avoid this problem and grep the log easily.


    
        
            %-30(%d [%thread]) %-5level %logger{16} - %replace(%msg){'\n','|'} %xEx%n
        
    

    
        
    

    


The class below produces logs like this. Too bad that even if you try to log in single line the Exception stack trace adding '%replace' in %xEx, it works only for the first stack trace line, if you have a solution please tell me.
package com.googlecode.log.pretty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {
 private static final Logger log = LoggerFactory.getLogger(App.class);
 
 public static void main(String[] args) {
  log.info("Hello World!");
  String message = "I'm a message\nI m a new line\n\tI'm a tabbed new line";
  log.trace(message);
  log.debug(message);
  log.info(message);
  log.warn(message);
  log.error(message);
  log.error("I'm an error", new Exception("To see stackTrace"));
  
 }
}
2012-08-18 16:48:25,156 [main] INFO  c.g.l.pretty.App - Hello World! 
2012-08-18 16:48:25,159 [main] TRACE c.g.l.pretty.App - I'm a message|I m a new line| I'm a tabbed new line 
2012-08-18 16:48:25,159 [main] DEBUG c.g.l.pretty.App - I'm a message|I m a new line| I'm a tabbed new line 
2012-08-18 16:48:25,159 [main] INFO  c.g.l.pretty.App - I'm a message|I m a new line| I'm a tabbed new line 
2012-08-18 16:48:25,159 [main] WARN  c.g.l.pretty.App - I'm a message|I m a new line| I'm a tabbed new line 
2012-08-18 16:48:25,159 [main] ERROR c.g.l.pretty.App - I'm a message|I m a new line| I'm a tabbed new line 
2012-08-18 16:48:25,162 [main] ERROR c.g.l.pretty.App - I'm an error java.lang.Exception: Oh mi grep styackTrace
 at com.googlecode.log.pretty.App.main(App.java:21) [classes/:na]
How to grep and print the original message
cat output.log | grep -E 'INFO|WARN|ERROR' | tr "|" "\n"

4 comments:

  1. Did you ever figure out a solution to logging stack traces on a single line?

    ReplyDelete
  2. Unfortunately I don't know any working solution on logback, I don't know if you can do it using another framework.

    ReplyDelete
  3. A solution is explained here: http://stackoverflow.com/questions/23067209/logback-controlling-the-formatting-of-exception-stacktraces

    %date [%level][%logger{1}][%thread{1}]
    %message%replace(%xException){"\n", "\\n"}%nopex%n

    ReplyDelete
    Replies
    1. replace is not solution.
      multi line stack trace need apply.

      Delete