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 */
017package org.apache.logging.log4j.core.appender.db.jpa;
018
019import java.lang.reflect.Constructor;
020
021import org.apache.logging.log4j.core.Appender;
022import org.apache.logging.log4j.core.Core;
023import org.apache.logging.log4j.core.Filter;
024import org.apache.logging.log4j.core.LogEvent;
025import org.apache.logging.log4j.core.appender.AbstractAppender;
026import org.apache.logging.log4j.core.appender.db.AbstractDatabaseAppender;
027import org.apache.logging.log4j.core.config.plugins.Plugin;
028import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
029import org.apache.logging.log4j.core.config.plugins.PluginElement;
030import org.apache.logging.log4j.core.config.plugins.PluginFactory;
031import org.apache.logging.log4j.core.util.Booleans;
032import org.apache.logging.log4j.util.LoaderUtil;
033import org.apache.logging.log4j.util.Strings;
034
035/**
036 * This Appender writes logging events to a relational database using the Java Persistence API. It requires a
037 * pre-configured JPA persistence unit and a concrete implementation of the abstract
038 * {@link AbstractLogEventWrapperEntity} class decorated with JPA annotations.
039 *
040 * @see AbstractLogEventWrapperEntity
041 */
042@Plugin(name = "JPA", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
043public final class JpaAppender extends AbstractDatabaseAppender<JpaDatabaseManager> {
044
045    private final String description;
046
047    private JpaAppender(final String name, final Filter filter, final boolean ignoreExceptions,
048            final JpaDatabaseManager manager) {
049        super(name, filter, ignoreExceptions, manager);
050        this.description = this.getName() + "{ manager=" + this.getManager() + " }";
051    }
052
053    @Override
054    public String toString() {
055        return this.description;
056    }
057
058    /**
059     * Factory method for creating a JPA appender within the plugin manager.
060     *
061     * @param name The name of the appender.
062     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
063     *               they are propagated to the caller.
064     * @param filter The filter, if any, to use.
065     * @param bufferSize If an integer greater than 0, this causes the appender to buffer log events and flush whenever
066     *                   the buffer reaches this size.
067     * @param entityClassName The fully qualified name of the concrete {@link AbstractLogEventWrapperEntity}
068     *                        implementation that has JPA annotations mapping it to a database table.
069     * @param persistenceUnitName The name of the JPA persistence unit that should be used for persisting log events.
070     * @return a new JPA appender.
071     */
072    @PluginFactory
073    public static JpaAppender createAppender(
074            @PluginAttribute("name") final String name,
075            @PluginAttribute("ignoreExceptions") final String ignore,
076            @PluginElement("Filter") final Filter filter,
077            @PluginAttribute("bufferSize") final String bufferSize,
078            @PluginAttribute("entityClassName") final String entityClassName,
079            @PluginAttribute("persistenceUnitName") final String persistenceUnitName) {
080        if (Strings.isEmpty(entityClassName) || Strings.isEmpty(persistenceUnitName)) {
081            LOGGER.error("Attributes entityClassName and persistenceUnitName are required for JPA Appender.");
082            return null;
083        }
084
085        final int bufferSizeInt = AbstractAppender.parseInt(bufferSize, 0);
086        final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
087
088        try {
089            final Class<? extends AbstractLogEventWrapperEntity> entityClass =
090                LoaderUtil.loadClass(entityClassName).asSubclass(AbstractLogEventWrapperEntity.class);
091
092            try {
093                entityClass.getConstructor();
094            } catch (final NoSuchMethodException e) {
095                LOGGER.error("Entity class [{}] does not have a no-arg constructor. The JPA provider will reject it.",
096                        entityClassName);
097                return null;
098            }
099
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}