Search in sources :

Example 6 with PluginFactory

use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project logging-log4j2 by apache.

the class MongoDbProvider method createNoSqlProvider.

/**
     * Factory method for creating a MongoDB provider within the plugin manager.
     *
     * @param collectionName The name of the MongoDB collection to which log events should be written.
     * @param writeConcernConstant The {@link WriteConcern} constant to control writing details, defaults to
     *                             {@link WriteConcern#ACKNOWLEDGED}.
     * @param writeConcernConstantClassName The name of a class containing the aforementioned static WriteConcern
     *                                      constant. Defaults to {@link WriteConcern}.
     * @param databaseName The name of the MongoDB database containing the collection to which log events should be
     *                     written. Mutually exclusive with {@code factoryClassName&factoryMethodName!=null}.
     * @param server The host name of the MongoDB server, defaults to localhost and mutually exclusive with
     *               {@code factoryClassName&factoryMethodName!=null}.
     * @param port The port the MongoDB server is listening on, defaults to the default MongoDB port and mutually
     *             exclusive with {@code factoryClassName&factoryMethodName!=null}.
     * @param userName The username to authenticate against the MongoDB server with.
     * @param password The password to authenticate against the MongoDB server with.
     * @param factoryClassName A fully qualified class name containing a static factory method capable of returning a
     *                         {@link DB} or a {@link MongoClient}.
     * @param factoryMethodName The name of the public static factory method belonging to the aforementioned factory
     *                          class.
     * @return a new MongoDB provider.
     */
@PluginFactory
public static MongoDbProvider createNoSqlProvider(@PluginAttribute("collectionName") final String collectionName, @PluginAttribute("writeConcernConstant") final String writeConcernConstant, @PluginAttribute("writeConcernConstantClass") final String writeConcernConstantClassName, @PluginAttribute("databaseName") final String databaseName, @PluginAttribute(value = "server", defaultString = "localhost") @ValidHost final String server, @PluginAttribute(value = "port", defaultString = "" + DEFAULT_PORT) @ValidPort final String port, @PluginAttribute("userName") final String userName, @PluginAttribute(value = "password", sensitive = true) final String password, @PluginAttribute("factoryClassName") final String factoryClassName, @PluginAttribute("factoryMethodName") final String factoryMethodName) {
    DB database;
    String description;
    if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) {
        try {
            final Class<?> factoryClass = LoaderUtil.loadClass(factoryClassName);
            final Method method = factoryClass.getMethod(factoryMethodName);
            final Object object = method.invoke(null);
            if (object instanceof DB) {
                database = (DB) object;
            } else if (object instanceof MongoClient) {
                if (Strings.isNotEmpty(databaseName)) {
                    database = ((MongoClient) object).getDB(databaseName);
                } else {
                    LOGGER.error("The factory method [{}.{}()] returned a MongoClient so the database name is " + "required.", factoryClassName, factoryMethodName);
                    return null;
                }
            } else if (object == null) {
                LOGGER.error("The factory method [{}.{}()] returned null.", factoryClassName, factoryMethodName);
                return null;
            } else {
                LOGGER.error("The factory method [{}.{}()] returned an unsupported type [{}].", factoryClassName, factoryMethodName, object.getClass().getName());
                return null;
            }
            description = "database=" + database.getName();
            final List<ServerAddress> addresses = database.getMongo().getAllAddress();
            if (addresses.size() == 1) {
                description += ", server=" + addresses.get(0).getHost() + ", port=" + addresses.get(0).getPort();
            } else {
                description += ", servers=[";
                for (final ServerAddress address : addresses) {
                    description += " { " + address.getHost() + ", " + address.getPort() + " } ";
                }
                description += "]";
            }
        } catch (final ClassNotFoundException e) {
            LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e);
            return null;
        } catch (final NoSuchMethodException e) {
            LOGGER.error("The factory class [{}] does not have a no-arg method named [{}].", factoryClassName, factoryMethodName, e);
            return null;
        } catch (final Exception e) {
            LOGGER.error("The factory method [{}.{}()] could not be invoked.", factoryClassName, factoryMethodName, e);
            return null;
        }
    } else if (Strings.isNotEmpty(databaseName)) {
        final List<MongoCredential> credentials = new ArrayList<>();
        description = "database=" + databaseName;
        if (Strings.isNotEmpty(userName) && Strings.isNotEmpty(password)) {
            description += ", username=" + userName + ", passwordHash=" + NameUtil.md5(password + MongoDbProvider.class.getName());
            credentials.add(MongoCredential.createCredential(userName, databaseName, password.toCharArray()));
        }
        try {
            final int portInt = TypeConverters.convert(port, int.class, DEFAULT_PORT);
            description += ", server=" + server + ", port=" + portInt;
            database = new MongoClient(new ServerAddress(server, portInt), credentials).getDB(databaseName);
        } catch (final Exception e) {
            LOGGER.error("Failed to obtain a database instance from the MongoClient at server [{}] and " + "port [{}].", server, port);
            return null;
        }
    } else {
        LOGGER.error("No factory method was provided so the database name is required.");
        return null;
    }
    try {
        // Check if the database actually requires authentication
        database.getCollectionNames();
    } catch (final Exception e) {
        LOGGER.error("The database is not up, or you are not authenticated, try supplying a username and password to the MongoDB provider.", e);
        return null;
    }
    final WriteConcern writeConcern = toWriteConcern(writeConcernConstant, writeConcernConstantClassName);
    return new MongoDbProvider(database, writeConcern, collectionName, description);
}
Also used : ServerAddress(com.mongodb.ServerAddress) Method(java.lang.reflect.Method) MongoClient(com.mongodb.MongoClient) WriteConcern(com.mongodb.WriteConcern) ArrayList(java.util.ArrayList) List(java.util.List) DB(com.mongodb.DB) PluginFactory(org.apache.logging.log4j.core.config.plugins.PluginFactory)

