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