001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.core.pattern; 018 019 import org.apache.logging.log4j.core.LogEvent; 020 import org.apache.logging.log4j.core.config.Configuration; 021 import org.apache.logging.log4j.core.config.plugins.Plugin; 022 import org.apache.logging.log4j.message.Message; 023 import org.apache.logging.log4j.message.MultiformatMessage; 024 025 /** 026 * Returns the event's rendered message in a StringBuilder. 027 */ 028 @Plugin(name = "MessagePatternConverter", category = PatternConverter.CATEGORY) 029 @ConverterKeys({ "m", "msg", "message" }) 030 public final class MessagePatternConverter extends LogEventPatternConverter { 031 032 private final String[] formats; 033 034 private final Configuration config; 035 036 /** 037 * Private constructor. 038 * @param options options, may be null. 039 */ 040 private MessagePatternConverter(final Configuration config, final String[] options) { 041 super("Message", "message"); 042 formats = options; 043 this.config = config; 044 } 045 046 /** 047 * Obtains an instance of pattern converter. 048 * 049 * @param config The Configuration. 050 * @param options options, may be null. 051 * @return instance of pattern converter. 052 */ 053 public static MessagePatternConverter newInstance(final Configuration config, final String[] options) { 054 return new MessagePatternConverter(config, options); 055 } 056 057 /** 058 * {@inheritDoc} 059 */ 060 @Override 061 public void format(final LogEvent event, final StringBuilder toAppendTo) { 062 final Message msg = event.getMessage(); 063 if (msg != null) { 064 String result; 065 if (msg instanceof MultiformatMessage) { 066 result = ((MultiformatMessage) msg).getFormattedMessage(formats); 067 } else { 068 result = msg.getFormattedMessage(); 069 } 070 if (result != null) { 071 toAppendTo.append(config != null && result.contains("${") ? 072 config.getStrSubstitutor().replace(event, result) : result); 073 } else { 074 toAppendTo.append("null"); 075 } 076 } 077 } 078 }