Example 7 with PluginFactory

use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project logging-log4j2 by apache.

the class JeroMqAppender method createAppender.

// The ZMQ.Socket class has other set methods that we do not cover because
// they throw unsupported operation exceptions.
@PluginFactory
public static JeroMqAppender createAppender(// @formatter:off
@Required(message = "No name provided for JeroMqAppender") @PluginAttribute("name") final String name, @PluginElement("Layout") Layout<?> layout, @PluginElement("Filter") final Filter filter, @PluginElement("Properties") final Property[] properties, // Super attributes
@PluginAttribute("ignoreExceptions") final boolean ignoreExceptions, // ZMQ attributes; defaults picked from zmq.Options.
@PluginAttribute(value = "affinity", defaultLong = 0) final long affinity, @PluginAttribute(value = "backlog", defaultLong = DEFAULT_BACKLOG) final long backlog, @PluginAttribute(value = "delayAttachOnConnect") final boolean delayAttachOnConnect, @PluginAttribute(value = "identity") final byte[] identity, @PluginAttribute(value = "ipv4Only", defaultBoolean = true) final boolean ipv4Only, @PluginAttribute(value = "linger", defaultLong = -1) final long linger, @PluginAttribute(value = "maxMsgSize", defaultLong = -1) final long maxMsgSize, @PluginAttribute(value = "rcvHwm", defaultLong = DEFAULT_RCV_HWM) final long rcvHwm, @PluginAttribute(value = "receiveBufferSize", defaultLong = 0) final long receiveBufferSize, @PluginAttribute(value = "receiveTimeOut", defaultLong = -1) final int receiveTimeOut, @PluginAttribute(value = "reconnectIVL", defaultLong = DEFAULT_IVL) final long reconnectIVL, @PluginAttribute(value = "reconnectIVLMax", defaultLong = 0) final long reconnectIVLMax, @PluginAttribute(value = "sendBufferSize", defaultLong = 0) final long sendBufferSize, @PluginAttribute(value = "sendTimeOut", defaultLong = -1) final int sendTimeOut, @PluginAttribute(value = "sndHwm", defaultLong = DEFAULT_SND_HWM) final long sndHwm, @PluginAttribute(value = "tcpKeepAlive", defaultInt = -1) final int tcpKeepAlive, @PluginAttribute(value = "tcpKeepAliveCount", defaultLong = -1) final long tcpKeepAliveCount, @PluginAttribute(value = "tcpKeepAliveIdle", defaultLong = -1) final long tcpKeepAliveIdle, @PluginAttribute(value = "tcpKeepAliveInterval", defaultLong = -1) final long tcpKeepAliveInterval, @PluginAttribute(value = "xpubVerbose") final boolean xpubVerbose) // @formatter:on
{
    if (layout == null) {
        layout = PatternLayout.createDefaultLayout();
    }
    List<String> endpoints;
    if (properties == null) {
        endpoints = new ArrayList<>(0);
    } else {
        endpoints = new ArrayList<>(properties.length);
        for (final Property property : properties) {
            if ("endpoint".equalsIgnoreCase(property.getName())) {
                final String value = property.getValue();
                if (Strings.isNotEmpty(value)) {
                    endpoints.add(value);
                }
            }
        }
    }
    LOGGER.debug("Creating JeroMqAppender with name={}, filter={}, layout={}, ignoreExceptions={}, endpoints={}", name, filter, layout, ignoreExceptions, endpoints);
    return new JeroMqAppender(name, filter, layout, ignoreExceptions, endpoints, affinity, backlog, delayAttachOnConnect, identity, ipv4Only, linger, maxMsgSize, rcvHwm, receiveBufferSize, receiveTimeOut, reconnectIVL, reconnectIVLMax, sendBufferSize, sendTimeOut, sndHwm, tcpKeepAlive, tcpKeepAliveCount, tcpKeepAliveIdle, tcpKeepAliveInterval, xpubVerbose);
}
Also used : Property(org.apache.logging.log4j.core.config.Property) PluginFactory(org.apache.logging.log4j.core.config.plugins.PluginFactory)

