You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by gg...@apache.org on 2018/10/30 02:15:27 UTC

logging-log4j2 git commit: Add JdbcDatabaseManager.getConnectionSource().

Repository: logging-log4j2
Updated Branches:
  refs/heads/release-2.x 74bc7e250 -> d39546d77


Add JdbcDatabaseManager.getConnectionSource().

Also sort members.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/d39546d7
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/d39546d7
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/d39546d7

Branch: refs/heads/release-2.x
Commit: d39546d775fbe6a31d042547930c38668e505d38
Parents: 74bc7e2
Author: Gary Gregory <ga...@gmail.com>
Authored: Mon Oct 29 20:15:24 2018 -0600
Committer: Gary Gregory <ga...@gmail.com>
Committed: Mon Oct 29 20:15:24 2018 -0600

----------------------------------------------------------------------
 .../appender/db/jdbc/JdbcDatabaseManager.java   | 444 ++++++++++---------
 1 file changed, 224 insertions(+), 220 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/d39546d7/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcDatabaseManager.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcDatabaseManager.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcDatabaseManager.java
index 3ed82e2..a026a3b 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcDatabaseManager.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcDatabaseManager.java
@@ -54,18 +54,172 @@ import org.apache.logging.log4j.util.Strings;
  */
 public final class JdbcDatabaseManager extends AbstractDatabaseManager {
 
+    /**
+     * Encapsulates data that {@link JdbcDatabaseManagerFactory} uses to create managers.
+     */
+    private static final class FactoryData extends AbstractDatabaseManager.AbstractFactoryData {
+        private final ConnectionSource connectionSource;
+        private final String tableName;
+        private final ColumnConfig[] columnConfigs;
+        private final ColumnMapping[] columnMappings;
+
+        protected FactoryData(final int bufferSize, final Layout<? extends Serializable> layout,
+                final ConnectionSource connectionSource, final String tableName, final ColumnConfig[] columnConfigs,
+                final ColumnMapping[] columnMappings) {
+            super(bufferSize, layout);
+            this.connectionSource = connectionSource;
+            this.tableName = tableName;
+            this.columnConfigs = columnConfigs;
+            this.columnMappings = columnMappings;
+        }
+    }
+
+    /**
+     * Creates managers.
+     */
+    private static final class JdbcDatabaseManagerFactory implements ManagerFactory<JdbcDatabaseManager, FactoryData> {
+        
+        private static final char PARAMETER_MARKER = '?';
+
+        @Override
+        public JdbcDatabaseManager createManager(final String name, final FactoryData data) {
+            final StringBuilder sb = new StringBuilder("INSERT INTO ").append(data.tableName).append(" (");
+            // so this gets a little more complicated now that there are two ways to configure column mappings, but
+            // both mappings follow the same exact pattern for the prepared statement
+            int i = 1;
+            for (final ColumnMapping mapping : data.columnMappings) {
+                final  String mappingName = mapping.getName();
+                logger().trace("Adding INSERT ColumnMapping[{}]: {}={} ", i++, mappingName, mapping);
+                sb.append(mappingName).append(',');
+            }
+            for (final ColumnConfig config : data.columnConfigs) {
+                sb.append(config.getColumnName()).append(',');
+            }
+            // at least one of those arrays is guaranteed to be non-empty
+            sb.setCharAt(sb.length() - 1, ')');
+            sb.append(" VALUES (");
+            i = 1;
+            final List<ColumnMapping> columnMappings = new ArrayList<>(data.columnMappings.length);
+            for (final ColumnMapping mapping : data.columnMappings) {
+                final String mappingName = mapping.getName();
+                if (Strings.isNotEmpty(mapping.getLiteralValue())) {
+                    logger().trace("Adding INSERT VALUES literal for ColumnMapping[{}]: {}={} ", i, mappingName, mapping.getLiteralValue());
+                    sb.append(mapping.getLiteralValue());
+                } else if (Strings.isNotEmpty(mapping.getParameter())) {
+                    logger().trace("Adding INSERT VALUES parameter for ColumnMapping[{}]: {}={} ", i, mappingName, mapping.getParameter());
+                    sb.append(mapping.getParameter());
+                    columnMappings.add(mapping);
+                } else {
+                    logger().trace("Adding INSERT VALUES parameter marker for ColumnMapping[{}]: {}={} ", i, mappingName, PARAMETER_MARKER);
+                    sb.append(PARAMETER_MARKER);
+                    columnMappings.add(mapping);
+                }
+                sb.append(',');
+                i++;
+            }
+            final List<ColumnConfig> columnConfigs = new ArrayList<>(data.columnConfigs.length);
+            for (final ColumnConfig config : data.columnConfigs) {
+                if (Strings.isNotEmpty(config.getLiteralValue())) {
+                    sb.append(config.getLiteralValue());
+                } else {
+                    sb.append(PARAMETER_MARKER);
+                    columnConfigs.add(config);
+                }
+                sb.append(',');
+            }
+            // at least one of those arrays is guaranteed to be non-empty
+            sb.setCharAt(sb.length() - 1, ')');
+            final String sqlStatement = sb.toString();
+
+            return new JdbcDatabaseManager(name, data.getBufferSize(), data.connectionSource, sqlStatement,
+                columnConfigs, columnMappings);
+        }
+    }
     private static final JdbcDatabaseManagerFactory INSTANCE = new JdbcDatabaseManagerFactory();
+    private static JdbcDatabaseManagerFactory getFactory() {
+        return INSTANCE;
+    }
+    /**
+     * Creates a JDBC manager for use within the {@link JdbcAppender}, or returns a suitable one if it already exists.
+     *
+     * @param name The name of the manager, which should include connection details and hashed passwords where possible.
+     * @param bufferSize The size of the log event buffer.
+     * @param connectionSource The source for connections to the database.
+     * @param tableName The name of the database table to insert log events into.
+     * @param columnConfigs Configuration information about the log table columns.
+     * @return a new or existing JDBC manager as applicable.
+     * @deprecated use {@link #getManager(String, int, Layout, ConnectionSource, String, ColumnConfig[], ColumnMapping[])}
+     */
+    @Deprecated
+    public static JdbcDatabaseManager getJDBCDatabaseManager(final String name, final int bufferSize,
+                                                             final ConnectionSource connectionSource,
+                                                             final String tableName,
+                                                             final ColumnConfig[] columnConfigs) {
+
+        return getManager(name,
+            new FactoryData(bufferSize, null, connectionSource, tableName, columnConfigs, new ColumnMapping[0]),
+            getFactory());
+    }
 
+    /**
+     * Creates a JDBC manager for use within the {@link JdbcAppender}, or returns a suitable one if it already exists.
+     *
+     * @param name The name of the manager, which should include connection details and hashed passwords where possible.
+     * @param bufferSize The size of the log event buffer.
+     * @param connectionSource The source for connections to the database.
+     * @param tableName The name of the database table to insert log events into.
+     * @param columnConfigs Configuration information about the log table columns.
+     * @param columnMappings column mapping configuration (including type conversion).
+     * @return a new or existing JDBC manager as applicable.
+     * @deprecated use {@link #getManager(String, int, Layout, ConnectionSource, String, ColumnConfig[], ColumnMapping[])}
+     */
+    @Deprecated
+    public static JdbcDatabaseManager getManager(final String name,
+                                                 final int bufferSize,
+                                                 final ConnectionSource connectionSource,
+                                                 final String tableName,
+                                                 final ColumnConfig[] columnConfigs,
+                                                 final ColumnMapping[] columnMappings) {
+        return getManager(name, new FactoryData(bufferSize, null, connectionSource, tableName, columnConfigs, columnMappings),
+            getFactory());
+    }
+    /**
+     * Creates a JDBC manager for use within the {@link JdbcAppender}, or returns a suitable one if it already exists.
+     *
+     * @param name The name of the manager, which should include connection details and hashed passwords where possible.
+     * @param bufferSize The size of the log event buffer.
+     * @param layout The Appender-level layout
+     * @param connectionSource The source for connections to the database.
+     * @param tableName The name of the database table to insert log events into.
+     * @param columnConfigs Configuration information about the log table columns.
+     * @param columnMappings column mapping configuration (including type conversion).
+     * @return a new or existing JDBC manager as applicable.
+     */
+    public static JdbcDatabaseManager getManager(final String name,
+                                                 final int bufferSize,
+                                                 final Layout<? extends Serializable> layout,
+                                                 final ConnectionSource connectionSource,
+                                                 final String tableName,
+                                                 final ColumnConfig[] columnConfigs,
+                                                 final ColumnMapping[] columnMappings) {
+        return getManager(name, new FactoryData(bufferSize, layout, connectionSource, tableName, columnConfigs, columnMappings),
+            getFactory());
+    }
     // NOTE: prepared statements are prepared in this order: column mappings, then column configs
     private final List<ColumnMapping> columnMappings;
+
     private final List<ColumnConfig> columnConfigs;
+
     private final ConnectionSource connectionSource;
+
     private final String sqlStatement;
 
     private Connection connection;
+    
     private PreparedStatement statement;
+    
     private boolean isBatchSupported;
-
+    
     private JdbcDatabaseManager(final String name, final int bufferSize, final ConnectionSource connectionSource,
                                 final String sqlStatement, final List<ColumnConfig> columnConfigs,
                                 final List<ColumnMapping> columnMappings) {
@@ -77,26 +231,42 @@ public final class JdbcDatabaseManager extends AbstractDatabaseManager {
     }
 
     @Override
-	protected void startupInternal() throws Exception {
-		this.connection = this.connectionSource.getConnection();
-		try {
-			final DatabaseMetaData metaData = this.connection.getMetaData();
-			this.isBatchSupported = metaData.supportsBatchUpdates();
-		} finally {
-			logger().debug("Closing Connection {}", this.connection);
-			Closer.closeSilently(this.connection);
-		}
-	}
+    protected boolean commitAndClose() {
+        boolean closed = true;
+        try {
+            if (this.connection != null && !this.connection.isClosed()) {
+                if (this.isBatchSupported) {
+                    logger().debug("Executing batch PreparedStatement {}", this.statement);
+                    int[] result = this.statement.executeBatch();
+                    logger().debug("Batch result: {}", Arrays.toString(result));
+                }
+                logger().debug("Committing Connection {}", this.connection);
+                this.connection.commit();
+            }
+        } catch (final SQLException e) {
+            throw new AppenderLoggingException("Failed to commit transaction logging event or flushing buffer.", e);
+        } finally {
+            try {
+                logger().debug("Closing PreparedStatement {}", this.statement);
+                Closer.close(this.statement);
+            } catch (final Exception e) {
+                logWarn("Failed to close SQL statement logging event or flushing buffer", e);
+                closed = false;
+            } finally {
+                this.statement = null;
+            }
 
-    @Override
-    protected boolean shutdownInternal() {
-        if (this.connection != null || this.statement != null) {
-            return this.commitAndClose();
-        }
-        if (connectionSource != null) {
-            connectionSource.stop();
+            try {
+                logger().debug("Closing Connection {}", this.connection);
+                Closer.close(this.connection);
+            } catch (final Exception e) {
+                logWarn("Failed to close database connection logging event or flushing buffer", e);
+                closed = false;
+            } finally {
+                this.connection = null;
+            }
         }
-        return true;
+        return closed;
     }
 
     @Override
@@ -111,17 +281,15 @@ public final class JdbcDatabaseManager extends AbstractDatabaseManager {
                     "Cannot write logging event or flush buffer; JDBC manager cannot connect to the database.", e);
         }
     }
-    
+
+    public ConnectionSource getConnectionSource() {
+        return connectionSource;
+    }
+
     public String getSqlStatement() {
         return sqlStatement;
     }
-    
-    @Deprecated
-    @Override
-    protected void writeInternal(final LogEvent event) {
-        writeInternal(event, null);
-    }
-    
+
     private void setFields(final MapMessage<?, ?> mapMessage) throws SQLException {
         final IndexedReadOnlyStringMap map = mapMessage.getIndexedReadOnlyStringMap();
         final String simpleName = statement.getClass().getName();
@@ -140,6 +308,35 @@ public final class JdbcDatabaseManager extends AbstractDatabaseManager {
     }
 
     @Override
+    protected boolean shutdownInternal() {
+        if (this.connection != null || this.statement != null) {
+            return this.commitAndClose();
+        }
+        if (connectionSource != null) {
+            connectionSource.stop();
+        }
+        return true;
+    }
+
+    @Override
+	protected void startupInternal() throws Exception {
+		this.connection = this.connectionSource.getConnection();
+		try {
+			final DatabaseMetaData metaData = this.connection.getMetaData();
+			this.isBatchSupported = metaData.supportsBatchUpdates();
+		} finally {
+			logger().debug("Closing Connection {}", this.connection);
+			Closer.closeSilently(this.connection);
+		}
+	}
+
+    @Deprecated
+    @Override
+    protected void writeInternal(final LogEvent event) {
+        writeInternal(event, null);
+    }
+
+    @Override
     protected void writeInternal(final LogEvent event, final Serializable serializable) {
         StringReader reader = null;
         try {
@@ -219,197 +416,4 @@ public final class JdbcDatabaseManager extends AbstractDatabaseManager {
         }
     }
 
-    @Override
-    protected boolean commitAndClose() {
-        boolean closed = true;
-        try {
-            if (this.connection != null && !this.connection.isClosed()) {
-                if (this.isBatchSupported) {
-                    logger().debug("Executing batch PreparedStatement {}", this.statement);
-                    int[] result = this.statement.executeBatch();
-                    logger().debug("Batch result: {}", Arrays.toString(result));
-                }
-                logger().debug("Committing Connection {}", this.connection);
-                this.connection.commit();
-            }
-        } catch (final SQLException e) {
-            throw new AppenderLoggingException("Failed to commit transaction logging event or flushing buffer.", e);
-        } finally {
-            try {
-                logger().debug("Closing PreparedStatement {}", this.statement);
-                Closer.close(this.statement);
-            } catch (final Exception e) {
-                logWarn("Failed to close SQL statement logging event or flushing buffer", e);
-                closed = false;
-            } finally {
-                this.statement = null;
-            }
-
-            try {
-                logger().debug("Closing Connection {}", this.connection);
-                Closer.close(this.connection);
-            } catch (final Exception e) {
-                logWarn("Failed to close database connection logging event or flushing buffer", e);
-                closed = false;
-            } finally {
-                this.connection = null;
-            }
-        }
-        return closed;
-    }
-
-    /**
-     * Creates a JDBC manager for use within the {@link JdbcAppender}, or returns a suitable one if it already exists.
-     *
-     * @param name The name of the manager, which should include connection details and hashed passwords where possible.
-     * @param bufferSize The size of the log event buffer.
-     * @param connectionSource The source for connections to the database.
-     * @param tableName The name of the database table to insert log events into.
-     * @param columnConfigs Configuration information about the log table columns.
-     * @return a new or existing JDBC manager as applicable.
-     * @deprecated use {@link #getManager(String, int, Layout, ConnectionSource, String, ColumnConfig[], ColumnMapping[])}
-     */
-    @Deprecated
-    public static JdbcDatabaseManager getJDBCDatabaseManager(final String name, final int bufferSize,
-                                                             final ConnectionSource connectionSource,
-                                                             final String tableName,
-                                                             final ColumnConfig[] columnConfigs) {
-
-        return getManager(name,
-            new FactoryData(bufferSize, null, connectionSource, tableName, columnConfigs, new ColumnMapping[0]),
-            getFactory());
-    }
-
-    /**
-     * Creates a JDBC manager for use within the {@link JdbcAppender}, or returns a suitable one if it already exists.
-     *
-     * @param name The name of the manager, which should include connection details and hashed passwords where possible.
-     * @param bufferSize The size of the log event buffer.
-     * @param connectionSource The source for connections to the database.
-     * @param tableName The name of the database table to insert log events into.
-     * @param columnConfigs Configuration information about the log table columns.
-     * @param columnMappings column mapping configuration (including type conversion).
-     * @return a new or existing JDBC manager as applicable.
-     * @deprecated use {@link #getManager(String, int, Layout, ConnectionSource, String, ColumnConfig[], ColumnMapping[])}
-     */
-    @Deprecated
-    public static JdbcDatabaseManager getManager(final String name,
-                                                 final int bufferSize,
-                                                 final ConnectionSource connectionSource,
-                                                 final String tableName,
-                                                 final ColumnConfig[] columnConfigs,
-                                                 final ColumnMapping[] columnMappings) {
-        return getManager(name, new FactoryData(bufferSize, null, connectionSource, tableName, columnConfigs, columnMappings),
-            getFactory());
-    }
-
-    /**
-     * Creates a JDBC manager for use within the {@link JdbcAppender}, or returns a suitable one if it already exists.
-     *
-     * @param name The name of the manager, which should include connection details and hashed passwords where possible.
-     * @param bufferSize The size of the log event buffer.
-     * @param layout The Appender-level layout
-     * @param connectionSource The source for connections to the database.
-     * @param tableName The name of the database table to insert log events into.
-     * @param columnConfigs Configuration information about the log table columns.
-     * @param columnMappings column mapping configuration (including type conversion).
-     * @return a new or existing JDBC manager as applicable.
-     */
-    public static JdbcDatabaseManager getManager(final String name,
-                                                 final int bufferSize,
-                                                 final Layout<? extends Serializable> layout,
-                                                 final ConnectionSource connectionSource,
-                                                 final String tableName,
-                                                 final ColumnConfig[] columnConfigs,
-                                                 final ColumnMapping[] columnMappings) {
-        return getManager(name, new FactoryData(bufferSize, layout, connectionSource, tableName, columnConfigs, columnMappings),
-            getFactory());
-    }
-
-    private static JdbcDatabaseManagerFactory getFactory() {
-        return INSTANCE;
-    }
-
-    /**
-     * Encapsulates data that {@link JdbcDatabaseManagerFactory} uses to create managers.
-     */
-    private static final class FactoryData extends AbstractDatabaseManager.AbstractFactoryData {
-        private final ConnectionSource connectionSource;
-        private final String tableName;
-        private final ColumnConfig[] columnConfigs;
-        private final ColumnMapping[] columnMappings;
-
-        protected FactoryData(final int bufferSize, final Layout<? extends Serializable> layout,
-                final ConnectionSource connectionSource, final String tableName, final ColumnConfig[] columnConfigs,
-                final ColumnMapping[] columnMappings) {
-            super(bufferSize, layout);
-            this.connectionSource = connectionSource;
-            this.tableName = tableName;
-            this.columnConfigs = columnConfigs;
-            this.columnMappings = columnMappings;
-        }
-    }
-
-    /**
-     * Creates managers.
-     */
-    private static final class JdbcDatabaseManagerFactory implements ManagerFactory<JdbcDatabaseManager, FactoryData> {
-        
-        private static final char PARAMETER_MARKER = '?';
-
-        @Override
-        public JdbcDatabaseManager createManager(final String name, final FactoryData data) {
-            final StringBuilder sb = new StringBuilder("INSERT INTO ").append(data.tableName).append(" (");
-            // so this gets a little more complicated now that there are two ways to configure column mappings, but
-            // both mappings follow the same exact pattern for the prepared statement
-            int i = 1;
-            for (final ColumnMapping mapping : data.columnMappings) {
-                final  String mappingName = mapping.getName();
-                logger().trace("Adding INSERT ColumnMapping[{}]: {}={} ", i++, mappingName, mapping);
-                sb.append(mappingName).append(',');
-            }
-            for (final ColumnConfig config : data.columnConfigs) {
-                sb.append(config.getColumnName()).append(',');
-            }
-            // at least one of those arrays is guaranteed to be non-empty
-            sb.setCharAt(sb.length() - 1, ')');
-            sb.append(" VALUES (");
-            i = 1;
-            final List<ColumnMapping> columnMappings = new ArrayList<>(data.columnMappings.length);
-            for (final ColumnMapping mapping : data.columnMappings) {
-                final String mappingName = mapping.getName();
-                if (Strings.isNotEmpty(mapping.getLiteralValue())) {
-                    logger().trace("Adding INSERT VALUES literal for ColumnMapping[{}]: {}={} ", i, mappingName, mapping.getLiteralValue());
-                    sb.append(mapping.getLiteralValue());
-                } else if (Strings.isNotEmpty(mapping.getParameter())) {
-                    logger().trace("Adding INSERT VALUES parameter for ColumnMapping[{}]: {}={} ", i, mappingName, mapping.getParameter());
-                    sb.append(mapping.getParameter());
-                    columnMappings.add(mapping);
-                } else {
-                    logger().trace("Adding INSERT VALUES parameter marker for ColumnMapping[{}]: {}={} ", i, mappingName, PARAMETER_MARKER);
-                    sb.append(PARAMETER_MARKER);
-                    columnMappings.add(mapping);
-                }
-                sb.append(',');
-                i++;
-            }
-            final List<ColumnConfig> columnConfigs = new ArrayList<>(data.columnConfigs.length);
-            for (final ColumnConfig config : data.columnConfigs) {
-                if (Strings.isNotEmpty(config.getLiteralValue())) {
-                    sb.append(config.getLiteralValue());
-                } else {
-                    sb.append(PARAMETER_MARKER);
-                    columnConfigs.add(config);
-                }
-                sb.append(',');
-            }
-            // at least one of those arrays is guaranteed to be non-empty
-            sb.setCharAt(sb.length() - 1, ')');
-            final String sqlStatement = sb.toString();
-
-            return new JdbcDatabaseManager(name, data.getBufferSize(), data.connectionSource, sqlStatement,
-                columnConfigs, columnMappings);
-        }
-    }
-
 }