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.
17 package org.apache.log4j.helpers;
19 import org.apache.log4j.spi.LoggingEvent;
20 import org.apache.log4j.pattern.LogEvent;
22 import java.lang.reflect.Method;
24 import java.io.ByteArrayOutputStream;
25 import java.io.ObjectOutputStream;
26 import java.io.ByteArrayInputStream;
27 import java.io.ObjectInputStream;
30 public final class MDCKeySetExtractor {
31 private final Method getKeySetMethod;
32 public static final MDCKeySetExtractor INSTANCE =
33 new MDCKeySetExtractor();
36 private MDCKeySetExtractor() {
38 // log4j 1.2.15 and later will have method to get names
41 Method getMethod = null;
44 getMethod = LoggingEvent.class.getMethod(
45 "getPropertyKeySet", null);
46 } catch(Exception ex) {
49 getKeySetMethod = getMethod;
53 public Set getPropertyKeySet(final LoggingEvent event) throws Exception {
55 // MDC keys are not visible prior to log4j 1.2.15
58 if (getKeySetMethod != null) {
59 keySet = (Set) getKeySetMethod.invoke(event, null);
62 // for 1.2.14 and earlier could serialize and
63 // extract MDC content
64 ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
65 ObjectOutputStream os = new ObjectOutputStream(outBytes);
66 os.writeObject(event);
69 byte[] raw = outBytes.toByteArray();
71 // bytes 6 and 7 should be the length of the original classname
72 // should be the same as our substitute class name
73 final String subClassName = LogEvent.class.getName();
74 if (raw[6] == 0 || raw[7] == subClassName.length()) {
76 // manipulate stream to use our class name
78 for (int i = 0; i < subClassName.length(); i++) {
79 raw[8 + i] = (byte) subClassName.charAt(i);
81 ByteArrayInputStream inBytes = new ByteArrayInputStream(raw);
82 ObjectInputStream is = new ObjectInputStream(inBytes);
83 Object cracked = is.readObject();
84 if (cracked instanceof LogEvent) {
85 keySet = ((LogEvent) cracked).getPropertyKeySet();