root/trunk/src/java/org/jcoderz/commons/logging/TraceLineFormat.java

Revision 1535, 8.6 kB (checked in by amandel, 3 years ago)

Take care not to add multiple "()" to output of source method.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 *
4 * Copyright 2006, The jCoderZ.org Project. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 *    * Redistributions of source code must retain the above copyright
11 *      notice, this list of conditions and the following disclaimer.
12 *    * Redistributions in binary form must reproduce the above
13 *      copyright notice, this list of conditions and the following
14 *      disclaimer in the documentation and/or other materials
15 *      provided with the distribution.
16 *    * Neither the name of the jCoderZ.org Project nor the names of
17 *      its contributors may be used to endorse or promote products
18 *      derived from this software without specific prior written
19 *      permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
30 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
31 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33package org.jcoderz.commons.logging;
34
35
36import java.text.Format;
37import java.text.MessageFormat;
38import java.text.ParseException;
39import java.util.List;
40import java.util.logging.LogRecord;
41
42import org.jcoderz.commons.Loggable;
43import org.jcoderz.commons.util.ArraysUtil;
44import org.jcoderz.commons.util.ObjectUtil;
45import org.jcoderz.commons.util.StringUtil;
46
47/**
48 * This formats a standard LogRecord and parses a log line with a formatted
49 * log record.
50 *
51 */
52public class TraceLineFormat
53      extends BasicLogLineFormat
54{
55   /** The number of fields added to the basic format.
56   The source and text field is added. */
57   private static final int NUMBER_OF_ADDITIONAL_PARAMETERS = 2;
58
59   private static final int LOGSOURCE_INDEX = NUMBER_OF_PARAMETERS;
60
61   private static final int TEXT_INDEX = LOGSOURCE_INDEX + 1;
62
63   /** The fields added to the basic format. No fields are added. */
64   private static final String ADDITIONAL_LOGLINE_FORMAT_PATTERN
65        = " {" + LOGSOURCE_INDEX + "} {" + TEXT_INDEX + "}";
66
67   private static final String EMPTY_MSG = " ";
68
69   /**
70    * Creates a new instance of this and sets the default line type specifier.
71    */
72   TraceLineFormat ()
73   {
74      this(LogLineFormat.TRACE_MESSAGE);
75   }
76
77   /**
78    * Creates a new instance of this and sets the supplied line type specifier.
79    * This might be used by more specialized subtypes of this.
80    *
81    * @param type The LineTypeSpecifier to set.
82    */
83   protected TraceLineFormat (final LogLineType type)
84   {
85      super(type, ADDITIONAL_LOGLINE_FORMAT_PATTERN,
86            NUMBER_OF_ADDITIONAL_PARAMETERS);
87      setFormats(getFormatList(null, true));
88   }
89
90   /**
91    * Formats the supplied LogRecord with the encapsulated message format.
92    * Appends a line feed after the data is formatted into the StringBuffer.
93    *
94    * @param sb The StringBuffer where to append the formatted LogRecord.
95    * @param record The LogRecord to format.
96    * @param loggable Unused by this, might be null.
97    * @param trackingIdSequence The list containing the sequence of tracking
98    * ids contributing to this log message.
99    * @param thrown Unused by this, might be null.
100    * @param parameter Unused by this, might be null.
101    *
102    * @see LogLineFormat#format(StringBuffer, LogRecord, Loggable, List, Throwable, Object)
103    */
104   public void format (
105         final StringBuffer sb,
106         final LogRecord record,
107         final Loggable loggable,
108         final List trackingIdSequence,
109         final Throwable thrown,
110         final Object parameter)
111   {
112      if (record.getParameters() == null)
113      {
114         setMessageText(record.getMessage());
115      }
116      else
117      {
118        setMessageText(
119          formatMessage(record.getMessage(), record.getParameters()));
120      }
121      setLogSource(record.getSourceClassName(), record.getSourceMethodName());
122      basicFormat(sb, record, loggable, trackingIdSequence);
123   }
124
125   /**
126    * Parses a log line, which must be formatted by this, and sets the
127    * appropriate values of the supplied LogFileEntry.
128    *
129    * @param sb The StringBuffer containing the current log line.
130    * @param entry The LogFileEntry for which to parse the log line.
131    *
132    * @throws ParseException if an error occurs.
133    *
134    * @see LogLineFormat#parse(StringBuffer, LogFileEntry)
135    */
136   public void parse (StringBuffer sb, LogFileEntry entry)
137         throws ParseException
138   {
139      try
140      {
141         basicParse(sb, entry);
142         entry.setMessage(getMessageText());
143         final String[] logSource = getLogSource();
144
145         entry.setSourceClass(logSource[SOURCECLASS_INDEX]);
146         entry.setSourceMethod(logSource[SOURCEMETHOD_INDEX]);
147      }
148      catch (ParseException pex)
149      {
150         // just rethrow
151         throw pex;
152      }
153      catch (Exception ex)
154      {
155         final ParseException pex = new ParseException(
156               "Got an error parsing " + sb, 0);
157         pex.initCause(ex);
158         throw pex;
159      }
160   }
161
162   /**
163    * Gets the formats as array for formatting a trace line.
164    *
165    * @param options The display options specifying which fields to display.
166    * Will be ignored and ,ight be null if <code>ignoreOptions == true</code>.
167    * @param ignoreOptions flag whether to ignore the supplied options and
168    * return the formats for all fields.
169    *
170    * @return array filled with formats for each selected field. Might be empty
171    * array, never null.
172    */
173   static final Format[] getFormatList (
174         final DisplayOptions options,
175         final boolean ignoreOptions)
176   {
177      final List formatList = getBasicFormatList(options, ignoreOptions);
178      if (ignoreOptions || options.displaySourceClass()
179            || options.displaySourceMethod())
180      {
181         formatList.add(new AsItIsFormat(" \t"));
182      }
183      formatList.add(new WhitespaceFormat(new AsItIsFormat("\r\n")));
184//      formatList.add(new AsItIsFormat("\r\n"));
185      return (Format[]) formatList.toArray(EMPTY_FORMATTERS);
186   }
187
188   /**
189    * Sets the message to format. If the supplied string is null or empty, a
190    * space is set.
191    *
192    * @param text The message text.
193    */
194   protected final void setMessageText (final String text)
195   {
196      if (text == null || text.length() <= 0)
197      {
198         setParameter(TEXT_INDEX, EMPTY_MSG);
199      }
200      else
201      {
202         setParameter(TEXT_INDEX, text);
203      }
204   }
205
206   /**
207    * Gets the message text of a parsed log line.
208    *
209    * @return Message text of parsed log line.
210    */
211   protected final String getMessageText ()
212   {
213      return (String) getParameter(TEXT_INDEX);
214   }
215
216   /**
217    * Sets the log source as classname.methodname()
218    *
219    * @param clazz The name of the class.
220    * @param method The name of the method.
221    */
222   protected final void setLogSource (
223         final String clazz, final String method)
224   {
225       final boolean needParentheses
226           = !StringUtil.isNullOrEmpty(method) && method.indexOf('(') < 0;
227       setParameter(LOGSOURCE_INDEX,
228           ObjectUtil.toStringOrEmpty(clazz) + "." 
229               + ObjectUtil.toStringOrEmpty(method) 
230               + (needParentheses ? "()" : ""));
231   }
232
233   /**
234    * Gets the source class name and source method name where the Log record was
235    * logged of a parsed log line.
236    *
237    * @return String array with source class name as first and source method
238    * name as second parameter.
239    */
240   protected final String[] getLogSource ()
241   {
242      return getLogSource((String) getParameter(LOGSOURCE_INDEX));
243   }
244
245   private static final String formatMessage (String pattern, Object[] params)
246   {
247      String result;
248      if (params != null && params.length != 0)
249      {
250          try
251          {
252              final MessageFormat formatter = new MessageFormat(pattern);
253              result
254                  = formatter.format(
255                      params, new StringBuffer(), null).toString();
256          }
257          catch (IllegalArgumentException ex)
258          {
259              result
260                  = ArraysUtil.toString(params) + " " + pattern;
261          }
262      }
263      else
264      {
265          result = pattern;
266      }
267      return result;
268   }
269
270}
Note: See TracBrowser for help on using the browser.