Remove dependency on slf4j for logging, create own internal abstraction, closes #146.

This commit is contained in:
kimchy 2010-04-21 00:29:42 +03:00
parent b1721ac07a
commit bda476eee8
47 changed files with 1204 additions and 415 deletions

View File

@ -50,7 +50,9 @@
<w>plugins</w>
<w>porterstem</w>
<w>rebalance</w>
<w>sbuf</w>
<w>searchable</w>
<w>serializers</w>
<w>snapshotting</w>
<w>stopwords</w>
<w>streamable</w>

View File

@ -2,8 +2,8 @@
<library name="logging">
<CLASSES>
<root url="jar://$GRADLE_REPOSITORY$/log4j/log4j/jars/log4j-1.2.15.jar!/" />
<root url="jar://$GRADLE_REPOSITORY$/org.slf4j/slf4j-log4j12/jars/slf4j-log4j12-1.5.11.jar!/" />
<root url="jar://$GRADLE_REPOSITORY$/org.slf4j/slf4j-api/jars/slf4j-api-1.5.11.jar!/" />
<root url="jar://$GRADLE_REPOSITORY$/org.slf4j/slf4j-log4j12/jars/slf4j-log4j12-1.5.11.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />

View File

@ -74,6 +74,7 @@ task explodedDist(dependsOn: [configurations.distLib], description: 'Builds a mi
ant.delete { fileset(dir: explodedDistLibDir, includes: "$archivesBaseName-*-javadoc.jar") }
ant.delete { fileset(dir: explodedDistLibDir, includes: "$archivesBaseName-*-sources.jar") }
ant.delete { fileset(dir: explodedDistLibDir, includes: "slf4j-*.jar") } // no need for slf4j
ant.chmod(dir: "$explodedDistDir/bin", perm: "ugo+rx", includes: "**/*")
}

View File

