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