View Javadoc
1   /*
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
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
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.
16   */
17  package org.apache.logging.log4j.web.appender;
18  
19  import java.io.Serializable;
20  
21  import javax.servlet.ServletContext;
22  
23  import org.apache.logging.log4j.core.Filter;
24  import org.apache.logging.log4j.core.Layout;
25  import org.apache.logging.log4j.core.LogEvent;
26  import org.apache.logging.log4j.core.appender.AbstractAppender;
27  import org.apache.logging.log4j.core.config.plugins.Plugin;
28  import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
29  import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
30  import org.apache.logging.log4j.core.layout.AbstractStringLayout;
31  import org.apache.logging.log4j.core.layout.PatternLayout;
32  import org.apache.logging.log4j.web.WebLoggerContextUtils;
33  
34  /**
35   * Logs using the ServletContext's log method
36   */
37  @Plugin(name = "Servlet", category = "Core", elementType = "appender", printObject = true)
38  public class ServletAppender extends AbstractAppender {
39  
40  	public static class Builder<B extends Builder<B>> extends AbstractAppender.Builder<B>
41  			implements org.apache.logging.log4j.core.util.Builder<ServletAppender> {
42  
43          @PluginBuilderAttribute
44          private boolean logThrowables;
45  
46  		@Override
47  		public ServletAppender build() {
48  			final String name = getName();
49  			if (name == null) {
50  				LOGGER.error("No name provided for ServletAppender");
51  			}
52  			final ServletContext servletContext = WebLoggerContextUtils.getServletContext();
53  			if (servletContext == null) {
54  				LOGGER.error("No servlet context is available");
55  				return null;
56  			}
57  			Layout<? extends Serializable> layout = getLayout();
58  			if (layout == null) {
59  				layout = PatternLayout.createDefaultLayout();
60  			} else if (!(layout instanceof AbstractStringLayout)) {
61  				LOGGER.error("Layout must be a StringLayout to log to ServletContext");
62  				return null;
63  			}
64  			return new ServletAppender(name, layout, getFilter(), servletContext, isIgnoreExceptions(), logThrowables);
65  		}
66  
67          /**
68           * Logs with {@link ServletContext#log(String, Throwable)} if true and with {@link ServletContext#log(String)} if false.
69           * 
70           * @return whether to log a Throwable with the servlet context.
71           */
72          public boolean isLogThrowables() {
73              return logThrowables;
74          }
75  
76          /**
77           * Logs with {@link ServletContext#log(String, Throwable)} if true and with {@link ServletContext#log(String)} if false.
78           */
79          public void setLogThrowables(boolean logThrowables) {
80              this.logThrowables = logThrowables;
81          }
82  
83  	}
84      
85      @PluginBuilderFactory
86      public static <B extends Builder<B>> B newBuilder() {
87          return new Builder<B>().asBuilder();
88      }
89  
90      private final ServletContext servletContext;
91      private boolean logThrowables;
92      
93      private ServletAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
94              final ServletContext servletContext, final boolean ignoreExceptions, final boolean logThrowables) {
95          super(name, filter, layout, ignoreExceptions);
96          this.servletContext = servletContext;
97          this.logThrowables = logThrowables;
98      }
99  
100     @Override
101     public void append(final LogEvent event) {
102         final String serialized = ((AbstractStringLayout) getLayout()).toSerializable(event);
103         if (logThrowables) {
104             servletContext.log(serialized, event.getThrown());
105         } else {
106             servletContext.log(serialized);
107         }
108     }
109 
110     /**
111      * Creates a Servlet Appender.
112      * @param layout The layout to use (required). Must extend {@link AbstractStringLayout}.
113      * @param filter The Filter or null.
114      * @param name The name of the Appender (required).
115      * @param ignoreExceptions If {@code true} (default) exceptions encountered when appending events are logged;
116      *                         otherwise they are propagated to the caller.
117      * @return The ServletAppender.
118      * @deprecated Use {@link #newBuilder()}.
119      */
120     @Deprecated
121     public static ServletAppender createAppender(Layout<? extends Serializable> layout, final Filter filter,
122             final String name, final boolean ignoreExceptions) {
123         // @formatter:off
124     	return newBuilder()
125     			.withFilter(filter)
126     			.withIgnoreExceptions(ignoreExceptions)
127     			.withLayout(layout)
128     			.withName(name)
129     			.build();
130     	// @formatter:on
131     }
132 
133 }