use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project cryptomator by cryptomator.
the class ConfigurableFileAppender method createAppender.
@PluginFactory
public static AbstractAppender createAppender(@PluginAttribute("name") final String name, @PluginAttribute("pathPropertyName") final String pathPropertyName, @PluginAttribute("append") final String append, @PluginElement("Layout") Layout<? extends Serializable> layout) {
if (name == null) {
LOGGER.error("No name provided for ConfigurableFileAppender");
return null;
}
if (pathPropertyName == null) {
LOGGER.error("No pathPropertyName provided for ConfigurableFileAppender with name " + name);
return null;
}
final String fileName = System.getProperty(pathPropertyName);
if (Strings.isEmpty(fileName)) {
LOGGER.warn("No log file location provided in system property \"" + pathPropertyName + "\"");
return null;
}
final Path filePath = parsePath(fileName);
if (filePath == null) {
LOGGER.warn("Invalid path \"" + fileName + "\"");
return null;
}
if (!Files.exists(filePath.getParent())) {
try {
Files.createDirectories(filePath.getParent());
} catch (IOException e) {
LOGGER.error("Could not create parent directories for log file located at " + filePath.toString(), e);
return null;
}
}
final boolean shouldAppend = Booleans.parseBoolean(append, true);
if (layout == null) {
layout = PatternLayout.createDefaultLayout();
}
final FileManager manager = FileManager.getFileManager(filePath.toString(), shouldAppend, false, true, null, layout, DEFAULT_BUFFER_SIZE);
return new ConfigurableFileAppender(name, layout, null, manager);
}
use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project logging-log4j2 by apache.
the class FactoryMethodConnectionSource method createConnectionSource.
/**
* Factory method for creating a connection source within the plugin manager.
*
* @param className The name of a public class that contains a static method capable of returning either a
* {@link DataSource} or a {@link Connection}.
* @param methodName The name of the public static method on the aforementioned class that returns the data source
* or connection. If this method returns a {@link Connection}, it should return a new connection
* every call.
* @return the created connection source.
*/
@PluginFactory
public static FactoryMethodConnectionSource createConnectionSource(@PluginAttribute("class") final String className, @PluginAttribute("method") final String methodName) {
if (Strings.isEmpty(className) || Strings.isEmpty(methodName)) {
LOGGER.error("No class name or method name specified for the connection factory method.");
return null;
}
final Method method;
try {
final Class<?> factoryClass = LoaderUtil.loadClass(className);
method = factoryClass.getMethod(methodName);
} catch (final Exception e) {
LOGGER.error(e.toString(), e);
return null;
}
final Class<?> returnType = method.getReturnType();
String returnTypeString = returnType.getName();
DataSource dataSource;
if (returnType == DataSource.class) {
try {
dataSource = (DataSource) method.invoke(null);
returnTypeString += "[" + dataSource + ']';
} catch (final Exception e) {
LOGGER.error(e.toString(), e);
return null;
}
} else if (returnType == Connection.class) {
dataSource = new DataSource() {
@Override
public Connection getConnection() throws SQLException {
try {
return (Connection) method.invoke(null);
} catch (final Exception e) {
throw new SQLException("Failed to obtain connection from factory method.", e);
}
}
@Override
public Connection getConnection(final String username, final String password) throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public int getLoginTimeout() throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public PrintWriter getLogWriter() throws SQLException {
throw new UnsupportedOperationException();
}
@Override
@SuppressWarnings("unused")
public java.util.logging.Logger getParentLogger() {
throw new UnsupportedOperationException();
}
@Override
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
return false;
}
@Override
public void setLoginTimeout(final int seconds) throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public void setLogWriter(final PrintWriter out) throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public <T> T unwrap(final Class<T> iface) throws SQLException {
return null;
}
};
} else {
LOGGER.error("Method [{}.{}()] returns unsupported type [{}].", className, methodName, returnType.getName());
return null;
}
return new FactoryMethodConnectionSource(dataSource, className, methodName, returnTypeString);
}
use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project logging-log4j2 by apache.
the class CouchDbProvider method createNoSqlProvider.
/**
* Factory method for creating an Apache CouchDB provider within the plugin manager.
*
* @param databaseName The name of the database to which log event documents will be written.
* @param protocol Either "http" or "https," defaults to "http" and mutually exclusive with
* {@code factoryClassName&factoryMethodName!=null}.
* @param server The host name of the CouchDB server, defaults to localhost and mutually exclusive with
* {@code factoryClassName&factoryMethodName!=null}.
* @param port The port that CouchDB is listening on, defaults to 80 if {@code protocol} is "http" and 443 if
* {@code protocol} is "https," and mutually exclusive with
* {@code factoryClassName&factoryMethodName!=null}.
* @param username The username to authenticate against the MongoDB server with, mutually exclusive with
* {@code factoryClassName&factoryMethodName!=null}.
* @param password The password to authenticate against the MongoDB server with, mutually exclusive with
* {@code factoryClassName&factoryMethodName!=null}.
* @param factoryClassName A fully qualified class name containing a static factory method capable of returning a
* {@link CouchDbClient} or {@link CouchDbProperties}.
* @param factoryMethodName The name of the public static factory method belonging to the aforementioned factory
* class.
* @return a new Apache CouchDB provider.
*/
@PluginFactory
public static CouchDbProvider createNoSqlProvider(@PluginAttribute("databaseName") final String databaseName, @PluginAttribute("protocol") String protocol, @PluginAttribute(value = "server", defaultString = "localhost") @ValidHost String server, @PluginAttribute(value = "port", defaultString = "0") @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) {
CouchDbClient client;
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 CouchDbClient) {
client = (CouchDbClient) object;
description = "uri=" + client.getDBUri();
} else if (object instanceof CouchDbProperties) {
final CouchDbProperties properties = (CouchDbProperties) object;
client = new CouchDbClient(properties);
description = "uri=" + client.getDBUri() + ", username=" + properties.getUsername() + ", passwordHash=" + NameUtil.md5(password + CouchDbProvider.class.getName()) + ", maxConnections=" + properties.getMaxConnections() + ", connectionTimeout=" + properties.getConnectionTimeout() + ", socketTimeout=" + properties.getSocketTimeout();
} 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;
}
} 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)) {
if (protocol != null && protocol.length() > 0) {
protocol = protocol.toLowerCase();
if (!protocol.equals("http") && !protocol.equals("https")) {
LOGGER.error("Only protocols [http] and [https] are supported, [{}] specified.", protocol);
return null;
}
} else {
protocol = "http";
LOGGER.warn("No protocol specified, using default port [http].");
}
final int portInt = TypeConverters.convert(port, int.class, protocol.equals("https") ? HTTPS : HTTP);
if (Strings.isEmpty(username) || Strings.isEmpty(password)) {
LOGGER.error("You must provide a username and password for the CouchDB provider.");
return null;
}
client = new CouchDbClient(databaseName, false, protocol, server, portInt, username, password);
description = "uri=" + client.getDBUri() + ", username=" + username + ", passwordHash=" + NameUtil.md5(password + CouchDbProvider.class.getName());
} else {
LOGGER.error("No factory method was provided so the database name is required.");
return null;
}
return new CouchDbProvider(client, description);
}
use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project xian by happyyangyuan.
the class GelfLogField method createField.
@PluginFactory
public static GelfLogField createField(@PluginConfiguration final Configuration config, @PluginAttribute("name") String name, @PluginAttribute("literal") String literalValue, @PluginAttribute("mdc") String mdc, @PluginAttribute("pattern") String pattern) {
final boolean isPattern = Strings.isNotEmpty(pattern);
final boolean isLiteralValue = Strings.isNotEmpty(literalValue);
final boolean isMDC = Strings.isNotEmpty(mdc);
if (Strings.isEmpty(name)) {
LOGGER.error("The name is empty");
return null;
}
if ((isPattern && isLiteralValue) || (isPattern && isMDC) || (isLiteralValue && isMDC)) {
LOGGER.error("The pattern, literal, and mdc attributes are mutually exclusive.");
return null;
}
if (isPattern) {
PatternLayout patternLayout = newBuilder().withPattern(pattern).withConfiguration(config).withNoConsoleNoAnsi(false).withAlwaysWriteExceptions(false).build();
return new GelfLogField(name, null, null, patternLayout);
}
return new GelfLogField(name, literalValue, mdc, null);
}
use of org.apache.logging.log4j.core.config.plugins.PluginFactory in project jaffa-framework by jaffa-projects.
the class ThreadContextFilter method createFilter.
/**
* @param pairs
* @param oper
* @param match
* @param mismatch
* @return
*/
@PluginFactory
public static org.apache.logging.log4j.core.filter.ThreadContextMapFilter createFilter(@PluginElement("Pairs") KeyValuePair[] pairs, @PluginAttribute("operator") String oper, @PluginAttribute("onMatch") Result match, @PluginAttribute("onMismatch") Result mismatch) {
if (pairs != null && pairs.length != 0) {
Map<String, List<String>> map = new HashMap();
KeyValuePair[] keyValuePairs = pairs;
for (int i$ = 0; i$ < pairs.length; ++i$) {
KeyValuePair pair = keyValuePairs[i$];
String key = pair.getKey();
if (key == null) {
LOGGER.error("A null key is not valid in MapFilter");
} else {
String value = pair.getValue();
if (value == null) {
LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
} else {
List<String> list = (List) map.get(pair.getKey());
if (list != null) {
list.add(value);
} else {
list = new ArrayList();
list.add(value);
map.put(pair.getKey(), list);
}
}
}
}
if (map.isEmpty()) {
LOGGER.error("ThreadContextFilter is not configured with any valid key value pairs");
return null;
} else {
boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
return new ThreadContextFilter(map, isAnd, match, mismatch);
}
} else {
LOGGER.error("key and value pairs must be specified for the ThreadContextFilter");
return null;
}
}
Aggregations