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

Revision 1518, 10.1 kB (checked in by amandel, 3 years ago)

Sort the parameters by their name in output.

  • 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.ParseException;
38import java.util.ArrayList;
39import java.util.Arrays;
40import java.util.Iterator;
41import java.util.List;
42import java.util.logging.LogRecord;
43
44import org.jcoderz.commons.Loggable;
45import org.jcoderz.commons.util.StringUtil;
46
47/**
48 * This class is used for formatting the parameters of a Loggable and parsing
49 * one parameter log line.
50 *
51 */
52public class ParameterLineFormat
53      extends ContinuationLineFormat
54{
55   /** The number of fields added to the basic continuation line format.
56     * The cause field is added.
57     */
58   private static final int NUMBER_OF_ADDITIONAL_PARAMETERS = 2;
59
60   private static final int PARAMETER_NAME_INDEX = NUMBER_OF_PARAMETERS;
61   private static final int PARAMETER_VALUE_INDEX = PARAMETER_NAME_INDEX + 1;
62
63   /** The fields added to the basic format. Parameter name and parameter value
64    * list are added.
65    */
66   private static final String ADDITIONAL_LOGLINE_FORMAT_PATTERN
67        = " {" + PARAMETER_NAME_INDEX + "}: \t{" + PARAMETER_VALUE_INDEX + "}";
68
69   /** The symbol name of a LogMessageInfo will be logged as parameter value
70    * for a parameter with this name. */
71   private static final String SYMBOL_TAG = LogItem.INTERNAL_PARAMETER_PREFIX
72         + "SYMBOL_";
73
74   /** The location where a Loggable is logged will be logged as parameter value
75    * for a parameter with this name. */
76   private static final String SOURCE_TAG = LogItem.INTERNAL_PARAMETER_PREFIX
77         + "LOGGED_AT_";
78
79   /** The possible solution for an error will be logged as parameter value
80    * for a parameter with this name. */
81   private static final String SOLUTION_TAG = LogItem.INTERNAL_PARAMETER_PREFIX
82         + "SOLUTION_";
83
84   /**
85    * Creates a new instance of this and initializes the message format.
86    */
87   public ParameterLineFormat ()
88   {
89      super(LogLineFormat.PARAMETER_LINE, ADDITIONAL_LOGLINE_FORMAT_PATTERN,
90            NUMBER_OF_ADDITIONAL_PARAMETERS);
91      setFormats(getFormatList(null, true));
92   }
93
94   /**
95    * Gets the formats as array for formatting a parameter line.
96    *
97    * @param options The display options specifying which fields to display.
98    * Will be ignored and ,ight be null if <code>ignoreOptions == true</code>.
99    * @param ignoreOptions flag whether to ignore the supplied options and
100    * return the formats for all fields.
101    *
102    * @return array filled with formats for each selected field. Might be empty
103    * array, never null.
104    */
105   static final Format[] getFormatList (
106         final DisplayOptions options,
107         final boolean ignoreOptions)
108   {
109      final List formatList = new ArrayList();
110      if (ignoreOptions || options.displayThreadId())
111      {
112         // thread id
113         formatList.add(getThreadIdFormat());
114      }
115      if (ignoreOptions || options.displayTrackingNumber())
116      {
117         // sequence of tracking id
118         formatList.add(getTrackingNumberFormat());
119      }
120      // parameter name
121      formatList.add(new AsItIsFormat(": \t"));
122         // parameter value list, the list end char must be included in the
123         // chars to escape.
124      formatList.add(new WhitespaceFormat(
125            new CollectionFormat(new StringEscapeFormat(",]"))));
126      return (Format[]) formatList.toArray(EMPTY_FORMATTERS);
127   }
128
129   /**
130    * Formats the parameters of a Loggable. Always adds the log location and
131    * log message symbal as first parameters. This will format several lines
132    * into the StringBuffer.
133    * Append a line feed after the data has been formatted into the
134    * StringBuffer.
135    *
136    * @param sb The StringBuffer where to append the formatted data.
137    * @param record Unused, might be null.
138    * @param loggable The Loggable to format.
139    * @param trackingIdSequence The sequence of contributing tracking ids.
140    * @param thrown Unused, might be null.
141    * @param parameter Unused, might be null.
142    */
143   public void format (
144         final StringBuffer sb,
145         final LogRecord record,
146         final Loggable loggable,
147         final List trackingIdSequence,
148         final Throwable thrown,
149         final Object parameter)
150   {
151      if ((parameter != null) && ! (parameter instanceof Throwable))
152      {
153         throw new IllegalArgumentException(
154               "Parameter must be null or a Throwable, but is: " + parameter);
155      }
156      if (!StringUtil.isEmptyOrNull(loggable.getLogMessageInfo().getSymbol()))
157      {
158          setParameterName(SYMBOL_TAG);
159          setParameterValues(Arrays.asList(
160                new String[]{loggable.getLogMessageInfo().getSymbol()}));
161          basicFormat(sb, record, loggable, trackingIdSequence);
162      }
163
164      final String solution = loggable.getLogMessageInfo().getSolution();
165      if (!StringUtil.isEmptyOrNull(solution))
166      {
167          setParameterName(SOLUTION_TAG);
168          setParameterValues(Arrays.asList(
169                new String[]{solution}));
170          basicFormat(sb, record, loggable, trackingIdSequence);
171      }
172
173      // log location
174      final String location = getLogLocation(record);
175      if (!".".equals(location))
176      {
177          setParameterName(SOURCE_TAG);
178          setParameterValues(Arrays.asList(new String[]{location}));
179          basicFormat(sb, record, loggable, trackingIdSequence);
180      }
181
182      appendParameters(sb, record, loggable, trackingIdSequence);
183   }
184
185   /**
186    * Parses one line of log data and sets the data in the supplied
187    * LogFileEntry.
188    *
189    * @param sb The StringBuffer containing the log line to parse from the
190    * current position to the end.
191    * @param entry The LogFileEntry which gets the data being parsed.
192    *
193    * @throws ParseException if an error occurs parsing the log line.
194    */
195   public void parse (StringBuffer sb, LogFileEntry entry)
196         throws ParseException
197   {
198      try
199      {
200         basicParse(sb, entry);
201         if (getParameterName().equals(SOURCE_TAG))
202         {
203            final String[] source
204                  = getLogSource((String) getParameterValues().get(0));
205            entry.setSourceClass(source[SOURCECLASS_INDEX]);
206            entry.setSourceMethod(source[SOURCEMETHOD_INDEX]);
207         }
208         else if (getParameterName().equals(SOLUTION_TAG)
209               && (getParameterValues() != null)
210               && ! getParameterValues().isEmpty())
211         {
212            entry.setSolution((String) getParameterValues().get(0));
213         }
214         else if (getParameterName().equals(SYMBOL_TAG))
215         {
216            entry.setSymbol((String) getParameterValues().get(0));
217         }
218         else
219         {
220            entry.addToParameters(getParameterName(), getParameterValues());
221         }
222      }
223      catch (ParseException pex)
224      {
225         // just rethrow
226         throw pex;
227      }
228      catch (Exception ex)
229      {
230         final ParseException pex = new ParseException(
231               "Got an error parsing " + sb, 0);
232         pex.initCause(ex);
233         throw pex;
234      }
235   }
236
237   private void appendParameters (
238         final StringBuffer sb,
239         final LogRecord record,
240         final Loggable loggable,
241         final List trackingIds)
242   {
243       final java.util.Set/*<String>*/ namesUnsorted
244           = loggable.getParameterNames();
245       final String[] names
246           = (String[]) namesUnsorted.toArray(
247               new String[namesUnsorted.size()]);
248       Arrays.sort(names);
249
250      for (final Iterator nameIter = Arrays.asList(names).iterator();
251            nameIter.hasNext(); )
252      {
253         final String name = (String) nameIter.next();
254         if (! name.startsWith(LogItem.INTERNAL_PARAMETER_PREFIX))
255         {
256            setParameterName(name);
257            setParameterValues(loggable.getParameter(name));
258            basicFormat(sb, record, loggable, trackingIds);
259         }
260      }
261   }
262
263   private void setParameterName (final String name)
264   {
265      setParameter(PARAMETER_NAME_INDEX, name);
266   }
267
268   private String getParameterName ()
269   {
270      return (String) getParameter(PARAMETER_NAME_INDEX);
271   }
272
273   private void setParameterValues (final List values)
274   {
275      setParameter(PARAMETER_VALUE_INDEX, values);
276   }
277
278   private List getParameterValues ()
279   {
280      return (List) getParameter(PARAMETER_VALUE_INDEX);
281   }
282
283   /**
284    * Gets the log location as classname.methodname
285    *
286    * @param record The LogRecord wrapping the log location.
287    *
288    * @return the location where the log record was logged.
289    */
290   private String getLogLocation (final LogRecord record)
291   {
292      return record.getSourceClassName() + "." + record.getSourceMethodName();
293   }
294}
Note: See TracBrowser for help on using the browser.