@ -125,8 +125,9 @@ uploadArchives {
pom.whenConfigured {pom ->
pom.dependencies = pom.dependencies.findAll {dep -> dep.scope != 'test' } // removes the test scoped ones
pom.dependencies = pom.dependencies.findAll {dep -> !dep.artifactId.contains('log4j') } // removes the test scoped ones
pom.dependencies = pom.dependencies.findAll {dep -> !dep.artifactId.contains('jline') } // removes the test scoped ones
pom.dependencies = pom.dependencies.findAll {dep -> !dep.artifactId.contains('log4j') }
pom.dependencies = pom.dependencies.findAll {dep -> !dep.artifactId.contains('slf4j') }
pom.dependencies = pom.dependencies.findAll {dep -> !dep.artifactId.contains('jline') }
pom.dependencies.findAll {dep -> dep.groupId == 'jgroups' }*.scope = 'runtime'
pom.dependencies.findAll {dep -> dep.groupId == 'org.jboss.netty' }*.scope = 'runtime'
}

View File

@ -31,10 +31,10 @@ import org.elasticsearch.node.internal.InternalSettingsPerparer;
import org.elasticsearch.util.Classes;
import org.elasticsearch.util.Tuple;
import org.elasticsearch.util.jline.ANSI;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.logging.log4j.LogConfigurator;
import org.elasticsearch.util.settings.Settings;
import org.slf4j.Logger;
import java.io.File;
import java.util.Set;
@ -162,7 +162,7 @@ public class Bootstrap {
System.err.close();
}
} catch (Throwable e) {
Logger logger = Loggers.getLogger(Bootstrap.class);
ESLogger logger = Loggers.getLogger(Bootstrap.class);
if (bootstrap.node != null) {
logger = Loggers.getLogger(Bootstrap.class, bootstrap.node.settings().get("name"));
}

View File

@ -19,10 +19,10 @@
package org.elasticsearch.discovery.jgroups;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.ESLoggerFactory;
import org.jgroups.logging.CustomLogFactory;
import org.jgroups.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author kimchy (Shay Banon)
@ -34,14 +34,14 @@ public class JgroupsCustomLogFactory implements CustomLogFactory {
}
@Override public Log getLog(String category) {
return new Slf4jLog(LoggerFactory.getLogger(category.replace("org.jgroups.", "jgroups.").replace(".protocols.", ".")));
return new JgroupsESLog(ESLoggerFactory.getLogger(category.replace("org.jgroups.", "jgroups.").replace(".protocols.", ".")));
}
private static class Slf4jLog implements Log {
private static class JgroupsESLog implements Log {
private final Logger logger;
private final ESLogger logger;
private Slf4jLog(Logger logger) {
private JgroupsESLog(ESLogger logger) {
this.logger = logger;
}

View File

@ -23,6 +23,7 @@ import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.http.*;
import org.elasticsearch.transport.BindTransportException;
import org.elasticsearch.transport.netty.NettyInternalESLoggerFactory;
import org.elasticsearch.util.SizeUnit;
import org.elasticsearch.util.SizeValue;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
@ -40,7 +41,6 @@ import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.timeout.ReadTimeoutException;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Slf4JLoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
@ -57,9 +57,9 @@ import static org.elasticsearch.util.io.HostResolver.*;
public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpServerTransport> implements HttpServerTransport {
static {
InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory() {
InternalLoggerFactory.setDefaultFactory(new NettyInternalESLoggerFactory() {
@Override public InternalLogger newInstance(String name) {
return super.newInstance(name.replace("org.jboss.netty.", "netty.lib."));
return super.newInstance(name.replace("org.jboss.netty.", "netty."));
}
});
}

View File

@ -21,9 +21,9 @@ package org.elasticsearch.index;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.jmx.ManagedGroupName;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.settings.Settings;
import org.slf4j.Logger;
import static org.elasticsearch.index.IndexServiceManagement.*;
@ -32,7 +32,7 @@ import static org.elasticsearch.index.IndexServiceManagement.*;
*/
public abstract class AbstractIndexComponent implements IndexComponent {
protected final Logger logger;
protected final ESLogger logger;
protected final Index index;

View File

@ -21,9 +21,9 @@ package org.elasticsearch.index.shard;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.jmx.ManagedGroupName;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.settings.Settings;
import org.slf4j.Logger;
import static org.elasticsearch.index.shard.IndexShardManagement.*;
@ -32,7 +32,7 @@ import static org.elasticsearch.index.shard.IndexShardManagement.*;
*/
public abstract class AbstractIndexShardComponent implements IndexShardComponent {
protected final Logger logger;
protected final ESLogger logger;
protected final ShardId shardId;

View File

@ -20,9 +20,9 @@
package org.elasticsearch.jmx;
import org.elasticsearch.util.io.HostResolver;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.settings.Settings;
import org.elasticsearch.util.transport.PortsRange;
import org.slf4j.Logger;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
@ -54,7 +54,7 @@ public class JmxService {
public static final String JMXRMI_PUBLISH_URI_PATTERN = "service:jmx:rmi:///jndi/rmi://{jmx.host}:{jmx.port}/jmxrmi";
private final Logger logger;
private final ESLogger logger;
private final Settings settings;
@ -76,7 +76,7 @@ public class JmxService {
private volatile boolean started = false;
public JmxService(Logger logger, final Settings settings) {
public JmxService(ESLogger logger, final Settings settings) {
this.logger = logger;
this.settings = settings;

View File

@ -25,7 +25,7 @@ import org.elasticsearch.util.Classes;
import org.elasticsearch.util.MapBuilder;
import org.elasticsearch.util.Preconditions;
import org.elasticsearch.util.Strings;
import org.slf4j.Logger;
import org.elasticsearch.util.logging.ESLogger;
import javax.management.*;
import java.lang.reflect.Field;
@ -46,7 +46,7 @@ public class ResourceDMBean implements DynamicMBean {
private static final Class<?>[] primitives = {int.class, byte.class, short.class, long.class,
float.class, double.class, boolean.class, char.class};
private final Logger logger;
private final ESLogger logger;
private final Object obj;
@ -68,7 +68,7 @@ public class ResourceDMBean implements DynamicMBean {
private final ImmutableList<MBeanOperationInfo> operations;
public ResourceDMBean(Object instance, Logger logger) {
public ResourceDMBean(Object instance, ESLogger logger) {
Preconditions.checkNotNull(instance, "Cannot make an MBean wrapper for null instance");
this.obj = instance;
this.logger = logger;

View File

@ -65,10 +65,10 @@ import org.elasticsearch.util.component.Lifecycle;
import org.elasticsearch.util.component.LifecycleComponent;
import org.elasticsearch.util.guice.Injectors;
import org.elasticsearch.util.io.FileSystemUtils;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.settings.Settings;
import org.elasticsearch.util.settings.SettingsModule;
import org.slf4j.Logger;
import java.io.File;
import java.util.ArrayList;
@ -100,7 +100,7 @@ public final class InternalNode implements Node {
public InternalNode(Settings pSettings, boolean loadConfigSettings) throws ElasticSearchException {
Tuple<Settings, Environment> tuple = InternalSettingsPerparer.prepareSettings(pSettings, loadConfigSettings);
Logger logger = Loggers.getLogger(Node.class, tuple.v1().get("name"));
ESLogger logger = Loggers.getLogger(Node.class, tuple.v1().get("name"));
logger.info("{{}}: Initializing ...", Version.full());
this.pluginsService = new PluginsService(tuple.v1(), tuple.v2());
@ -151,7 +151,7 @@ public final class InternalNode implements Node {
return this;
}
Logger logger = Loggers.getLogger(Node.class, settings.get("name"));
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
logger.info("{{}}: Starting ...", Version.full());
for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
@ -184,7 +184,7 @@ public final class InternalNode implements Node {
if (!lifecycle.moveToStopped()) {
return this;
}
Logger logger = Loggers.getLogger(Node.class, settings.get("name"));
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
logger.info("{{}}: Stopping ...", Version.full());
if (settings.getAsBoolean("http.enabled", true)) {
@ -228,7 +228,7 @@ public final class InternalNode implements Node {
return;
}
Logger logger = Loggers.getLogger(Node.class, settings.get("name"));
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
logger.info("{{}}: Closing ...", Version.full());
if (settings.getAsBoolean("http.enabled", true)) {

View File

@ -25,21 +25,21 @@ import org.elasticsearch.util.io.ThrowableObjectInputStream;
import org.elasticsearch.util.io.stream.HandlesStreamInput;
import org.elasticsearch.util.io.stream.StreamInput;
import org.elasticsearch.util.io.stream.Streamable;
import org.elasticsearch.util.logging.ESLogger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.*;
import org.slf4j.Logger;
import java.io.IOException;
import static org.elasticsearch.transport.Transport.Helper.*;
/**
* @author kimchy (Shay Banon)
* @author kimchy (shay.banon)
*/
@ChannelPipelineCoverage("one")
public class MessageChannelHandler extends SimpleChannelUpstreamHandler {
private final Logger logger;
private final ESLogger logger;
private final ThreadPool threadPool;
@ -47,7 +47,7 @@ public class MessageChannelHandler extends SimpleChannelUpstreamHandler {
private final NettyTransport transport;
public MessageChannelHandler(NettyTransport transport, Logger logger) {
public MessageChannelHandler(NettyTransport transport, ESLogger logger) {
this.threadPool = transport.threadPool();
this.transportServiceAdapter = transport.transportServiceAdapter();
this.transport = transport;

View File

@ -0,0 +1,83 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.netty;
import org.elasticsearch.util.logging.ESLogger;
import org.jboss.netty.logging.AbstractInternalLogger;
/**
* @author kimchy (shay.banon)
*/
public class NettyInternalESLogger extends AbstractInternalLogger {
private final ESLogger logger;
public NettyInternalESLogger(ESLogger logger) {
this.logger = logger;
}
@Override public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
@Override public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
@Override public void debug(String msg) {
logger.debug(msg);
}
@Override public void debug(String msg, Throwable cause) {
logger.debug(msg, cause);
}
@Override public void info(String msg) {
logger.info(msg);
}
@Override public void info(String msg, Throwable cause) {
logger.info(msg, cause);
}
@Override public void warn(String msg) {
logger.warn(msg);
}
@Override public void warn(String msg, Throwable cause) {
logger.warn(msg, cause);
}
@Override public void error(String msg) {
logger.error(msg);
}
@Override public void error(String msg, Throwable cause) {
logger.error(msg, cause);
}
}

View File

@ -0,0 +1,34 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.netty;
import org.elasticsearch.util.logging.Loggers;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
/**
* @author kimchy (shay.banon)
*/
public class NettyInternalESLoggerFactory extends InternalLoggerFactory {
@Override public InternalLogger newInstance(String name) {
return new NettyInternalESLogger(Loggers.getLogger(name));
}
}

View File

@ -46,7 +46,6 @@ import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Slf4JLoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
@ -76,7 +75,7 @@ import static org.elasticsearch.util.transport.NetworkExceptionHelper.*;
public class NettyTransport extends AbstractLifecycleComponent<Transport> implements Transport {
static {
InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory() {
InternalLoggerFactory.setDefaultFactory(new NettyInternalESLoggerFactory() {
@Override public InternalLogger newInstance(String name) {
return super.newInstance(name.replace("org.jboss.netty.", "netty."));
}

View File

@ -19,8 +19,8 @@
package org.elasticsearch.util;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.slf4j.Logger;
import java.lang.ref.Reference;
import java.lang.reflect.Field;
@ -32,7 +32,7 @@ import java.lang.reflect.Method;
*/
public class ThreadLocals {
private static final Logger logger = Loggers.getLogger(ThreadLocals.class);
private static final ESLogger logger = Loggers.getLogger(ThreadLocals.class);
public static class CleanableValue<T> {

View File

@ -19,8 +19,8 @@
package org.elasticsearch.util;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.slf4j.Logger;
/**
* A {@link Runnable} that changes the current thread name and reverts it back
@ -31,7 +31,7 @@ import org.slf4j.Logger;
*/
public class ThreadRenamingRunnable implements Runnable {
private static final Logger logger = Loggers.getLogger(ThreadRenamingRunnable.class);
private static final ESLogger logger = Loggers.getLogger(ThreadRenamingRunnable.class);
private static volatile ThreadNameDeterminer threadNameDeterminer =
ThreadNameDeterminer.PROPOSED;

View File

@ -19,16 +19,16 @@
package org.elasticsearch.util.component;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.settings.Settings;
import org.slf4j.Logger;
/**
* @author kimchy (shay.banon)
*/
public class AbstractComponent {
protected final Logger logger;
protected final ESLogger logger;
protected final Settings settings;

View File

@ -0,0 +1,106 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging;
/**
* @author kimchy (shay.banon)
*/
public interface ESLogger {
String getPrefix();
String getName();
/**
* Returns {@code true} if a TRACE level message is logged.
*/
boolean isTraceEnabled();
/**
* Returns {@code true} if a DEBUG level message is logged.
*/
boolean isDebugEnabled();
/**
* Returns {@code true} if an INFO level message is logged.
*/
boolean isInfoEnabled();
/**
* Returns {@code true} if a WARN level message is logged.
*/
boolean isWarnEnabled();
/**
* Returns {@code true} if an ERROR level message is logged.
*/
boolean isErrorEnabled();
/**
* Logs a DEBUG level message.
*/
void trace(String msg, Object... params);
/**
* Logs a DEBUG level message.
*/
void trace(String msg, Throwable cause, Object... params);
/**
* Logs a DEBUG level message.
*/
void debug(String msg, Object... params);
/**
* Logs a DEBUG level message.
*/
void debug(String msg, Throwable cause, Object... params);
/**
* Logs an INFO level message.
*/
void info(String msg, Object... params);
/**
* Logs an INFO level message.
*/
void info(String msg, Throwable cause, Object... params);
/**
* Logs a WARN level message.
*/
void warn(String msg, Object... params);
/**
* Logs a WARN level message.
*/
void warn(String msg, Throwable cause, Object... params);
/**
* Logs an ERROR level message.
*/
void error(String msg, Object... params);
/**
* Logs an ERROR level message.
*/
void error(String msg, Throwable cause, Object... params);
}

View File

@ -0,0 +1,72 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging;
import org.elasticsearch.util.logging.jdk.JdkESLoggerFactory;
import org.elasticsearch.util.logging.log4j.Log4jESLoggerFactory;
import org.elasticsearch.util.logging.slf4j.Slf4jESLoggerFactory;
/**
* @author kimchy (shay.banon)
*/
public abstract class ESLoggerFactory {
private static volatile ESLoggerFactory defaultFactory = new JdkESLoggerFactory();
static {
try {
Class.forName("org.slf4j.Logger");
defaultFactory = new Slf4jESLoggerFactory();
} catch (Throwable e) {
// no slf4j
try {
Class.forName("org.apache.log4j.Logger");
defaultFactory = new Log4jESLoggerFactory();
} catch (Throwable e1) {
// no log4j
}
}
}
/**
* Changes the default factory.
*/
public static void setDefaultFactory(ESLoggerFactory defaultFactory) {
if (defaultFactory == null) {
throw new NullPointerException("defaultFactory");
}
ESLoggerFactory.defaultFactory = defaultFactory;
}
public static ESLogger getLogger(String prefix, String name) {
return defaultFactory.newInstance(prefix, name);
}
public static ESLogger getLogger(String name) {
return defaultFactory.newInstance(name);
}
public ESLogger newInstance(String name) {
return newInstance(null, name);
}
public abstract ESLogger newInstance(String prefix, String name);
}

View File

@ -24,8 +24,6 @@ import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.util.Classes;
import org.elasticsearch.util.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
@ -36,12 +34,8 @@ import static java.util.Arrays.asList;
/**
* A set of utilities around Logging.
* <p/>
* <p>The most important is the {@link #getLogger(Class)} which should be used instead of
* {@link org.slf4j.LoggerFactory#getLogger(Class)}. It will use the package name as the
* logging level without the actual class name.
*
* @author kimchy (Shay Banon)
* @author kimchy (shay.banon)
*/
public class Loggers {
@ -59,15 +53,15 @@ public class Loggers {
return consoleLoggingEnabled;
}
public static Logger getLogger(Class clazz, Settings settings, ShardId shardId, String... prefixes) {
public static ESLogger getLogger(Class clazz, Settings settings, ShardId shardId, String... prefixes) {
return getLogger(clazz, settings, shardId.index(), Lists.asList(Integer.toString(shardId.id()), prefixes).toArray(new String[0]));
}
public static Logger getLogger(Class clazz, Settings settings, Index index, String... prefixes) {
public static ESLogger getLogger(Class clazz, Settings settings, Index index, String... prefixes) {
return getLogger(clazz, settings, Lists.asList(index.name(), prefixes).toArray(new String[0]));
}
public static Logger getLogger(Class clazz, Settings settings, String... prefixes) {
public static ESLogger getLogger(Class clazz, Settings settings, String... prefixes) {
List<String> prefixesList = newArrayList();
if (settings.getAsBoolean("logger.logHostAddress", false)) {
try {
@ -90,44 +84,40 @@ public class Loggers {
if (prefixes != null && prefixes.length > 0) {
prefixesList.addAll(asList(prefixes));
}
return getLogger(clazz, prefixesList.toArray(new String[prefixesList.size()]));
return getLogger(getLoggerName(clazz), prefixesList.toArray(new String[prefixesList.size()]));
}
public static Logger getLogger(Logger parentLogger, String s) {
Logger logger = getLogger(parentLogger.getName() + s);
if (parentLogger instanceof PrefixLoggerAdapter) {
return new PrefixLoggerAdapter(((PrefixLoggerAdapter) parentLogger).prefix(), logger);
}
return logger;
public static ESLogger getLogger(ESLogger parentLogger, String s) {
return getLogger(parentLogger.getName() + s, parentLogger.getPrefix());
}
public static Logger getLogger(String s) {
return LoggerFactory.getLogger(s);
public static ESLogger getLogger(String s) {
return ESLoggerFactory.getLogger(s);
}
public static Logger getLogger(Class clazz) {
return LoggerFactory.getLogger(getLoggerName(clazz));
public static ESLogger getLogger(Class clazz) {
return ESLoggerFactory.getLogger(getLoggerName(clazz));
}
public static Logger getLogger(Class clazz, String... prefixes) {
return getLogger(LoggerFactory.getLogger(getLoggerName(clazz)), prefixes);
public static ESLogger getLogger(Class clazz, String... prefixes) {
return getLogger(getLoggerName(clazz), prefixes);
}
public static Logger getLogger(Logger logger, String... prefixes) {
if (prefixes == null || prefixes.length == 0) {
return logger;
}
StringBuilder sb = new StringBuilder();
for (String prefix : prefixes) {
if (prefix != null) {
sb.append("[").append(prefix).append("]");
public static ESLogger getLogger(String name, String... prefixes) {
String prefix = null;
if (prefixes != null && prefixes.length > 0) {
StringBuilder sb = new StringBuilder();
for (String prefixX : prefixes) {
if (prefixX != null) {
sb.append("[").append(prefixX).append("]");
}
}
if (sb.length() > 0) {
sb.append(" ");
prefix = sb.toString();
}
}
if (sb.length() == 0) {
return logger;
}
sb.append(" ");
return new PrefixLoggerAdapter(sb.toString(), logger);
return ESLoggerFactory.getLogger(prefix, getLoggerName(name));
}
private static String getLoggerName(Class clazz) {

View File

@ -1,294 +0,0 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging;
import org.slf4j.Logger;
import org.slf4j.Marker;
/**
* A Logger that wraps another logger and adds the provided prefix to every log
* message.
*
* @author kimchy (Shay Banon)
*/
// TODO is there a way to do this without String concatenation?
public class PrefixLoggerAdapter implements Logger {
private final String prefix;
private final Logger logger;
public PrefixLoggerAdapter(String prefix, Logger logger) {
this.prefix = prefix;
this.logger = logger;
}
public String prefix() {
return this.prefix;
}
private String wrap(String s) {
return prefix + s;
}
public String getName() {
return logger.getName();
}
public final boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
public final void trace(String s) {
logger.trace(wrap(s));
}
public final void trace(String s, Object o) {
logger.trace(wrap(s), o);
}
public final void trace(String s, Object o, Object o1) {
logger.trace(wrap(s), o, o1);
}
public final void trace(String s, Object[] objects) {
logger.trace(wrap(s), objects);
}
public final void trace(String s, Throwable throwable) {
logger.trace(wrap(s), throwable);
}
public final boolean isTraceEnabled(Marker marker) {
return logger.isTraceEnabled(marker);
}
public final void trace(Marker marker, String s) {
logger.trace(marker, wrap(s));
}
public final void trace(Marker marker, String s, Object o) {
logger.trace(marker, wrap(s), o);
}
public final void trace(Marker marker, String s, Object o, Object o1) {
logger.trace(marker, wrap(s), o, o1);
}
public final void trace(Marker marker, String s, Object[] objects) {
logger.trace(marker, wrap(s), objects);
}
public final void trace(Marker marker, String s, Throwable throwable) {
logger.trace(marker, wrap(s), throwable);
}
public final boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
public final void debug(String s) {
logger.debug(wrap(s));
}
public final void debug(String s, Object o) {
logger.debug(wrap(s), o);
}
public final void debug(String s, Object o, Object o1) {
logger.debug(wrap(s), o, o1);
}
public final void debug(String s, Object[] objects) {
logger.debug(wrap(s), objects);
}
public final void debug(String s, Throwable throwable) {
logger.debug(wrap(s), throwable);
}
public final boolean isDebugEnabled(Marker marker) {
return logger.isDebugEnabled(marker);
}
public final void debug(Marker marker, String s) {
logger.debug(marker, wrap(s));
}
public final void debug(Marker marker, String s, Object o) {
logger.debug(marker, wrap(s), o);
}
public final void debug(Marker marker, String s, Object o, Object o1) {
logger.debug(marker, wrap(s), o, o1);
}
public final void debug(Marker marker, String s, Object[] objects) {
logger.debug(marker, wrap(s), objects);
}
public final void debug(Marker marker, String s, Throwable throwable) {
logger.debug(marker, wrap(s), throwable);
}
public final boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
public final void info(String s) {
logger.info(wrap(s));
}
public final void info(String s, Object o) {
logger.info(wrap(s), o);
}
public final void info(String s, Object o, Object o1) {
logger.info(wrap(s), o, o1);
}
public final void info(String s, Object[] objects) {
logger.info(wrap(s), objects);
}
public final void info(String s, Throwable throwable) {
logger.info(wrap(s), throwable);
}
public final boolean isInfoEnabled(Marker marker) {
return logger.isInfoEnabled(marker);
}
public final void info(Marker marker, String s) {
logger.info(marker, wrap(s));
}
public final void info(Marker marker, String s, Object o) {
logger.info(marker, wrap(s), o);
}
public final void info(Marker marker, String s, Object o, Object o1) {
logger.info(marker, wrap(s), o, o1);
}
public final void info(Marker marker, String s, Object[] objects) {
logger.info(marker, wrap(s), objects);
}
public final void info(Marker marker, String s, Throwable throwable) {
logger.info(marker, wrap(s), throwable);
}
public final boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
public final void warn(String s) {
logger.warn(wrap(s));
}
public final void warn(String s, Object o) {
logger.warn(wrap(s), o);
}
public final void warn(String s, Object[] objects) {
logger.warn(wrap(s), objects);
}
public final void warn(String s, Object o, Object o1) {
logger.warn(wrap(s), o, o1);
}
public final void warn(String s, Throwable throwable) {
logger.warn(wrap(s), throwable);
}
public final boolean isWarnEnabled(Marker marker) {
return logger.isWarnEnabled(marker);
}
public final void warn(Marker marker, String s) {
logger.warn(marker, wrap(s));
}
public final void warn(Marker marker, String s, Object o) {
logger.warn(marker, wrap(s), o);
}
public final void warn(Marker marker, String s, Object o, Object o1) {
logger.warn(marker, wrap(s), o, o1);
}
public final void warn(Marker marker, String s, Object[] objects) {
logger.warn(marker, wrap(s), objects);
}
public final void warn(Marker marker, String s, Throwable throwable) {
logger.warn(marker, wrap(s), throwable);
}
public final boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
public final void error(String s) {
logger.error(wrap(s));
}
public final void error(String s, Object o) {
logger.error(wrap(s), o);
}
public final void error(String s, Object o, Object o1) {
logger.error(wrap(s), o, o1);
}
public final void error(String s, Object[] objects) {
logger.error(wrap(s), objects);
}
public final void error(String s, Throwable throwable) {
logger.error(wrap(s), throwable);
}
public final boolean isErrorEnabled(Marker marker) {
return logger.isErrorEnabled(marker);
}
public final void error(Marker marker, String s) {
logger.error(marker, wrap(s));
}
public final void error(Marker marker, String s, Object o) {
logger.error(marker, wrap(s), o);
}
public final void error(Marker marker, String s, Object o, Object o1) {
logger.error(marker, wrap(s), o, o1);
}
public final void error(Marker marker, String s, Object[] objects) {
logger.error(marker, wrap(s), objects);
}
public final void error(Marker marker, String s, Throwable throwable) {
logger.error(marker, wrap(s), throwable);
}
}

View File

@ -0,0 +1,102 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.jdk;
import org.elasticsearch.util.logging.support.AbstractESLogger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author kimchy (shay.banon)
*/
public class JdkESLogger extends AbstractESLogger {
private final Logger logger;
public JdkESLogger(String prefix, Logger logger) {
super(prefix);
this.logger = logger;
}
@Override public String getName() {
return logger.getName();
}
@Override public boolean isTraceEnabled() {
return logger.isLoggable(Level.FINEST);
}
@Override public boolean isDebugEnabled() {
return logger.isLoggable(Level.FINE);
}
@Override public boolean isInfoEnabled() {
return logger.isLoggable(Level.INFO);
}
@Override public boolean isWarnEnabled() {
return logger.isLoggable(Level.WARNING);
}
@Override public boolean isErrorEnabled() {
return logger.isLoggable(Level.SEVERE);
}
@Override protected void internalTrace(String msg) {
logger.log(Level.FINEST, msg);
}
@Override protected void internalTrace(String msg, Throwable cause) {
logger.log(Level.FINEST, msg, cause);
}
@Override protected void internalDebug(String msg) {
logger.log(Level.FINE, msg);
}
@Override protected void internalDebug(String msg, Throwable cause) {
logger.log(Level.FINE, msg, cause);
}
@Override protected void internalInfo(String msg) {
logger.log(Level.INFO, msg);
}
@Override protected void internalInfo(String msg, Throwable cause) {
logger.log(Level.INFO, msg, cause);
}
@Override protected void internalWarn(String msg) {
logger.log(Level.WARNING, msg);
}
@Override protected void internalWarn(String msg, Throwable cause) {
logger.log(Level.WARNING, msg, cause);
}
@Override protected void internalError(String msg) {
logger.log(Level.SEVERE, msg);
}
@Override protected void internalError(String msg, Throwable cause) {
logger.log(Level.SEVERE, msg, cause);
}
}

View File

@ -0,0 +1,34 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.jdk;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.ESLoggerFactory;
/**
* @author kimchy (shay.banon)
*/
public class JdkESLoggerFactory extends ESLoggerFactory {
@Override public ESLogger newInstance(String prefix, String name) {
final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name);
return new JdkESLogger(prefix, logger);
}
}

View File

@ -17,7 +17,7 @@
* under the License.
*/
package org.elasticsearch.util.logging;
package org.elasticsearch.util.logging.log4j;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;

View File

@ -0,0 +1,101 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.log4j;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.elasticsearch.util.logging.support.AbstractESLogger;
/**
* @author kimchy (shay.banon)
*/
public class Log4jESLogger extends AbstractESLogger {
private final org.apache.log4j.Logger logger;
public Log4jESLogger(String prefix, Logger logger) {
super(prefix);
this.logger = logger;
}
@Override public String getName() {
return logger.getName();
}
@Override public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
@Override public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override public boolean isWarnEnabled() {
return logger.isEnabledFor(Level.WARN);
}
@Override public boolean isErrorEnabled() {
return logger.isEnabledFor(Level.ERROR);
}
@Override protected void internalTrace(String msg) {
logger.trace(msg);
}
@Override protected void internalTrace(String msg, Throwable cause) {
logger.trace(msg, cause);
}
@Override protected void internalDebug(String msg) {
logger.debug(msg);
}
@Override protected void internalDebug(String msg, Throwable cause) {
logger.debug(msg, cause);
}
@Override protected void internalInfo(String msg) {
logger.info(msg);
}
@Override protected void internalInfo(String msg, Throwable cause) {
logger.info(msg, cause);
}
@Override protected void internalWarn(String msg) {
logger.warn(msg);
}
@Override protected void internalWarn(String msg, Throwable cause) {
logger.warn(msg, cause);
}
@Override protected void internalError(String msg) {
logger.error(msg);
}
@Override protected void internalError(String msg, Throwable cause) {
logger.error(msg, cause);
}
}

View File

@ -0,0 +1,34 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.log4j;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.ESLoggerFactory;
/**
* @author kimchy (shay.banon)
*/
public class Log4jESLoggerFactory extends ESLoggerFactory {
@Override public ESLogger newInstance(String prefix, String name) {
final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(name);
return new Log4jESLogger(prefix, logger);
}
}

View File

@ -60,7 +60,7 @@ public class LogConfigurator {
.put("simple", "org.apache.log4j.SimpleLayout")
.put("html", "org.apache.log4j.HTMLLayout")
.put("pattern", "org.apache.log4j.PatternLayout")
.put("consolePattern", "org.elasticsearch.util.logging.JLinePatternLayout")
.put("consolePattern", "org.elasticsearch.util.logging.log4j.JLinePatternLayout")
.put("ttcc", "org.apache.log4j.TTCCLayout")
.put("xml", "org.apache.log4j.XMLLayout")
.immutableMap();

View File

@ -0,0 +1,100 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.slf4j;
import org.elasticsearch.util.logging.support.AbstractESLogger;
import org.slf4j.Logger;
/**
* @author kimchy (shay.banon)
*/
public class Slf4jESLogger extends AbstractESLogger {
private final Logger logger;
public Slf4jESLogger(String prefix, Logger logger) {
super(prefix);
this.logger = logger;
}
@Override public String getName() {
return logger.getName();
}
@Override public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
@Override public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
@Override public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
@Override protected void internalTrace(String msg) {
logger.trace(msg);
}
@Override protected void internalTrace(String msg, Throwable cause) {
logger.trace(msg, cause);
}
@Override protected void internalDebug(String msg) {
logger.debug(msg);
}
@Override protected void internalDebug(String msg, Throwable cause) {
logger.debug(msg, cause);
}
@Override protected void internalInfo(String msg) {
logger.info(msg);
}
@Override protected void internalInfo(String msg, Throwable cause) {
logger.info(msg, cause);
}
@Override protected void internalWarn(String msg) {
logger.warn(msg);
}
@Override protected void internalWarn(String msg, Throwable cause) {
logger.warn(msg, cause);
}
@Override protected void internalError(String msg) {
logger.error(msg);
}
@Override protected void internalError(String msg, Throwable cause) {
logger.error(msg, cause);
}
}

View File

@ -0,0 +1,34 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.slf4j;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.ESLoggerFactory;
import org.slf4j.LoggerFactory;
/**
* @author kimchy (shay.banon)
*/
public class Slf4jESLoggerFactory extends ESLoggerFactory {
@Override public ESLogger newInstance(String prefix, String name) {
return new Slf4jESLogger(prefix, LoggerFactory.getLogger(name));
}
}

View File

@ -0,0 +1,122 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.support;
import org.elasticsearch.util.logging.ESLogger;
/**
* @author kimchy (shay.banon)
*/
public abstract class AbstractESLogger implements ESLogger {
private final String prefix;
protected AbstractESLogger(String prefix) {
this.prefix = prefix;
}
@Override public String getPrefix() {
return this.prefix;
}
@Override public void trace(String msg, Object... params) {
if (isTraceEnabled()) {
internalTrace(LoggerMessageFormat.format(prefix, msg, params));
}
}
protected abstract void internalTrace(String msg);
@Override public void trace(String msg, Throwable cause, Object... params) {
if (isTraceEnabled()) {
internalTrace(LoggerMessageFormat.format(prefix, msg, params), cause);
}
}
protected abstract void internalTrace(String msg, Throwable cause);
@Override public void debug(String msg, Object... params) {
if (isDebugEnabled()) {
internalDebug(LoggerMessageFormat.format(prefix, msg, params));
}
}
protected abstract void internalDebug(String msg);
@Override public void debug(String msg, Throwable cause, Object... params) {
if (isDebugEnabled()) {
internalDebug(LoggerMessageFormat.format(prefix, msg, params), cause);
}
}
protected abstract void internalDebug(String msg, Throwable cause);
@Override public void info(String msg, Object... params) {
if (isInfoEnabled()) {
internalInfo(LoggerMessageFormat.format(prefix, msg, params));
}
}
protected abstract void internalInfo(String msg);
@Override public void info(String msg, Throwable cause, Object... params) {
if (isInfoEnabled()) {
internalInfo(LoggerMessageFormat.format(prefix, msg, params), cause);
}
}
protected abstract void internalInfo(String msg, Throwable cause);
@Override public void warn(String msg, Object... params) {
if (isWarnEnabled()) {
internalWarn(LoggerMessageFormat.format(prefix, msg, params));
}
}
protected abstract void internalWarn(String msg);
@Override public void warn(String msg, Throwable cause, Object... params) {
if (isWarnEnabled()) {
internalWarn(LoggerMessageFormat.format(prefix, msg, params), cause);
}
}
protected abstract void internalWarn(String msg, Throwable cause);
@Override public void error(String msg, Object... params) {
if (isErrorEnabled()) {
internalError(LoggerMessageFormat.format(prefix, msg, params));
}
}
protected abstract void internalError(String msg);
@Override public void error(String msg, Throwable cause, Object... params) {
if (isErrorEnabled()) {
internalError(LoggerMessageFormat.format(prefix, msg, params), cause);
}
}
protected abstract void internalError(String msg, Throwable cause);
}

View File

@ -0,0 +1,269 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.util.logging.support;
import java.util.HashMap;
import java.util.Map;
/**
* @author kimchy (shay.banon)
*/
public class LoggerMessageFormat {
static final char DELIM_START = '{';
static final char DELIM_STOP = '}';
static final String DELIM_STR = "{}";
private static final char ESCAPE_CHAR = '\\';
public static String format(final String messagePattern, final Object... argArray) {
return format(null, messagePattern, argArray);
}
public static String format(final String prefix, final String messagePattern, final Object... argArray) {
if (messagePattern == null) {
return null;
}
if (argArray == null) {
if (prefix == null) {
return messagePattern;
} else {
return prefix + messagePattern;
}
}
int i = 0;
int j;
StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50);
if (prefix != null) {
sbuf.append(prefix);
}
for (int L = 0; L < argArray.length; L++) {
j = messagePattern.indexOf(DELIM_STR, i);
if (j == -1) {
// no more variables
if (i == 0) { // this is a simple string
return messagePattern;
} else { // add the tail string which contains no variables and return
// the result.
sbuf.append(messagePattern.substring(i, messagePattern.length()));
return sbuf.toString();
}
} else {
if (isEscapedDelimeter(messagePattern, j)) {
if (!isDoubleEscaped(messagePattern, j)) {
L--; // DELIM_START was escaped, thus should not be incremented
sbuf.append(messagePattern.substring(i, j - 1));
sbuf.append(DELIM_START);
i = j + 1;
} else {
// The escape character preceding the delimiter start is
// itself escaped: "abc x:\\{}"
// we have to consume one backward slash
sbuf.append(messagePattern.substring(i, j - 1));
deeplyAppendParameter(sbuf, argArray[L], new HashMap());
i = j + 2;
}
} else {
// normal case
sbuf.append(messagePattern.substring(i, j));
deeplyAppendParameter(sbuf, argArray[L], new HashMap());
i = j + 2;
}
}
}
// append the characters following the last {} pair.
sbuf.append(messagePattern.substring(i, messagePattern.length()));
return sbuf.toString();
}
static boolean isEscapedDelimeter(String messagePattern,
int delimeterStartIndex) {
if (delimeterStartIndex == 0) {
return false;
}
char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
if (potentialEscape == ESCAPE_CHAR) {
return true;
} else {
return false;
}
}
static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
return true;
} else {
return false;
}
}
private static void deeplyAppendParameter(StringBuffer sbuf, Object o, Map seenMap) {
if (o == null) {
sbuf.append("null");
return;
}
if (!o.getClass().isArray()) {
safeObjectAppend(sbuf, o);
} else {
// check for primitive array types because they
// unfortunately cannot be cast to Object[]
if (o instanceof boolean[]) {
booleanArrayAppend(sbuf, (boolean[]) o);
} else if (o instanceof byte[]) {
byteArrayAppend(sbuf, (byte[]) o);
} else if (o instanceof char[]) {
charArrayAppend(sbuf, (char[]) o);
} else if (o instanceof short[]) {
shortArrayAppend(sbuf, (short[]) o);
} else if (o instanceof int[]) {
intArrayAppend(sbuf, (int[]) o);
} else if (o instanceof long[]) {
longArrayAppend(sbuf, (long[]) o);
} else if (o instanceof float[]) {
floatArrayAppend(sbuf, (float[]) o);
} else if (o instanceof double[]) {
doubleArrayAppend(sbuf, (double[]) o);
} else {
objectArrayAppend(sbuf, (Object[]) o, seenMap);
}
}
}
private static void safeObjectAppend(StringBuffer sbuf, Object o) {
try {
String oAsString = o.toString();
sbuf.append(oAsString);
} catch (Throwable t) {
System.err.println("Logger: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]");
t.printStackTrace();
sbuf.append("[FAILED toString()]");
}
}
private static void objectArrayAppend(StringBuffer sbuf, Object[] a, Map seenMap) {
sbuf.append('[');
if (!seenMap.containsKey(a)) {
seenMap.put(a, null);
final int len = a.length;
for (int i = 0; i < len; i++) {
deeplyAppendParameter(sbuf, a[i], seenMap);
if (i != len - 1)
sbuf.append(", ");
}
// allow repeats in siblings
seenMap.remove(a);
} else {
sbuf.append("...");
}
sbuf.append(']');
}
private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void byteArrayAppend(StringBuffer sbuf, byte[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void charArrayAppend(StringBuffer sbuf, char[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void shortArrayAppend(StringBuffer sbuf, short[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void intArrayAppend(StringBuffer sbuf, int[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void longArrayAppend(StringBuffer sbuf, long[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void floatArrayAppend(StringBuffer sbuf, float[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void doubleArrayAppend(StringBuffer sbuf, double[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
}

View File

@ -20,18 +20,18 @@
package org.elasticsearch.util.lucene;
import org.apache.lucene.index.IndexWriter;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.slf4j.Logger;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author kimchy (Shay Banon)
* @author kimchy (shay.banon)
*/
public abstract class IndexWriters {
private static Logger logger = Loggers.getLogger(IndexWriters.class);
private static ESLogger logger = Loggers.getLogger(IndexWriters.class);
private static Field docWriterField;

View File

@ -19,8 +19,8 @@
package org.elasticsearch.util.lucene;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.slf4j.Logger;
import java.io.OutputStream;
import java.io.PrintStream;
@ -40,9 +40,9 @@ public class LoggerInfoStream extends PrintStream {
/**
* Creates a new {@link LoggerInfoStream} based on the provided logger
* by appending to its {@link Logger#getName()} the {@link #SUFFIX}.
* by appending to its <tt>NAME</tt> the {@link #SUFFIX}.
*/
public static LoggerInfoStream getInfoStream(Logger logger) {
public static LoggerInfoStream getInfoStream(ESLogger logger) {
return new LoggerInfoStream(Loggers.getLogger(logger, SUFFIX));
}
@ -54,13 +54,13 @@ public class LoggerInfoStream extends PrintStream {
return new LoggerInfoStream(Loggers.getLogger(name + SUFFIX));
}
private final Logger logger;
private final ESLogger logger;
/**
* Constucts a new instance based on the provided logger. Will output
* each {@link #println(String)} operation as a trace level.
*/
public LoggerInfoStream(Logger logger) {
public LoggerInfoStream(ESLogger logger) {
super((OutputStream) null);
this.logger = logger;
}

View File

@ -23,7 +23,7 @@ import org.elasticsearch.util.MapBackedSet;
import org.elasticsearch.util.ReusableIterator;
import org.elasticsearch.util.ThreadRenamingRunnable;
import org.elasticsearch.util.concurrent.ConcurrentIdentityHashMap;
import org.slf4j.Logger;
import org.elasticsearch.util.logging.ESLogger;
import java.util.*;
import java.util.concurrent.ThreadFactory;
@ -71,7 +71,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
*/
public class HashedWheelTimer implements Timer {
private final Logger logger;
private final ESLogger logger;
private static final AtomicInteger id = new AtomicInteger();
@ -101,7 +101,7 @@ public class HashedWheelTimer implements Timer {
* @param tickDuration the duration between tick
* @param unit the time unit of the {@code tickDuration}
*/
public HashedWheelTimer(Logger logger, ThreadFactory threadFactory, long tickDuration, TimeUnit unit) {
public HashedWheelTimer(ESLogger logger, ThreadFactory threadFactory, long tickDuration, TimeUnit unit) {
this(logger, threadFactory, tickDuration, unit, 512);
}
@ -115,7 +115,7 @@ public class HashedWheelTimer implements Timer {
* @param unit the time unit of the {@code tickDuration}
* @param ticksPerWheel the size of the wheel
*/
public HashedWheelTimer(Logger logger, ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel) {
public HashedWheelTimer(ESLogger logger, ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel) {
this.logger = logger;
if (threadFactory == null) {

View File

@ -23,8 +23,8 @@ import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticSearchIllegalStateException;
import org.elasticsearch.util.io.stream.StreamInput;
import org.elasticsearch.util.io.stream.StreamOutput;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.slf4j.Logger;
import java.io.IOException;
import java.lang.reflect.Constructor;
@ -33,15 +33,15 @@ import static org.elasticsearch.util.MapBuilder.*;
/**
* A global registry of all different types of {@link org.elasticsearch.util.transport.TransportAddress} allowing
* to perfrom serialization of them.
* <p/>
* <p>By defualt, adds {@link org.elasticsearch.util.transport.InetSocketTransportAddress}.
* to perform serialization of them.
*
* <p>By default, adds {@link org.elasticsearch.util.transport.InetSocketTransportAddress}.
*
* @author kimchy (Shay Banon)
*/
public abstract class TransportAddressSerializers {
private static final Logger logger = Loggers.getLogger(TransportAddressSerializers.class);
private static final ESLogger logger = Loggers.getLogger(TransportAddressSerializers.class);
private static ImmutableMap<Short, Constructor<? extends TransportAddress>> addressConstructors = ImmutableMap.of();

View File

@ -25,9 +25,9 @@ import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.MutableShardRouting;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.transport.DummyTransportAddress;
import org.slf4j.Logger;
import org.testng.annotations.Test;
import java.util.List;
@ -47,7 +47,7 @@ import static org.hamcrest.Matchers.*;
@Test
public class FailedShardsRoutingTests {
private final Logger logger = Loggers.getLogger(FailedShardsRoutingTests.class);
private final ESLogger logger = Loggers.getLogger(FailedShardsRoutingTests.class);
@Test public void testFailures() {
DefaultShardsRoutingStrategy strategy = new DefaultShardsRoutingStrategy();

View File

@ -27,9 +27,9 @@ import org.elasticsearch.cluster.routing.MutableShardRouting;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.transport.DummyTransportAddress;
import org.slf4j.Logger;
import org.testng.annotations.Test;
import java.util.List;
@ -51,7 +51,7 @@ import static org.hamcrest.Matchers.*;
*/
public class SingleShardNoBackupsRoutingStrategyTests {
private final Logger logger = Loggers.getLogger(SingleShardNoBackupsRoutingStrategyTests.class);
private final ESLogger logger = Loggers.getLogger(SingleShardNoBackupsRoutingStrategyTests.class);
@Test public void testSingleIndexStartedShard() {
DefaultShardsRoutingStrategy strategy = new DefaultShardsRoutingStrategy();

View File

@ -24,9 +24,9 @@ import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.transport.DummyTransportAddress;
import org.slf4j.Logger;
import org.testng.annotations.Test;
import static org.elasticsearch.cluster.ClusterState.*;
@ -43,7 +43,7 @@ import static org.hamcrest.Matchers.*;
*/
public class SingleShardOneBackupRoutingStrategyTests {
private final Logger logger = Loggers.getLogger(SingleShardOneBackupRoutingStrategyTests.class);
private final ESLogger logger = Loggers.getLogger(SingleShardOneBackupRoutingStrategyTests.class);
@Test public void testSingleIndexFirstStartPrimaryThenBackups() {
DefaultShardsRoutingStrategy strategy = new DefaultShardsRoutingStrategy();

View File

@ -24,9 +24,9 @@ import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.transport.DummyTransportAddress;
import org.slf4j.Logger;
import org.testng.annotations.Test;
import static org.elasticsearch.cluster.ClusterState.*;
@ -43,7 +43,7 @@ import static org.hamcrest.Matchers.*;
*/
public class TenShardsOneBackupRoutingTests {
private final Logger logger = Loggers.getLogger(TenShardsOneBackupRoutingTests.class);
private final ESLogger logger = Loggers.getLogger(TenShardsOneBackupRoutingTests.class);
@Test public void testSingleIndexFirstStartPrimaryThenBackups() {
DefaultShardsRoutingStrategy strategy = new DefaultShardsRoutingStrategy();

View File

@ -21,9 +21,9 @@ package org.elasticsearch.test.integration;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.settings.Settings;
import org.slf4j.Logger;
import java.util.Map;
@ -34,7 +34,7 @@ import static org.elasticsearch.util.settings.ImmutableSettings.*;
public abstract class AbstractNodesTests {
protected final Logger logger = Loggers.getLogger(getClass());
protected final ESLogger logger = Loggers.getLogger(getClass());
private Map<String, Node> nodes = newHashMap();

View File

@ -28,9 +28,9 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.node.internal.InternalNode;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.elasticsearch.util.settings.Settings;
import org.slf4j.Logger;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@ -42,11 +42,11 @@ import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
/**
* @author kimchy (Shay Banon)
* @author kimchy (shay.banon)
*/
public class IndexLifecycleActionTests extends AbstractNodesTests {
private final Logger logger = Loggers.getLogger(IndexLifecycleActionTests.class);
private final ESLogger logger = Loggers.getLogger(IndexLifecycleActionTests.class);
@AfterMethod public void closeNodes() {
closeAllNodes();

View File

@ -23,8 +23,8 @@ import org.elasticsearch.action.admin.cluster.ping.broadcast.BroadcastPingRespon
import org.elasticsearch.action.admin.cluster.ping.replication.ReplicationPingResponse;
import org.elasticsearch.action.admin.cluster.ping.single.SinglePingResponse;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.slf4j.Logger;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@ -38,7 +38,7 @@ import static org.hamcrest.Matchers.*;
*/
public class PingActionTests extends AbstractNodesTests {
private final Logger logger = Loggers.getLogger(PingActionTests.class);
private final ESLogger logger = Loggers.getLogger(PingActionTests.class);
@BeforeMethod public void startNodes() {
startNode("server1");

View File

@ -20,7 +20,6 @@
package org.elasticsearch.util.testng;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.LoggerFactory;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
@ -30,7 +29,7 @@ import java.io.IOException;
import java.util.Properties;
/**
* @author kimchy (Shay Banon)
* @author kimchy (shay.banon)
*/
public class LoggingListener extends TestListenerAdapter {
@ -55,19 +54,19 @@ public class LoggingListener extends TestListenerAdapter {
}
PropertyConfigurator.configure(props);
LoggerFactory.getLogger("testng").info("========== Starting Test [" + result.getName() + "] ==========");
org.apache.log4j.Logger.getLogger("testng").info("========== Starting Test [" + result.getName() + "] ==========");
}
@Override public void onTestSuccess(ITestResult result) {
LoggerFactory.getLogger("testng").info("========== Test Success [" + result.getName() + "] ==========");
org.apache.log4j.Logger.getLogger("testng").info("========== Test Success [" + result.getName() + "] ==========");
}
@Override public void onTestFailure(ITestResult result) {
LoggerFactory.getLogger("testng").info("========== Test Failure [" + result.getName() + "] ==========");
org.apache.log4j.Logger.getLogger("testng").info("========== Test Failure [" + result.getName() + "] ==========");
}
@Override public void onTestSkipped(ITestResult result) {
LoggerFactory.getLogger("testng").info("========== Test Skipped [" + result.getName() + "] ==========");
org.apache.log4j.Logger.getLogger("testng").info("========== Test Skipped [" + result.getName() + "] ==========");
}
/**

View File

@ -23,8 +23,8 @@ import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.node.Node;
import org.elasticsearch.util.logging.ESLogger;
import org.elasticsearch.util.logging.Loggers;
import org.slf4j.Logger;
import org.testng.annotations.*;
import static org.elasticsearch.client.Requests.*;
@ -42,7 +42,7 @@ import static org.hamcrest.Matchers.*;
@Test
public class SimpleAttachmentIntegrationTests {
private final Logger logger = Loggers.getLogger(getClass());
private final ESLogger logger = Loggers.getLogger(getClass());
private Node node;

View File

@ -25,6 +25,7 @@ import org.elasticsearch.http.BindHttpException;
import org.elasticsearch.memcached.MemcachedServerTransport;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.transport.BindTransportException;
import org.elasticsearch.transport.netty.NettyInternalESLoggerFactory;
import org.elasticsearch.util.SizeValue;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
import org.elasticsearch.util.settings.Settings;
@ -39,7 +40,6 @@ import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Slf4JLoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
@ -56,7 +56,7 @@ import static org.elasticsearch.util.io.HostResolver.*;
public class NettyMemcachedServerTransport extends AbstractLifecycleComponent<MemcachedServerTransport> implements MemcachedServerTransport {
static {
InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory() {
InternalLoggerFactory.setDefaultFactory(new NettyInternalESLoggerFactory() {
@Override public InternalLogger newInstance(String name) {
return super.newInstance(name.replace("org.jboss.netty.", "netty."));
}