Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we remove extra message in log files

i have a simple logging program ie:

public class LoggingExample1 {
 public static void main(String args[]) {
try {
  LogManager lm = LogManager.getLogManager();
  Logger logger;
  FileHandler fh = new FileHandler("log_test.txt");

  logger = Logger.getLogger("LoggingExample1");
  lm.addLogger(logger);
  logger.setLevel(Level.INFO);

  fh.setFormatter(new SimpleFormatter());

  logger.addHandler(fh);
  // root logger defaults to SimpleFormatter. We don't want messages
  // logged twice.
  //logger.setUseParentHandlers(false);

  logger.log(Level.INFO, "test 1");
  logger.log(Level.INFO, "test 2");
  logger.log(Level.INFO, "test 3");
  fh.close();
} catch (Exception e) {
  System.out.println("Exception thrown: " + e);
  e.printStackTrace();
}
}
}

i get this log:

Aug 1, 2011 5:36:37 PM LoggingExample1 main
INFO: test 1
Aug 1, 2011 5:36:37 PM LoggingExample1 main
INFO: test 2
Aug 1, 2011 5:36:37 PM LoggingExample1 main
INFO: test 3

but i want to remove the messages like: LoggingExample1 main and INFO and only keep the data that are logged by code. what can i do???

like image 320
RosAng Avatar asked Aug 01 '11 12:08

RosAng


2 Answers

This is because you are using a SimpleFormatter which always logs the class name, method name etc. If you don't want this information, you can write your own formatter. Here is a simple example of a formatter which just outputs the log level and the log message:

import java.util.logging.*;

class MyFormatter extends Formatter{

    /* (non-Javadoc)
     * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
     */
    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder();
        sb.append(record.getLevel()).append(':');
        sb.append(record.getMessage()).append('\n');
        return sb.toString();
    }    
}

Use this formatter in your file handler:

fh.setFormatter(new MyFormatter());

This will output:

INFO:test 1
INFO:test 2
INFO:test 3
like image 147
dogbane Avatar answered Sep 21 '22 18:09

dogbane


Extend your class with formatter class as below:

public class MyFormatter extends SimpleFormatter{

@Override

public synchronized String format(LogRecord record){

    record.setSourceClassName(MyFormatter.class .getName());
    return String.format(
            " [%1$s] :%2$s\n",
            record.getLevel().getName(), formatMessage(record));

    }
}

Then in you main class, set console handler and filehandler format as your class format object. In my case ,it is consoleHandler.format(new MyFormatter); filehandler.format(new Myformatter);

Most imp thing is you have to set logger.setUseParentHandler(false);

now you are good to go!

like image 25
bunny Avatar answered Sep 21 '22 18:09

bunny