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