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.core.appender.db.jpa;
18  
19  import java.lang.reflect.Constructor;
20  
21  import org.apache.logging.log4j.core.Appender;
22  import org.apache.logging.log4j.core.Core;
23  import org.apache.logging.log4j.core.Filter;
24  import org.apache.logging.log4j.core.LogEvent;
25  import org.apache.logging.log4j.core.appender.AbstractAppender;
26  import org.apache.logging.log4j.core.appender.db.AbstractDatabaseAppender;
27  import org.apache.logging.log4j.core.config.plugins.Plugin;
28  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
29  import org.apache.logging.log4j.core.config.plugins.PluginElement;
30  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
31  import org.apache.logging.log4j.core.util.Booleans;
32  import org.apache.logging.log4j.util.LoaderUtil;
33  import org.apache.logging.log4j.util.Strings;
34  
35  /**
36   * This Appender writes logging events to a relational database using the Java Persistence API. It requires a
37   * pre-configured JPA persistence unit and a concrete implementation of the abstract
38   * {@link AbstractLogEventWrapperEntity} class decorated with JPA annotations.
39   *
40   * @see AbstractLogEventWrapperEntity
41   */
42  @Plugin(name = "JPA", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
43  public final class JpaAppender extends AbstractDatabaseAppender<JpaDatabaseManager> {
44  
45      private final String description;
46  
47      private JpaAppender(final String name, final Filter filter, final boolean ignoreExceptions,
48              final JpaDatabaseManager manager) {
49          super(name, filter, ignoreExceptions, manager);
50          this.description = this.getName() + "{ manager=" + this.getManager() + " }";
51      }
52  
53      @Override
54      public String toString() {
55          return this.description;
56      }
57  
58      /**
59       * Factory method for creating a JPA appender within the plugin manager.
60       *
61       * @param name The name of the appender.
62       * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
63       *               they are propagated to the caller.
64       * @param filter The filter, if any, to use.
65       * @param bufferSize If an integer greater than 0, this causes the appender to buffer log events and flush whenever
66       *                   the buffer reaches this size.
67       * @param entityClassName The fully qualified name of the concrete {@link AbstractLogEventWrapperEntity}
68       *                        implementation that has JPA annotations mapping it to a database table.
69       * @param persistenceUnitName The name of the JPA persistence unit that should be used for persisting log events.
70       * @return a new JPA appender.
71       */
72      @PluginFactory
73      public static JpaAppender createAppender(
74              @PluginAttribute("name") final String name,
75              @PluginAttribute("ignoreExceptions") final String ignore,
76              @PluginElement("Filter") final Filter filter,
77              @PluginAttribute("bufferSize") final String bufferSize,
78              @PluginAttribute("entityClassName") final String entityClassName,
79              @PluginAttribute("persistenceUnitName") final String persistenceUnitName) {
80          if (Strings.isEmpty(entityClassName) || Strings.isEmpty(persistenceUnitName)) {
81              LOGGER.error("Attributes entityClassName and persistenceUnitName are required for JPA Appender.");
82              return null;
83          }
84  
85          final int bufferSizeInt = AbstractAppender.parseInt(bufferSize, 0);
86          final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
87  
88          try {
89              final Class<? extends AbstractLogEventWrapperEntity> entityClass =
90                  LoaderUtil.loadClass(entityClassName).asSubclass(AbstractLogEventWrapperEntity.class);
91  
92              try {
93                  entityClass.getConstructor();
94              } catch (final NoSuchMethodException e) {
95                  LOGGER.error("Entity class [{}] does not have a no-arg constructor. The JPA provider will reject it.",
96                          entityClassName);
97                  return null;
98              }
99  
100             final Constructor<? extends AbstractLogEventWrapperEntity> entityConstructor =
101                     entityClass.getConstructor(LogEvent.class);
102 
103             final String managerName = "jpaManager{ description=" + name + ", bufferSize=" + bufferSizeInt
104                     + ", persistenceUnitName=" + persistenceUnitName + ", entityClass=" + entityClass.getName() + '}';
105 
106             final JpaDatabaseManager manager = JpaDatabaseManager.getJPADatabaseManager(
107                     managerName, bufferSizeInt, entityClass, entityConstructor, persistenceUnitName
108             );
109             if (manager == null) {
110                 return null;
111             }
112 
113             return new JpaAppender(name, filter, ignoreExceptions, manager);
114         } catch (final ClassNotFoundException e) {
115             LOGGER.error("Could not load entity class [{}].", entityClassName, e);
116             return null;
117         } catch (final NoSuchMethodException e) {
118             LOGGER.error("Entity class [{}] does not have a constructor with a single argument of type LogEvent.",
119                     entityClassName);
120             return null;
121         } catch (final ClassCastException e) {
122             LOGGER.error("Entity class [{}] does not extend AbstractLogEventWrapperEntity.", entityClassName);
123             return null;
124         }
125     }
126 }