Example 8 with PluginFactory

use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project logging-log4j2 by apache.

the class SmtpAppender method createAppender.

/**
     * Create a SmtpAppender.
     *
     * @param name
     *            The name of the Appender.
     * @param to
     *            The comma-separated list of recipient email addresses.
     * @param cc
     *            The comma-separated list of CC email addresses.
     * @param bcc
     *            The comma-separated list of BCC email addresses.
     * @param from
     *            The email address of the sender.
     * @param replyTo
     *            The comma-separated list of reply-to email addresses.
     * @param subject The subject of the email message.
     * @param smtpProtocol The SMTP transport protocol (such as "smtps", defaults to "smtp").
     * @param smtpHost
     *            The SMTP hostname to send to.
     * @param smtpPortStr
     *            The SMTP port to send to.
     * @param smtpUsername
     *            The username required to authenticate against the SMTP server.
     * @param smtpPassword
     *            The password required to authenticate against the SMTP server.
     * @param smtpDebug
     *            Enable mail session debuging on STDOUT.
     * @param bufferSizeStr
     *            How many log events should be buffered for inclusion in the
     *            message?
     * @param layout
     *            The layout to use (defaults to HtmlLayout).
     * @param filter
     *            The Filter or null (defaults to ThresholdFilter, level of
     *            ERROR).
     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
     *               they are propagated to the caller.
     * @return The SmtpAppender.
     */
@PluginFactory
public static SmtpAppender createAppender(@PluginConfiguration final Configuration config, @PluginAttribute("name") @Required final String name, @PluginAttribute("to") final String to, @PluginAttribute("cc") final String cc, @PluginAttribute("bcc") final String bcc, @PluginAttribute("from") final String from, @PluginAttribute("replyTo") final String replyTo, @PluginAttribute("subject") final String subject, @PluginAttribute("smtpProtocol") final String smtpProtocol, @PluginAttribute("smtpHost") final String smtpHost, @PluginAttribute(value = "smtpPort", defaultString = "0") @ValidPort final String smtpPortStr, @PluginAttribute("smtpUsername") final String smtpUsername, @PluginAttribute(value = "smtpPassword", sensitive = true) final String smtpPassword, @PluginAttribute("smtpDebug") final String smtpDebug, @PluginAttribute("bufferSize") final String bufferSizeStr, @PluginElement("Layout") Layout<? extends Serializable> layout, @PluginElement("Filter") Filter filter, @PluginAttribute("ignoreExceptions") final String ignore) {
    if (name == null) {
        LOGGER.error("No name provided for SmtpAppender");
        return null;
    }
    final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
    final int smtpPort = AbstractAppender.parseInt(smtpPortStr, 0);
    final boolean isSmtpDebug = Boolean.parseBoolean(smtpDebug);
    final int bufferSize = bufferSizeStr == null ? DEFAULT_BUFFER_SIZE : Integer.parseInt(bufferSizeStr);
    if (layout == null) {
        layout = HtmlLayout.createDefaultLayout();
    }
    if (filter == null) {
        filter = ThresholdFilter.createFilter(null, null, null);
    }
    final Configuration configuration = config != null ? config : new DefaultConfiguration();
    final SmtpManager manager = SmtpManager.getSmtpManager(configuration, to, cc, bcc, from, replyTo, subject, smtpProtocol, smtpHost, smtpPort, smtpUsername, smtpPassword, isSmtpDebug, filter.toString(), bufferSize);
    if (manager == null) {
        return null;
    }
    return new SmtpAppender(name, filter, layout, manager, ignoreExceptions);
}
Also used : DefaultConfiguration(org.apache.logging.log4j.core.config.DefaultConfiguration) PluginConfiguration(org.apache.logging.log4j.core.config.plugins.PluginConfiguration) Configuration(org.apache.logging.log4j.core.config.Configuration) SmtpManager(org.apache.logging.log4j.core.net.SmtpManager) DefaultConfiguration(org.apache.logging.log4j.core.config.DefaultConfiguration) PluginFactory(org.apache.logging.log4j.core.config.plugins.PluginFactory)

