001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.classic.pattern; 015 016import ch.qos.logback.classic.spi.ILoggingEvent; 017 018import java.util.Map; 019 020import static ch.qos.logback.core.util.OptionHelper.extractDefaultReplacement; 021 022public class MDCConverter extends ClassicConverter { 023 024 private String key; 025 private String defaultValue = ""; 026 027 @Override 028 public void start() { 029 String[] keyInfo = extractDefaultReplacement(getFirstOption()); 030 key = keyInfo[0]; 031 if (keyInfo[1] != null) { 032 defaultValue = keyInfo[1]; 033 } 034 super.start(); 035 } 036 037 @Override 038 public void stop() { 039 key = null; 040 super.stop(); 041 } 042 043 @Override 044 public String convert(ILoggingEvent event) { 045 Map<String, String> mdcPropertyMap = event.getMDCPropertyMap(); 046 047 if (mdcPropertyMap == null) { 048 return defaultValue; 049 } 050 051 if (key == null) { 052 return outputMDCForAllKeys(mdcPropertyMap); 053 } else { 054 055 String value = mdcPropertyMap.get(key); 056 if (value != null) { 057 return value; 058 } else { 059 return defaultValue; 060 } 061 } 062 } 063 064 /** 065 * if no key is specified, return all the values present in the MDC, in the 066 * format "k1=v1, k2=v2, ..." 067 */ 068 private String outputMDCForAllKeys(Map<String, String> mdcPropertyMap) { 069 StringBuilder buf = new StringBuilder(); 070 boolean first = true; 071 for (Map.Entry<String, String> entry : mdcPropertyMap.entrySet()) { 072 if (first) { 073 first = false; 074 } else { 075 buf.append(", "); 076 } 077 // format: key0=value0, key1=value1 078 buf.append(entry.getKey()).append('=').append(entry.getValue()); 079 } 080 return buf.toString(); 081 } 082 083 /** 084 * PrefixCompositeConverter needs the key 085 * 086 * @return 087 */ 088 public String getKey() { 089 return key; 090 } 091 092}