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