Example 9 with PluginFactory

use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project logging-log4j2 by apache.

the class DataSourceConnectionSource method createConnectionSource.

/**
     * Factory method for creating a connection source within the plugin manager.
     *
     * @param jndiName The full JNDI path where the data source is bound. Should start with java:/comp/env or
     *                 environment-equivalent.
     * @return the created connection source.
     */
@PluginFactory
public static DataSourceConnectionSource createConnectionSource(@PluginAttribute("jndiName") final String jndiName) {
    if (Strings.isEmpty(jndiName)) {
        LOGGER.error("No JNDI name provided.");
        return null;
    }
    try {
        final InitialContext context = new InitialContext();
        final DataSource dataSource = (DataSource) context.lookup(jndiName);
        if (dataSource == null) {
            LOGGER.error("No data source found with JNDI name [" + jndiName + "].");
            return null;
        }
        return new DataSourceConnectionSource(jndiName, dataSource);
    } catch (final NamingException e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
}
Also used : NamingException(javax.naming.NamingException) InitialContext(javax.naming.InitialContext) DataSource(javax.sql.DataSource) PluginFactory(org.apache.logging.log4j.core.config.plugins.PluginFactory)

Example 10 with PluginFactory

use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project logging-log4j2 by apache.

the class ScriptFile method createScript.

@PluginFactory
public static ScriptFile createScript(// @formatter:off
@PluginAttribute("name") String name, @PluginAttribute("language") String language, @PluginAttribute("path") final String filePathOrUri, @PluginAttribute("isWatched") final Boolean isWatched, @PluginAttribute("charset") final Charset charset) {
    // @formatter:on
    if (filePathOrUri == null) {
        LOGGER.error("No script path provided for ScriptFile");
        return null;
    }
    if (name == null) {
        name = filePathOrUri;
    }
    final URI uri = NetUtils.toURI(filePathOrUri);
    final File file = FileUtils.fileFromUri(uri);
    if (language == null && file != null) {
        final String fileExtension = FileUtils.getFileExtension(file);
        if (fileExtension != null) {
            final ExtensionLanguageMapping mapping = ExtensionLanguageMapping.getByExtension(fileExtension);
            if (mapping != null) {
                language = mapping.getLanguage();
            }
        }
    }
    if (language == null) {
        LOGGER.info("No script language supplied, defaulting to {}", DEFAULT_LANGUAGE);
        language = DEFAULT_LANGUAGE;
    }
    final Charset actualCharset = charset == null ? Charset.defaultCharset() : charset;
    String scriptText;
    try (final Reader reader = new InputStreamReader(file != null ? new FileInputStream(file) : uri.toURL().openStream(), actualCharset)) {
        scriptText = IOUtils.toString(reader);
    } catch (final IOException e) {
        LOGGER.error("{}: language={}, path={}, actualCharset={}", e.getClass().getSimpleName(), language, filePathOrUri, actualCharset);
        return null;
    }
    final Path path = file != null ? Paths.get(file.toURI()) : Paths.get(uri);
    if (path == null) {
        LOGGER.error("Unable to convert {} to a Path", uri.toString());
        return null;
    }
    return new ScriptFile(name, path, language, isWatched == null ? Boolean.FALSE : isWatched, scriptText);
}
Also used : Path(java.nio.file.Path) InputStreamReader(java.io.InputStreamReader) Charset(java.nio.charset.Charset) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ExtensionLanguageMapping(org.apache.logging.log4j.core.util.ExtensionLanguageMapping) IOException(java.io.IOException) URI(java.net.URI) File(java.io.File) FileInputStream(java.io.FileInputStream) PluginFactory(org.apache.logging.log4j.core.config.plugins.PluginFactory)

Aggregations

PluginFactory (org.apache.logging.log4j.core.config.plugins.PluginFactory)12 Method (java.lang.reflect.Method)3 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 DataSource (javax.sql.DataSource)2 DB (com.mongodb.DB)1 MongoClient (com.mongodb.MongoClient)1 ServerAddress (com.mongodb.ServerAddress)1 WriteConcern (com.mongodb.WriteConcern)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStreamReader (java.io.InputStreamReader)1 PrintWriter (java.io.PrintWriter)1 Reader (java.io.Reader)1 URI (java.net.URI)1 Charset (java.nio.charset.Charset)1 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1