2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 package org.apache.log4j.pattern;
20 import org.apache.log4j.spi.LoggingEvent;
22 import java.util.Iterator;
24 import org.apache.log4j.helpers.*;
28 * Able to handle the contents of the LoggingEvent's Property bundle and either
29 * output the entire contents of the properties in a similar format to the
30 * java.util.Hashtable.toString(), or to output the value of a specific key
31 * within the property bundle
32 * when this pattern converter has the option set.
35 * @author Ceki Gülcü
37 public final class PropertiesPatternConverter
38 extends LoggingEventPatternConverter {
40 * Name of property to output.
42 private final String option;
45 * Private constructor.
46 * @param options options, may be null.
48 private PropertiesPatternConverter(
49 final String[] options) {
51 ((options != null) && (options.length > 0))
52 ? ("Property{" + options[0] + "}") : "Properties", "property");
54 if ((options != null) && (options.length > 0)) {
62 * Obtains an instance of PropertiesPatternConverter.
63 * @param options options, may be null or first element contains name of property to format.
64 * @return instance of PropertiesPatternConverter.
66 public static PropertiesPatternConverter newInstance(
67 final String[] options) {
68 return new PropertiesPatternConverter(options);
74 public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
75 // if there is no additional options, we output every single
76 // Key/Value pair for the MDC in a similar format to Hashtable.toString()
78 toAppendTo.append("{");
81 Set keySet = MDCKeySetExtractor.INSTANCE.getPropertyKeySet(event);
83 for (Iterator i = keySet.iterator(); i.hasNext();) {
84 Object item = i.next();
85 Object val = event.getMDC(item.toString());
86 toAppendTo.append("{").append(item).append(",").append(val).append(
90 } catch(Exception ex) {
91 LogLog.error("Unexpected exception while extracting MDC keys", ex);
94 toAppendTo.append("}");
96 // otherwise they just want a single key output
97 Object val = event.getMDC(option);
100 toAppendTo.append(val);