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 */ 017package org.apache.logging.log4j.core.layout; 018 019import java.nio.charset.Charset; 020import java.nio.charset.StandardCharsets; 021 022import org.apache.logging.log4j.core.LogEvent; 023 024/** 025 * Abstract base class for Layouts that result in a String. 026 */ 027public abstract class AbstractStringLayout extends AbstractLayout<String> { 028 029 private static final long serialVersionUID = 1L; 030 031 /** 032 * Converts a String to a byte[]. 033 * 034 * @param str 035 * if null, return null. 036 * @param charset 037 * if null, use the default charset. 038 * @return a byte[] 039 */ 040 static byte[] toBytes(final String str, final Charset charset) { 041 if (str != null) { 042 return str.getBytes(charset != null ? charset : Charset.defaultCharset()); 043 } 044 return null; 045 } 046 047 /** 048 * The charset for the formatted message. 049 */ 050 // TODO: Charset is not serializable. Implement read/writeObject() ? 051 private final Charset charset; 052 053 protected AbstractStringLayout(final Charset charset) { 054 this(charset, null, null); 055 } 056 057 protected AbstractStringLayout(final Charset charset, final byte[] header, final byte[] footer) { 058 super(header, footer); 059 this.charset = charset == null ? StandardCharsets.UTF_8 : charset; 060 } 061 062 protected byte[] getBytes(final String s) { 063 return s.getBytes(charset); 064 } 065 066 protected Charset getCharset() { 067 return charset; 068 } 069 070 /** 071 * @return The default content type for Strings. 072 */ 073 @Override 074 public String getContentType() { 075 return "text/plain"; 076 } 077 078 /** 079 * Formats the Log Event as a byte array. 080 * 081 * @param event 082 * The Log Event. 083 * @return The formatted event as a byte array. 084 */ 085 @Override 086 public byte[] toByteArray(final LogEvent event) { 087 return toSerializable(event).getBytes(charset); 088 } 089 090}