001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions Copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2014 ForgeRock AS.
015 */
016package org.opends.server.loggers;
017
018import java.text.DateFormat;
019import java.text.SimpleDateFormat;
020import java.util.Date;
021import java.util.logging.Formatter;
022import java.util.logging.LogRecord;
023
024import org.opends.server.util.StaticUtils;
025
026/**
027 * A formatter to replace default format of java.util.logging loggers.
028 * <p>
029 * With JDK 7+, it is possible to pass in the format from the
030 * "java.util.logging.SimpleFormatter.format" parameter to the JVM. Use the
031 * parameter instead of this class when JDK6 is not supported any more.
032 */
033public final class JDKLoggingFormater extends Formatter
034{
035
036  /** Use one formatter per thread as DateFormat is not thread-safe. */
037  private static final ThreadLocal<DateFormat> DATE_FORMAT =
038      new ThreadLocal<DateFormat>()
039      {
040        @Override
041        protected DateFormat initialValue()
042        {
043          return new SimpleDateFormat("[dd/MM/yyyy:HH:mm:ss Z]");
044        }
045      };
046
047  /** {@inheritDoc} */
048  @Override
049  public String format(LogRecord record)
050  {
051    StringBuilder b = new StringBuilder();
052    b.append(DATE_FORMAT.get().format(new Date(record.getMillis())));
053    b.append(" category=").append(LoggingCategoryNames.getCategoryName(record.getLoggerName()));
054    b.append(" seq=").append(record.getSequenceNumber());
055    b.append(" severity=").append(record.getLevel());
056    b.append(" msg=").append(record.getMessage());
057    if (record.getThrown() != null)
058    {
059      b.append(" exception=").append(
060          StaticUtils.stackTraceToSingleLineString(record.getThrown()));
061    }
062    b.append("\n");
063    return b.toString();
064  }
065
066}