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

Revision 1537, 14.8 kB (checked in by amandel, 3 years ago)

Catch the situation where a old loggable is held that does not carry the thread name.

  • 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
35import java.text.MessageFormat;
36import java.text.ParseException;
37import java.util.ArrayList;
38import java.util.List;
39import java.util.logging.Level;
40import java.util.logging.LogRecord;
41
42import org.jcoderz.commons.BusinessImpact;
43import org.jcoderz.commons.Category;
44import org.jcoderz.commons.Loggable;
45import org.jcoderz.commons.LoggableImpl;
46import org.jcoderz.commons.types.Date;
47import org.jcoderz.commons.util.Constants;
48
49
50
51/**
52 * This class is the base class for log formats formatting the main log line of
53 * the log message, which contains all fields required for CA Unicenter
54 * integration. All sub classes of this are required to use these fields at the
55 * index required by this, but are allowed to append additional fields.
56 *
57 */
58public abstract class BasicLogLineFormat
59      extends LogLineFormat
60{
61   /** The number of parameters of the basic format. */
62   protected static final int NUMBER_OF_PARAMETERS = 9;
63
64   private static final int TIMESTAMP_INDEX = 0;
65   private static final int NODEID_INDEX = 1;
66   private static final int INSTANCEID_INDEX = 2;
67   private static final int THREADID_INDEX = 3;
68   private static final int LEVEL_INDEX = 4;
69   private static final int MESSAGEID_INDEX = 5;
70   private static final int BUSINESSIMPACT_INDEX = 6;
71   private static final int CATEGORY_INDEX = 7;
72   private static final int THREAD_NAME_INDEX = 7;
73   private static final int TRACKINGID_INDEX = 8;
74
75   /**
76    * Common format for CA Unicenter log lines.
77    * Has the fields in following order:
78    * <ul>
79    * <li>timestamp
80    * <li>node id
81    * <li>instance id
82    * <li>thread id
83    * <li>logger level
84    * <li>message id
85    * <li>business impact
86    * <li>category
87    * <li>tracking number
88    * <li>thread name
89    * </ul>
90    */
91   private static final String LOGLINE_FORMAT_PATTERN
92         = "{0} {1} {2} {3} {4} {5} {6} {7} {8}";
93
94   private static final String NO_MSG_SYMBOL = "TRACEMSG";
95
96   private final int mNumParameters;
97   private final String mLogFormatPattern;
98
99
100   /**
101    * Creates a new instance of this and initializes the message format.
102    *
103    * @param type THe log line type.
104    * @param additionalPattern The pattern for additional fields not included by
105    * this. Must start with the desired delimiter before the first field.
106    * @param numAdditionalParameters The number of additional fields.
107    */
108   protected BasicLogLineFormat (
109         final LogLineType type,
110         final String additionalPattern,
111         final int numAdditionalParameters)
112   {
113      super(type, new MessageFormat(type.getTypeSpecifier() + " "
114            + LOGLINE_FORMAT_PATTERN + additionalPattern),
115            NUMBER_OF_PARAMETERS + numAdditionalParameters);
116
117      mNumParameters = NUMBER_OF_PARAMETERS + numAdditionalParameters;
118      mLogFormatPattern = LOGLINE_FORMAT_PATTERN + additionalPattern;
119   }
120
121   /**
122    * Gets the formats as array for formatting all elements of a basic log line.
123    *
124    * @param options The display options specifying which fields to display.
125    * Will be ignored and might be null if <code>ignoreOptions == true</code>.
126    * @param ignoreOptions flag whether to ignore the supplied options and
127    * return the formats for all fields.
128    *
129    * @return List filled with formats for each selected field. Might be empty,
130    * never null.
131    */
132   protected static List getBasicFormatList (
133         final DisplayOptions options,
134         final boolean ignoreOptions)
135   {
136      final List formatList = new ArrayList();
137      if (ignoreOptions || options.displayTimestamp())
138      {
139         // date
140         formatList.add(getTimestampFormat());
141      }
142      if (ignoreOptions || options.displayNodeId())
143      {
144         // node id
145         formatList.add(getNodeIdFormat());
146      }
147      if (ignoreOptions || options.displayInstanceId())
148      {
149         // instance id
150         formatList.add(getInstanceIdFormat());
151      }
152      if (ignoreOptions || options.displayThreadId())
153      {
154         // thread id
155         formatList.add(getThreadIdFormat());
156      }
157      if (ignoreOptions || options.displayLoggerLevel())
158      {
159         // logger level
160         formatList.add(getLoggerLevelFormat());
161      }
162      if (ignoreOptions || options.displaySymbolId())
163      {
164         // symbol
165         formatList.add(getMessageSymbolFormat());
166      }
167      if (ignoreOptions || options.displayBusinessImpact())
168      {
169         // business impact
170         formatList.add(getBusinessImpactFormat());
171      }
172      if (ignoreOptions || options.displayThreadName())
173      {
174         // category
175         formatList.add(getThreadNameFormat());
176      }
177      // was replaced with thread name in default
178      if (!ignoreOptions && options.displayCategory())
179      {
180         // category
181         formatList.add(getCategoryFormat());
182      }
183      if (ignoreOptions || options.displayTrackingNumber())
184      {
185         // sequence of tracking id
186         formatList.add(getTrackingNumberFormat());
187      }
188      return formatList;
189   }
190
191   /**
192    * Formats the supplied LogRecord with the encapsulated basic message format.
193    * Data for additional fields has to be set before calling this.
194    * Appends a line feed after the data is formatted into the StringBuffer.
195    *
196    * @param sb The StringBuffer where to append the formatted LogRecord.
197    * @param record The LogRecord to format.
198    * @param loggable Unused by this, might be null.
199    * @param trackingIdSequence The list containing the sequence of tracking
200    * ids contributing to this log message.
201    */
202   protected final void basicFormat (
203         final StringBuffer sb,
204         final LogRecord record,
205         final Loggable loggable,
206         final List trackingIdSequence)
207   {
208      setLevel(record.getLevel());
209      setTrackingIds(trackingIdSequence);
210
211      if (loggable != null)
212      {
213         setTimestamp(new Date(loggable.getEventTime()));
214         setNodeId(loggable.getNodeId());
215         setInstanceId(loggable.getInstanceId());
216         setThreadId(loggable.getThreadId());
217         setMessageId(
218               Integer.toHexString(loggable.getLogMessageInfo().toInt()));
219         setBusinessImpact(loggable.getLogMessageInfo().getBusinessImpact());
220         setCategory(loggable.getLogMessageInfo().getCategory());
221         try
222         {
223             setThreadName(loggable.getThreadName());
224         }
225         catch (AbstractMethodError ex)
226         {
227             // We have a old loggable that does not support
228             // thread name jet.
229             setThreadName(Thread.currentThread().getName());
230         }
231      }
232      else
233      {
234         setTimestamp(new Date(record.getMillis()));
235         setNodeId(LoggableImpl.NODE_ID);
236         setInstanceId(LoggableImpl.INSTANCE_ID);
237         setThreadId(record.getThreadID());
238         setBusinessImpact(BusinessImpact.NONE);
239         setCategory(Category.TECHNICAL);
240         // Take care this one might be wrong!
241         setThreadName(Thread.currentThread().getName());
242         setMessageId(NO_MSG_SYMBOL);
243      }
244      format(sb);
245      sb.append(Constants.LINE_SEPARATOR);
246   }
247
248   /**
249    * Parses a log line, which must be formatted by this, and sets the
250    * appropriate basic values of the supplied LogFileEntry. Derived types might
251    * retrieve specific field values after this has been called.
252    *
253    * @param sb The StringBuffer containing the current log line.
254    * @param entry The LogFileEntry for which to parse the log line.
255    *
256    * @throws ParseException if an error occurs parsing <code>sb</code>.
257    *
258    * @see org.jcoderz.commons.logging.LogLineFormat#parse(java.lang.StringBuffer, org.jcoderz.commons.logging.LogFileEntry)
259    */
260   protected final void basicParse (StringBuffer sb, LogFileEntry entry)
261         throws ParseException
262   {
263      try
264      {
265         parse(sb);
266
267         entry.setBusinessImpact(getBusinessImpact());
268         // entry.setCategory(getCategory());
269         entry.setThreadName(getThreadName());
270         entry.setInstanceId(getInstanceId());
271         entry.setLoggerLevel(getLevel());
272         entry.setNodeId(getNodeId());
273         entry.setThreadId(getThreadId());
274         entry.setSymbolId(getMessageId());
275         entry.setTimestamp(getTimestamp());
276
277         // the last element within the tracking id sequence is the id of the
278         // current entry.
279         final List trackingIds = getTrackingIds();
280         entry.setTrackingNumber((String) trackingIds.get(
281               trackingIds.size() - 1));
282      }
283      catch (ParseException pex)
284      {
285         // just rethrow
286         throw pex;
287      }
288      catch (Exception ex)
289      {
290         final ParseException pex = new ParseException(
291               "Got an error parsing " + sb, 0);
292         pex.initCause(ex);
293         throw pex;
294      }
295   }
296
297
298   /**
299    * Sets the timestamp.
300    *
301    * @param timestamp The timestamp to set.
302    */
303   protected final void setTimestamp (final Date timestamp)
304   {
305      setParameter(TIMESTAMP_INDEX, timestamp);
306   }
307
308   /**
309    * Gets the timestamp of a parsed log line.
310    *
311    * @return Timestamp of parsed log line.
312    */
313   protected final Date getTimestamp ()
314   {
315      return (Date) getParameter(TIMESTAMP_INDEX);
316   }
317
318   /**
319    * Sets the node id to dump.
320    *
321    * @param nodeId The node id to dump.
322    */
323   protected final void setNodeId (final String nodeId)
324   {
325      setParameter(NODEID_INDEX, nodeId);
326   }
327
328   /**
329    * Gets the node id of a parsed log line.
330    *
331    * @return Node id of parsed log line.
332    */
333   protected final String getNodeId ()
334   {
335      return (String) getParameter(NODEID_INDEX);
336   }
337
338   /**
339    * Sets the instance id to dump.
340    *
341    * @param instanceId The instance id to dump.
342    */
343   protected final void setInstanceId (final String instanceId)
344   {
345      setParameter(INSTANCEID_INDEX, instanceId);
346   }
347
348   /**
349    * Gets the instance id of a parsed log line.
350    *
351    * @return Instance id of parsed log line.
352    */
353   protected final String getInstanceId ()
354   {
355      return (String) getParameter(INSTANCEID_INDEX);
356   }
357
358   /**
359    * Sets the thread id from the message to dump.
360    *
361    * @param threadId The thread id to dump.
362    */
363   protected final void setThreadId (final long threadId)
364   {
365      setParameter(THREADID_INDEX, String.valueOf(threadId));
366   }
367
368   /**
369    * Gets the thread id of a parsed log line.
370    *
371    * @return Thread id of parsed log line.
372    */
373   protected final long getThreadId ()
374   {
375      return Long.parseLong((String) getParameter(THREADID_INDEX));
376   }
377
378   /**
379    * Sets the thread name from the message to dump.
380    *
381    * @param threadName The thread name to dump.
382    */
383   protected final void setThreadName (String threadName)
384   {
385      setParameter(THREAD_NAME_INDEX, threadName);
386   }
387
388   /**
389    * Gets the thread id of a parsed log line.
390    *
391    * @return Thread id of parsed log line.
392    */
393   protected final String getThreadName ()
394   {
395      return (String) getParameter(THREAD_NAME_INDEX);
396   }
397
398   /**
399    * Sets the list of tracking ids to dump.
400    *
401    * @param trackingIds The sequence of tracking ids to dump.
402    */
403   protected final void setTrackingIds (final List trackingIds)
404   {
405      setParameter(TRACKINGID_INDEX, trackingIds);
406   }
407
408   /**
409    * Gets the sequence of tracking ids of a parsed log line.
410    *
411    * @return Sequence of tracking ids of parsed log line.
412    */
413   protected final List getTrackingIds ()
414   {
415      return (List) getParameter(TRACKINGID_INDEX);
416   }
417
418   /**
419    * Sets the level of the message to dump,
420    *
421    * @param level The log level of the message.
422    */
423   protected final void setLevel (final Level level)
424   {
425      setParameter(LEVEL_INDEX, level.getName());
426   }
427
428   /**
429    * Gets the log level of a parsed log line.
430    *
431    * @return Log level of parsed log line.
432    */
433   protected final Level getLevel ()
434   {
435      return Level.parse((String) getParameter(LEVEL_INDEX));
436   }
437
438   /**
439    * Sets the message id from the message to dump.
440    *
441    * @param messageId The message id of the message.
442    */
443   protected final void setMessageId (final String messageId)
444   {
445      setParameter(MESSAGEID_INDEX, messageId);
446   }
447
448   /**
449    * Gets the message id of a parsed log line.
450    *
451    * @return Message id of parsed log line.
452    */
453   protected final String getMessageId ()
454   {
455      return (String) getParameter(MESSAGEID_INDEX);
456   }
457
458   /**
459    * Sets the business impact from the message to dump.
460    *
461    * @param impact The business impact of the message.
462    */
463   protected final void setBusinessImpact (final BusinessImpact impact)
464   {
465      setParameter(BUSINESSIMPACT_INDEX, impact.toString());
466   }
467
468   /**
469    * Gets the business impact of a parsed log line.
470    *
471    * @return Business impact of parsed log line.
472    */
473   protected final BusinessImpact getBusinessImpact ()
474   {
475      return BusinessImpact.fromString(
476            (String) getParameter(BUSINESSIMPACT_INDEX));
477   }
478
479   /**
480    * Sets the category to dump.
481    *
482    * @param category The category of the message to dump.
483    */
484   protected final void setCategory (final Category category)
485   {
486      setParameter(CATEGORY_INDEX, category.toString());
487   }
488
489   /**
490    * Gets the category of a parsed log line.
491    *
492    * @return Category of parsed log line.
493    */
494   protected final Category getCategory ()
495   {
496      return Category.fromString((String) getParameter(CATEGORY_INDEX));
497   }
498
499}
Note: See TracBrowser for help on using the browser.