001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements. See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache license, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License. You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the license for the specific language governing permissions and
015     * limitations under the license.
016     */
017    package org.apache.logging.log4j.core.appender.db.jpa;
018    
019    import java.lang.reflect.Constructor;
020    
021    import org.apache.logging.log4j.core.Filter;
022    import org.apache.logging.log4j.core.LogEvent;
023    import org.apache.logging.log4j.core.appender.AbstractAppender;
024    import org.apache.logging.log4j.core.appender.db.AbstractDatabaseAppender;
025    import org.apache.logging.log4j.core.config.plugins.Plugin;
026    import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
027    import org.apache.logging.log4j.core.config.plugins.PluginElement;
028    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
029    import org.apache.logging.log4j.core.util.Booleans;
030    import org.apache.logging.log4j.core.util.Loader;
031    import org.apache.logging.log4j.util.Strings;
032    
033    /**
034     * This Appender writes logging events to a relational database using the Java Persistence API. It requires a
035     * pre-configured JPA persistence unit and a concrete implementation of the abstract
036     * {@link AbstractLogEventWrapperEntity} class decorated with JPA annotations.
037     *
038     * @see AbstractLogEventWrapperEntity
039     */
040    @Plugin(name = "JPA", category = "Core", elementType = "appender", printObject = true)
041    public final class JpaAppender extends AbstractDatabaseAppender<JpaDatabaseManager> {
042        private final String description;
043    
044        private JpaAppender(final String name, final Filter filter, final boolean ignoreExceptions,
045                final JpaDatabaseManager manager) {
046            super(name, filter, ignoreExceptions, manager);
047            this.description = this.getName() + "{ manager=" + this.getManager() + " }";
048        }
049    
050        @Override
051        public String toString() {
052            return this.description;
053        }
054    
055        /**
056         * Factory method for creating a JPA appender within the plugin manager.
057         *
058         * @param name The name of the appender.
059         * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
060         *               they are propagated to the caller.
061         * @param filter The filter, if any, to use.
062         * @param bufferSize If an integer greater than 0, this causes the appender to buffer log events and flush whenever
063         *                   the buffer reaches this size.
064         * @param entityClassName The fully qualified name of the concrete {@link AbstractLogEventWrapperEntity}
065         *                        implementation that has JPA annotations mapping it to a database table.
066         * @param persistenceUnitName The name of the JPA persistence unit that should be used for persisting log events.
067         * @return a new JPA appender.
068         */
069        @PluginFactory
070        public static JpaAppender createAppender(
071                @PluginAttribute("name") final String name,
072                @PluginAttribute("ignoreExceptions") final String ignore,
073                @PluginElement("Filter") final Filter filter,
074                @PluginAttribute("bufferSize") final String bufferSize,
075                @PluginAttribute("entityClassName") final String entityClassName,
076                @PluginAttribute("persistenceUnitName") final String persistenceUnitName) {
077            if (Strings.isEmpty(entityClassName) || Strings.isEmpty(persistenceUnitName)) {
078                LOGGER.error("Attributes entityClassName and persistenceUnitName are required for JPA Appender.");
079                return null;
080            }
081    
082            final int bufferSizeInt = AbstractAppender.parseInt(bufferSize, 0);
083            final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
084    
085            try {
086                @SuppressWarnings("unchecked")
087                final Class<? extends AbstractLogEventWrapperEntity> entityClass =
088                        (Class<? extends AbstractLogEventWrapperEntity>) Loader.loadClass(entityClassName);
089    
090                if (!AbstractLogEventWrapperEntity.class.isAssignableFrom(entityClass)) {
091                    LOGGER.error("Entity class [{}] does not extend AbstractLogEventWrapperEntity.", entityClassName);
092                    return null;
093                }
094    
095                try {
096                    entityClass.getConstructor();
097                } catch (final NoSuchMethodException e) {
098                    LOGGER.error("Entity class [{}] does not have a no-arg constructor. The JPA provider will reject it.",
099                            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    }