Custom log message format in Java

Публикувано / posted 2011-01-06 в категория / in category: Java
  

Sometimes default formating of the log messages in Java is just not good enough. For example: I needed dates to be formated as YYYY-MM-DD, not YYYY-M-D and more important: I needed and extra new line after each message for two purposes: 1. To improve readability and 2. To be compatible with one old (PHP based) tool of mine that I use to parse log files. Strangely enough, I was unable to find decent examples how to change the default behaviour and after few attempts I finally come with the following (you will have to replace FMConstants.LOGGER_NAME and FMConstants.LOGGER_LEVEL with your own values):

		logger = Logger.getLogger(FMConstants.LOGGER_NAME);
		logger.setLevel(FMConstants.LOGGER_LEVEL);

		Handler handler = new ConsoleHandler();
		handler.setLevel(FMConstants.LOGGER_LEVEL);
		SimpleFormatter fmt = new SimpleFormatter() {
			@Override
			public String format(LogRecord record) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				StringBuffer sb = new StringBuffer();
				sb.append(sdf.format(record.getMillis()));
				sb.append(" - ");
				if (record.getSourceClassName() != null) {
				    sb.append(record.getSourceClassName());
				} else {
				    sb.append(record.getLoggerName());
				}
				if (record.getSourceMethodName() != null) {
				    sb.append(" ");
				    sb.append(record.getSourceMethodName());
				}

			    String lineSeparator = (String) java.security.AccessController.doPrivileged(
		               new sun.security.action.GetPropertyAction("line.separator"));
				sb.append(lineSeparator);

				sb.append(record.getLevel().getLocalizedName());
				sb.append(": ");
				sb.append(record.getMessage());

				sb.append(lineSeparator);
				sb.append(lineSeparator);

				return sb.toString();
			}

		};
		handler.setFormatter(fmt);
		logger.addHandler(handler);

And the log output will look like:

2011-01-06 17:42:09 - com.bolyar.fm.FMConfigStorage load
CONFIG: No value for last source dir. Will try to detect.

2011-01-06 17:42:09 - com.bolyar.fm.FMConfigStorage load
CONFIG: Last source dir: C:\

2011-01-06 17:42:09 - com.bolyar.fm.FMConfigStorage load
CONFIG: No value for last target dir. Will try to detect.

2011-01-06 17:42:09 - com.bolyar.fm.FMConfigStorage load
CONFIG: Last target dir: C:\

Leave a Reply

Внимание: Моля, въведете само ПЪРВИТЕ ТРИ цифри от картинката
Important: Please enter just the first three digits from the image