diff options
author | Simon Brandhof <simon.brandhof@sonarsource.com> | 2015-02-18 12:13:34 +0100 |
---|---|---|
committer | Simon Brandhof <simon.brandhof@sonarsource.com> | 2015-02-19 12:08:25 +0100 |
commit | d5a8ab383c56026165e995d62fbbeb0bed790d53 (patch) | |
tree | 81085987cadbaca5d1ed3bba4fe8a62e6fdf5ab0 | |
parent | 6adb553ddc2711cb88632be9bd96b4e91c51082e (diff) | |
download | sonarqube-d5a8ab383c56026165e995d62fbbeb0bed790d53.tar.gz sonarqube-d5a8ab383c56026165e995d62fbbeb0bed790d53.zip |
SONAR-6194 SONAR-5009 profiling api + unique property sonar.log.level
113 files changed, 1566 insertions, 1450 deletions
diff --git a/server/sonar-process-monitor/src/test/resources/org/sonar/process/ProcessTest/sonar.properties b/server/sonar-process-monitor/src/test/resources/org/sonar/process/ProcessTest/sonar.properties index 1577a214b3b..4d323dabfef 100644 --- a/server/sonar-process-monitor/src/test/resources/org/sonar/process/ProcessTest/sonar.properties +++ b/server/sonar-process-monitor/src/test/resources/org/sonar/process/ProcessTest/sonar.properties @@ -198,11 +198,6 @@ sonar.jdbc.timeBetweenEvictionRunsMillis=30000 #sonar.notifications.delay=60 -#-------------------------------------------------------------------------------------------------- -# PROFILING -# Level of information displayed in the logs: NONE (default), BASIC (functional information) and FULL (functional and technical details) -#sonar.log.profilingLevel=NONE - #-------------------------------------------------------------------------------------------------- # DEVELOPMENT MODE diff --git a/server/sonar-process/src/test/resources/org/sonar/process/ProcessTest/sonar.properties b/server/sonar-process/src/test/resources/org/sonar/process/ProcessTest/sonar.properties index 1577a214b3b..4d323dabfef 100644 --- a/server/sonar-process/src/test/resources/org/sonar/process/ProcessTest/sonar.properties +++ b/server/sonar-process/src/test/resources/org/sonar/process/ProcessTest/sonar.properties @@ -198,11 +198,6 @@ sonar.jdbc.timeBetweenEvictionRunsMillis=30000 #sonar.notifications.delay=60 -#-------------------------------------------------------------------------------------------------- -# PROFILING -# Level of information displayed in the logs: NONE (default), BASIC (functional information) and FULL (functional and technical details) -#sonar.log.profilingLevel=NONE - #-------------------------------------------------------------------------------------------------- # DEVELOPMENT MODE diff --git a/server/sonar-server/src/main/java/org/sonar/server/app/WebLogging.java b/server/sonar-server/src/main/java/org/sonar/server/app/WebLogging.java index f2333792413..a434e44159c 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/app/WebLogging.java +++ b/server/sonar-server/src/main/java/org/sonar/server/app/WebLogging.java @@ -24,6 +24,7 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.ConsoleAppender; import org.slf4j.bridge.SLF4JBridgeHandler; +import org.sonar.api.utils.MessageException; import org.sonar.process.LogbackHelper; import org.sonar.process.Props; @@ -35,7 +36,8 @@ import java.util.logging.LogManager; */ class WebLogging { - private static final String LOG_FORMAT = "%d{yyyy.MM.dd HH:mm:ss} %-5level web[%logger{20}] %X %msg%n"; + private static final String LOG_FORMAT = "%d{yyyy.MM.dd HH:mm:ss} %-5level web[%logger{20}] %msg%n"; + public static final String LOG_LEVEL_PROPERTY = "sonar.log.level"; private final LogbackHelper helper = new LogbackHelper(); @@ -72,7 +74,17 @@ class WebLogging { helper.configureLogger(ctx, "org.elasticsearch.node", Level.INFO); helper.configureLogger(ctx, "org.elasticsearch.http", Level.INFO); helper.configureLogger(ctx, "ch.qos.logback", Level.WARN); - boolean debug = props.valueAsBoolean("sonar.log.debug", false); - helper.configureLogger(ctx, Logger.ROOT_LOGGER_NAME, debug ? Level.DEBUG : Level.INFO); + String levelCode = props.value(LOG_LEVEL_PROPERTY, "INFO"); + Level level; + if ("TRACE".equals(levelCode)) { + level = Level.TRACE; + } else if ("DEBUG".equals(levelCode)) { + level = Level.DEBUG; + } else if ("INFO".equals(levelCode)) { + level = Level.INFO; + } else { + throw MessageException.of(String.format("Unsupported log level: %s. Please check property %s", levelCode, LOG_LEVEL_PROPERTY)); + } + helper.configureLogger(ctx, Logger.ROOT_LOGGER_NAME, level); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/ComputationService.java b/server/sonar-server/src/main/java/org/sonar/server/computation/ComputationService.java index b0f60f1d6b7..2f8f2cce6ca 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/ComputationService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/ComputationService.java @@ -22,11 +22,11 @@ package org.sonar.server.computation; import com.google.common.base.Throwables; import org.apache.commons.lang.ArrayUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.sonar.api.ServerComponent; import org.sonar.api.utils.System2; import org.sonar.api.utils.TimeProfiler; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; import org.sonar.core.activity.Activity; import org.sonar.core.component.ComponentDto; import org.sonar.core.computation.db.AnalysisReportDto; @@ -39,7 +39,7 @@ import org.sonar.server.db.DbClient; public class ComputationService implements ServerComponent { - private static final Logger LOG = Loggers.get(ComputationService.class); + private static final Logger LOG = LoggerFactory.getLogger(ComputationService.class); private final DbClient dbClient; private final ComputationSteps steps; diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/EsClient.java b/server/sonar-server/src/main/java/org/sonar/server/es/EsClient.java index f20f3fdc7d3..30ef5b63da7 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/EsClient.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/EsClient.java @@ -48,8 +48,28 @@ import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.metrics.max.Max; import org.picocontainer.Startable; -import org.sonar.core.profiling.Profiling; -import org.sonar.server.es.request.*; +import org.sonar.api.utils.log.Logger; +import org.sonar.api.utils.log.Loggers; +import org.sonar.server.es.request.ProxyBulkRequestBuilder; +import org.sonar.server.es.request.ProxyClearCacheRequestBuilder; +import org.sonar.server.es.request.ProxyClusterHealthRequestBuilder; +import org.sonar.server.es.request.ProxyClusterStateRequestBuilder; +import org.sonar.server.es.request.ProxyClusterStatsRequestBuilder; +import org.sonar.server.es.request.ProxyCountRequestBuilder; +import org.sonar.server.es.request.ProxyCreateIndexRequestBuilder; +import org.sonar.server.es.request.ProxyDeleteByQueryRequestBuilder; +import org.sonar.server.es.request.ProxyDeleteRequestBuilder; +import org.sonar.server.es.request.ProxyFlushRequestBuilder; +import org.sonar.server.es.request.ProxyGetRequestBuilder; +import org.sonar.server.es.request.ProxyIndexRequestBuilder; +import org.sonar.server.es.request.ProxyIndicesExistsRequestBuilder; +import org.sonar.server.es.request.ProxyIndicesStatsRequestBuilder; +import org.sonar.server.es.request.ProxyMultiGetRequestBuilder; +import org.sonar.server.es.request.ProxyNodesStatsRequestBuilder; +import org.sonar.server.es.request.ProxyPutMappingRequestBuilder; +import org.sonar.server.es.request.ProxyRefreshRequestBuilder; +import org.sonar.server.es.request.ProxySearchRequestBuilder; +import org.sonar.server.es.request.ProxySearchScrollRequestBuilder; import org.sonar.server.search.ClusterHealth; import org.sonar.server.search.SearchClient; @@ -59,16 +79,14 @@ import org.sonar.server.search.SearchClient; */ public class EsClient implements Startable { - private final Profiling profiling; + public static final Logger LOGGER = Loggers.get("es"); private final Client client; public EsClient(SearchClient deprecatedClient) { - this.profiling = deprecatedClient.getProfiling(); this.client = deprecatedClient; } - EsClient(Profiling profiling, Client client) { - this.profiling = profiling; + EsClient(Client client) { this.client = client; } @@ -86,31 +104,31 @@ public class EsClient implements Startable { } public RefreshRequestBuilder prepareRefresh(String... indices) { - return new ProxyRefreshRequestBuilder(client, profiling).setIndices(indices); + return new ProxyRefreshRequestBuilder(client).setIndices(indices); } public FlushRequestBuilder prepareFlush(String... indices) { - return new ProxyFlushRequestBuilder(client, profiling).setIndices(indices); + return new ProxyFlushRequestBuilder(client).setIndices(indices); } public IndicesStatsRequestBuilder prepareStats(String... indices) { - return new ProxyIndicesStatsRequestBuilder(client, profiling).setIndices(indices); + return new ProxyIndicesStatsRequestBuilder(client).setIndices(indices); } public NodesStatsRequestBuilder prepareNodesStats(String... nodesIds) { - return new ProxyNodesStatsRequestBuilder(client, profiling).setNodesIds(nodesIds); + return new ProxyNodesStatsRequestBuilder(client).setNodesIds(nodesIds); } public ClusterStatsRequestBuilder prepareClusterStats() { - return new ProxyClusterStatsRequestBuilder(client, profiling); + return new ProxyClusterStatsRequestBuilder(client); } public ClusterStateRequestBuilder prepareState() { - return new ProxyClusterStateRequestBuilder(client, profiling); + return new ProxyClusterStateRequestBuilder(client); } public ClusterHealthRequestBuilder prepareHealth(String... indices) { - return new ProxyClusterHealthRequestBuilder(client, profiling).setIndices(indices); + return new ProxyClusterHealthRequestBuilder(client).setIndices(indices); } public void waitForStatus(ClusterHealthStatus status) { @@ -118,55 +136,55 @@ public class EsClient implements Startable { } public IndicesExistsRequestBuilder prepareIndicesExist(String... indices) { - return new ProxyIndicesExistsRequestBuilder(client, profiling, indices); + return new ProxyIndicesExistsRequestBuilder(client, indices); } public CreateIndexRequestBuilder prepareCreate(String index) { - return new ProxyCreateIndexRequestBuilder(client, profiling, index); + return new ProxyCreateIndexRequestBuilder(client, index); } public PutMappingRequestBuilder preparePutMapping(String... indices) { - return new ProxyPutMappingRequestBuilder(client, profiling).setIndices(indices); + return new ProxyPutMappingRequestBuilder(client).setIndices(indices); } public SearchRequestBuilder prepareSearch(String... indices) { - return new ProxySearchRequestBuilder(client, profiling).setIndices(indices); + return new ProxySearchRequestBuilder(client).setIndices(indices); } public SearchScrollRequestBuilder prepareSearchScroll(String scrollId) { - return new ProxySearchScrollRequestBuilder(scrollId, client, profiling); + return new ProxySearchScrollRequestBuilder(scrollId, client); } public GetRequestBuilder prepareGet() { - return new ProxyGetRequestBuilder(client, profiling); + return new ProxyGetRequestBuilder(client); } public GetRequestBuilder prepareGet(String index, String type, String id) { - return new ProxyGetRequestBuilder(client, profiling).setIndex(index).setType(type).setId(id); + return new ProxyGetRequestBuilder(client).setIndex(index).setType(type).setId(id); } public MultiGetRequestBuilder prepareMultiGet() { - return new ProxyMultiGetRequestBuilder(client, profiling); + return new ProxyMultiGetRequestBuilder(client); } public CountRequestBuilder prepareCount(String... indices) { - return new ProxyCountRequestBuilder(client, profiling).setIndices(indices); + return new ProxyCountRequestBuilder(client).setIndices(indices); } public BulkRequestBuilder prepareBulk() { - return new ProxyBulkRequestBuilder(client, profiling); + return new ProxyBulkRequestBuilder(client); } public DeleteRequestBuilder prepareDelete(String index, String type, String id) { - return new ProxyDeleteRequestBuilder(profiling, client, index).setType(type).setId(id); + return new ProxyDeleteRequestBuilder(client, index).setType(type).setId(id); } public DeleteByQueryRequestBuilder prepareDeleteByQuery(String... indices) { - return new ProxyDeleteByQueryRequestBuilder(client, profiling).setIndices(indices); + return new ProxyDeleteByQueryRequestBuilder(client).setIndices(indices); } public IndexRequestBuilder prepareIndex(String index, String type) { - return new ProxyIndexRequestBuilder(client, profiling).setIndex(index).setType(type); + return new ProxyIndexRequestBuilder(client).setIndex(index).setType(type); } public OptimizeRequestBuilder prepareOptimize(String indexName) { @@ -177,7 +195,7 @@ public class EsClient implements Startable { } public ClearIndicesCacheRequestBuilder prepareClearCache(String... indices) { - return new ProxyClearCacheRequestBuilder(client, profiling).setIndices(indices); + return new ProxyClearCacheRequestBuilder(client).setIndices(indices); } public long getLastUpdatedAt(String indexName, String typeName) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyBulkRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyBulkRequestBuilder.java index 66aee7b890e..6ace4a6579b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyBulkRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyBulkRequestBuilder.java @@ -22,8 +22,6 @@ package org.sonar.server.es.request; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset.Entry; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ListenableActionFuture; import org.elasticsearch.action.bulk.BulkRequestBuilder; @@ -33,30 +31,27 @@ import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; import java.util.Set; public class ProxyBulkRequestBuilder extends BulkRequestBuilder { - private final Profiling profiling; - - public ProxyBulkRequestBuilder(Client client, Profiling profiling) { + public ProxyBulkRequestBuilder(Client client) { super(client); - this.profiling = profiling; } @Override public BulkResponse get() { - StopWatch fullProfile = profiling.start("bulk", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } @@ -86,7 +81,7 @@ public class ProxyBulkRequestBuilder extends BulkRequestBuilder { StringBuilder message = new StringBuilder(); message.append("Bulk["); HashMultiset<BulkRequestKey> groupedRequests = HashMultiset.create(); - for (int i=0 ; i<request.requests().size() ; i++) { + for (int i = 0; i < request.requests().size(); i++) { ActionRequest item = request.requests().get(i); String requestType, index, docType; if (item instanceof IndexRequest) { @@ -138,13 +133,29 @@ public class ProxyBulkRequestBuilder extends BulkRequestBuilder { } @Override - public boolean equals(Object obj) { - return EqualsBuilder.reflectionEquals(this, obj); + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BulkRequestKey that = (BulkRequestKey) o; + if (!docType.equals(that.docType)) { + return false; + } + if (!index.equals(that.index)) { + return false; + } + return requestType.equals(that.requestType); } @Override public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); + int result = requestType.hashCode(); + result = 31 * result + index.hashCode(); + result = 31 * result + docType.hashCode(); + return result; } @Override diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilder.java index 298f2ea4ca3..9011db4c5cd 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheReque import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyClearCacheRequestBuilder extends ClearIndicesCacheRequestBuilder { - private final Profiling profiling; - - public ProxyClearCacheRequestBuilder(Client client, Profiling profiling) { + public ProxyClearCacheRequestBuilder(Client client) { super(client.admin().indices()); - this.profiling = profiling; } @Override public ClearIndicesCacheResponse get() { - StopWatch fullProfile = profiling.start("clear cache", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.FULL)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilder.java index e141bc98fd8..feef18b14d9 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyClusterHealthRequestBuilder extends ClusterHealthRequestBuilder { - private final Profiling profiling; - - public ProxyClusterHealthRequestBuilder(Client client, Profiling profiling) { + public ProxyClusterHealthRequestBuilder(Client client) { super(client.admin().cluster()); - this.profiling = profiling; } @Override public ClusterHealthResponse get() { - StopWatch fullProfile = profiling.start("cluster health", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilder.java index c425e580ccb..f1b40fd7064 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.cluster.state.ClusterStateRequestBuilder; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyClusterStateRequestBuilder extends ClusterStateRequestBuilder { - private final Profiling profiling; - - public ProxyClusterStateRequestBuilder(Client client, Profiling profiling) { + public ProxyClusterStateRequestBuilder(Client client) { super(client.admin().cluster()); - this.profiling = profiling; } @Override public ClusterStateResponse get() { - StopWatch fullProfile = profiling.start("cluster state", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilder.java index 15f15c9c3ef..14312f5de90 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequestBuilder; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyClusterStatsRequestBuilder extends ClusterStatsRequestBuilder { - private final Profiling profiling; - - public ProxyClusterStatsRequestBuilder(Client client, Profiling profiling) { + public ProxyClusterStatsRequestBuilder(Client client) { super(client.admin().cluster()); - this.profiling = profiling; } @Override public ClusterStatsResponse get() { - StopWatch fullProfile = profiling.start("cluster stats", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCountRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCountRequestBuilder.java index 0c808787004..e29fea74219 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCountRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCountRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.count.CountRequestBuilder; import org.elasticsearch.action.count.CountResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyCountRequestBuilder extends CountRequestBuilder { - private final Profiling profiling; - - public ProxyCountRequestBuilder(Client client, Profiling profiling) { + public ProxyCountRequestBuilder(Client client) { super(client); - this.profiling = profiling; } @Override public CountResponse get() { - StopWatch fullProfile = profiling.start("count", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilder.java index c99462b0baa..5640b011df5 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilder.java @@ -25,30 +25,28 @@ import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyCreateIndexRequestBuilder extends CreateIndexRequestBuilder { - private final Profiling profiling; private final String index; - public ProxyCreateIndexRequestBuilder(Client client, Profiling profiling, String index) { + public ProxyCreateIndexRequestBuilder(Client client, String index) { super(client.admin().indices(), index); - this.profiling = profiling; this.index = index; } @Override public CreateIndexResponse get() { - StopWatch fullProfile = profiling.start("create index", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilder.java index 0d1474e66ff..9079114c28f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilder.java @@ -30,32 +30,29 @@ import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilder; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; import java.io.IOException; public class ProxyDeleteByQueryRequestBuilder extends DeleteByQueryRequestBuilder { - private final Profiling profiling; - private QueryBuilder internalBuilder; - public ProxyDeleteByQueryRequestBuilder(Client client, Profiling profiling) { + public ProxyDeleteByQueryRequestBuilder(Client client) { super(client); - this.profiling = profiling; } @Override public DeleteByQueryResponse get() { - StopWatch fullProfile = profiling.start("delete by query", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteRequestBuilder.java index 88e9d32ffae..70389a14560 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyDeleteRequestBuilder.java @@ -24,28 +24,25 @@ import org.elasticsearch.action.delete.DeleteRequestBuilder; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyDeleteRequestBuilder extends DeleteRequestBuilder { - private final Profiling profiling; - - public ProxyDeleteRequestBuilder(Profiling profiling, Client client, String index) { + public ProxyDeleteRequestBuilder(Client client, String index) { super(client, index); - this.profiling = profiling; } @Override public DeleteResponse get() { - StopWatch fullProfile = profiling.start("delete", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyFlushRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyFlushRequestBuilder.java index 65eed7aa771..e07f0643c08 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyFlushRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyFlushRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.indices.flush.FlushRequestBuilder; import org.elasticsearch.action.admin.indices.flush.FlushResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyFlushRequestBuilder extends FlushRequestBuilder { - private final Profiling profiling; - - public ProxyFlushRequestBuilder(Client client, Profiling profiling) { + public ProxyFlushRequestBuilder(Client client) { super(client.admin().indices()); - this.profiling = profiling; } @Override public FlushResponse get() { - StopWatch fullProfile = profiling.start("flush", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyGetRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyGetRequestBuilder.java index 7aa23889e18..e2a45b60e9f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyGetRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyGetRequestBuilder.java @@ -25,28 +25,25 @@ import org.elasticsearch.action.get.GetRequestBuilder; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyGetRequestBuilder extends GetRequestBuilder { - private final Profiling profiling; - - public ProxyGetRequestBuilder(Client client, Profiling profiling) { + public ProxyGetRequestBuilder(Client client) { super(client); - this.profiling = profiling; } @Override public GetResponse get() { - StopWatch fullProfile = profiling.start("get", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndexRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndexRequestBuilder.java index e9987f6759f..a9404f77b19 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndexRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndexRequestBuilder.java @@ -24,28 +24,25 @@ import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyIndexRequestBuilder extends IndexRequestBuilder { - private final Profiling profiling; - - public ProxyIndexRequestBuilder(Client client, Profiling profiling) { + public ProxyIndexRequestBuilder(Client client) { super(client); - this.profiling = profiling; } @Override public IndexResponse get() { - StopWatch fullProfile = profiling.start("index", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.FULL)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilder.java index 49f8443ab67..b91561d16ba 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsReques import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyIndicesExistsRequestBuilder extends IndicesExistsRequestBuilder { - private final Profiling profiling; - - public ProxyIndicesExistsRequestBuilder(Client client, Profiling profiling, String... indices) { + public ProxyIndicesExistsRequestBuilder(Client client, String... indices) { super(client.admin().indices(), indices); - this.profiling = profiling; } @Override public IndicesExistsResponse get() { - StopWatch fullProfile = profiling.start("indices exists", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilder.java index 3bf1994f6cf..877e7c1af02 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequestBuilder; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyIndicesStatsRequestBuilder extends IndicesStatsRequestBuilder { - private final Profiling profiling; - - public ProxyIndicesStatsRequestBuilder(Client client, Profiling profiling) { + public ProxyIndicesStatsRequestBuilder(Client client) { super(client.admin().indices()); - this.profiling = profiling; } @Override public IndicesStatsResponse get() { - StopWatch fullProfile = profiling.start("indices stats", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilder.java index d30e2aa81b9..1115684274f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.get.MultiGetRequestBuilder; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyMultiGetRequestBuilder extends MultiGetRequestBuilder { - private final Profiling profiling; - - public ProxyMultiGetRequestBuilder(Client client, Profiling profiling) { + public ProxyMultiGetRequestBuilder(Client client) { super(client); - this.profiling = profiling; } @Override public MultiGetResponse get() { - StopWatch fullProfile = profiling.start("get", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilder.java index dfa01b78cb3..cdb874f7af2 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequestBuilde import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyNodesStatsRequestBuilder extends NodesStatsRequestBuilder { - private final Profiling profiling; - - public ProxyNodesStatsRequestBuilder(Client client, Profiling profiling) { + public ProxyNodesStatsRequestBuilder(Client client) { super(client.admin().cluster()); - this.profiling = profiling; } @Override public NodesStatsResponse get() { - StopWatch fullProfile = profiling.start("nodes stats", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilder.java index 8a9699a0802..68546827a67 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuild import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyPutMappingRequestBuilder extends PutMappingRequestBuilder { - private final Profiling profiling; - - public ProxyPutMappingRequestBuilder(Client client, Profiling profiling) { + public ProxyPutMappingRequestBuilder(Client client) { super(client.admin().indices()); - this.profiling = profiling; } @Override public PutMappingResponse get() { - StopWatch fullProfile = profiling.start("put mapping", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyRefreshRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyRefreshRequestBuilder.java index da888cb6598..2f5821867f8 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyRefreshRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxyRefreshRequestBuilder.java @@ -26,28 +26,25 @@ import org.elasticsearch.action.admin.indices.refresh.RefreshRequestBuilder; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxyRefreshRequestBuilder extends RefreshRequestBuilder { - private final Profiling profiling; - - public ProxyRefreshRequestBuilder(Client client, Profiling profiling) { + public ProxyRefreshRequestBuilder(Client client) { super(client.admin().indices()); - this.profiling = profiling; } @Override public RefreshResponse get() { - StopWatch fullProfile = profiling.start("refresh", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchRequestBuilder.java index 3676494e336..2a000de2ea0 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchRequestBuilder.java @@ -28,31 +28,28 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; import java.io.IOException; import java.util.Arrays; public class ProxySearchRequestBuilder extends SearchRequestBuilder { - private final Profiling profiling; - - public ProxySearchRequestBuilder(Client client, Profiling profiling) { + public ProxySearchRequestBuilder(Client client) { super(client); - this.profiling = profiling; } @Override public SearchResponse get() { - StopWatch fullProfile = profiling.start("search", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilder.java b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilder.java index dbaa4aa45ff..58dbfd1826a 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilder.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilder.java @@ -25,28 +25,25 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequestBuilder; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; +import org.sonar.server.es.EsClient; public class ProxySearchScrollRequestBuilder extends SearchScrollRequestBuilder { - private final Profiling profiling; - - public ProxySearchScrollRequestBuilder(String scrollId, Client client, Profiling profiling) { + public ProxySearchScrollRequestBuilder(String scrollId, Client client) { super(client, scrollId); - this.profiling = profiling; } @Override public SearchResponse get() { - StopWatch fullProfile = profiling.start("search scroll", Profiling.Level.FULL); + Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return super.execute().actionGet(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute %s", toString()), e); } finally { - if (profiling.isProfilingEnabled(Profiling.Level.BASIC)) { - fullProfile.stop("%s", toString()); + if (profiler.isTraceEnabled()) { + profiler.stopTrace(toString()); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/measure/MeasureFilterEngine.java b/server/sonar-server/src/main/java/org/sonar/server/measure/MeasureFilterEngine.java index c935e136b1d..332c7081f14 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/measure/MeasureFilterEngine.java +++ b/server/sonar-server/src/main/java/org/sonar/server/measure/MeasureFilterEngine.java @@ -20,43 +20,36 @@ package org.sonar.server.measure; import com.google.common.base.Joiner; -import org.apache.commons.lang.SystemUtils; import org.sonar.api.ServerComponent; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.Profiling.Level; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; import javax.annotation.Nullable; - import java.util.List; import java.util.Map; public class MeasureFilterEngine implements ServerComponent { - private static final Logger LOG = Loggers.get("org.sonar.MEASURE_FILTER"); + private static final Logger LOG = Loggers.get("MeasureFilter"); private final MeasureFilterFactory factory; private final MeasureFilterExecutor executor; - private final Profiling profiling; - public MeasureFilterEngine(MeasureFilterFactory factory, MeasureFilterExecutor executor, Profiling profiling) { + public MeasureFilterEngine(MeasureFilterFactory factory, MeasureFilterExecutor executor) { this.executor = executor; this.factory = factory; - this.profiling = profiling; } public MeasureFilterResult execute(Map<String, Object> filterMap, @Nullable Long userId) { - StopWatch watch = profiling.start("measures", Level.BASIC); - StopWatch sqlWatch = null; + Profiler profiler = Profiler.createIfDebug(LOG).start(); MeasureFilterResult result = new MeasureFilterResult(); MeasureFilterContext context = new MeasureFilterContext(); context.setUserId(userId); context.setData(String.format("{%s}", Joiner.on('|').withKeyValueSeparator("=").join(filterMap))); try { + profiler.addContext("request", context.getData()); MeasureFilter filter = factory.create(filterMap); - sqlWatch = profiling.start("sql", Level.FULL); List<MeasureFilterRow> rows = executor.execute(filter, context); result.setRows(rows); @@ -67,20 +60,9 @@ public class MeasureFilterEngine implements ServerComponent { result.setError(MeasureFilterResult.Error.UNKNOWN); LOG.error("Fail to execute measure filter: " + context, e); } finally { - if (sqlWatch != null) { - sqlWatch.stop(context.getSql()); - } - watch.stop(log(context, result)); + profiler.addContext("result", result.toString()); + profiler.stopDebug("Measure filter executed"); } return result; } - - private String log(MeasureFilterContext context, MeasureFilterResult result) { - StringBuilder log = new StringBuilder(); - log.append(SystemUtils.LINE_SEPARATOR); - log.append("request: ").append(context.getData()).append(SystemUtils.LINE_SEPARATOR); - log.append(" result: ").append(result.toString()); - return log.toString(); - } - } diff --git a/server/sonar-server/src/main/java/org/sonar/server/notifications/NotificationService.java b/server/sonar-server/src/main/java/org/sonar/server/notifications/NotificationService.java index f832d51127d..58d52639dc0 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/notifications/NotificationService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/notifications/NotificationService.java @@ -31,7 +31,6 @@ import org.sonar.api.config.Settings; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.notifications.NotificationDispatcher; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.core.notification.DefaultNotificationManager; @@ -70,8 +69,6 @@ public class NotificationService implements ServerComponent, Startable { public static final String PROPERTY_DELAY = "sonar.notifications.delay"; public static final String PROPERTY_DELAY_BEFORE_REPORTING_STATUS = "sonar.notifications.runningDelayBeforeReportingStatus"; - private static final TimeProfiler TIME_PROFILER = new TimeProfiler(LOG).setLevelToDebug(); - private final long delayInSeconds; private final long delayBeforeReportingStatusInSeconds; private final DefaultNotificationManager manager; @@ -129,7 +126,6 @@ public class NotificationService implements ServerComponent, Startable { @VisibleForTesting synchronized void processQueue() { - TIME_PROFILER.start("Processing notifications queue"); long start = now(); long lastLog = start; long notifSentCount = 0; @@ -150,8 +146,6 @@ public class NotificationService implements ServerComponent, Startable { } notifToSend = manager.getFromQueue(); } - - TIME_PROFILER.stop(); } @VisibleForTesting diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ProfilingFilter.java b/server/sonar-server/src/main/java/org/sonar/server/platform/ProfilingFilter.java index a462c4509a1..c4d9aa1e584 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ProfilingFilter.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/ProfilingFilter.java @@ -20,16 +20,19 @@ package org.sonar.server.platform; -import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import org.apache.commons.lang.StringUtils; -import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.Profiling.Level; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; -import javax.servlet.*; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; + import java.io.IOException; import java.util.Set; @@ -49,6 +52,7 @@ public class ProfilingFilter implements Filter { private static final String MESSAGE_WITH_QUERY = "%s %s?%s"; private static final String MESSAGE_WITHOUT_QUERY = "%s %s"; + public static final org.sonar.api.utils.log.Logger Logger = Loggers.get("http"); private String contextRoot; private Set<String> staticResourceDirs; @@ -76,12 +80,15 @@ public class ProfilingFilter implements Filter { // Static resource, not profiled chain.doFilter(request, response); } else { - StopWatch watch = getProfiling().start("http", Level.BASIC); + Profiler profiler = Profiler.createIfDebug(Logger).start(); try { chain.doFilter(request, response); } finally { - String queryString = httpRequest.getQueryString(); - watch.stop(queryString == null ? MESSAGE_WITHOUT_QUERY : MESSAGE_WITH_QUERY, httpRequest.getMethod(), requestUri, queryString); + if (profiler.isDebugEnabled()) { + String queryString = httpRequest.getQueryString(); + String message = String.format(queryString == null ? MESSAGE_WITHOUT_QUERY : MESSAGE_WITH_QUERY, httpRequest.getMethod(), requestUri, queryString); + profiler.stopDebug(message); + } } } } else { @@ -106,13 +113,4 @@ public class ProfilingFilter implements Filter { public void destroy() { // Nothing } - - @VisibleForTesting - Profiling getProfiling() { - Profiling profiling = Platform.component(Profiling.class); - if (profiling != null) { - return profiling; - } - return new Profiling(new Settings()); - } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java b/server/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java index f6f1357628b..288a7cbee5b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java @@ -54,7 +54,6 @@ import org.sonar.core.metric.DefaultMetricFinder; import org.sonar.core.notification.DefaultNotificationManager; import org.sonar.core.permission.PermissionFacade; import org.sonar.core.persistence.*; -import org.sonar.core.profiling.Profiling; import org.sonar.core.purge.PurgeProfiler; import org.sonar.core.qualitygate.db.ProjectQgateAssociationDao; import org.sonar.core.qualitygate.db.QualityGateConditionDao; @@ -177,7 +176,6 @@ import org.sonar.server.test.ws.*; import org.sonar.server.text.MacroInterpreter; import org.sonar.server.text.RubyTextService; import org.sonar.server.ui.JRubyI18n; -import org.sonar.server.ui.JRubyProfiling; import org.sonar.server.ui.PageDecorations; import org.sonar.server.ui.Views; import org.sonar.server.updatecenter.ws.UpdateCenterWs; @@ -222,8 +220,6 @@ class ServerComponents { ServerSettings.class, ServerImpl.class, Logback.class, - Profiling.class, - JRubyProfiling.class, EmbeddedDatabaseFactory.class, DefaultDatabase.class, DatabaseChecker.class, diff --git a/server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginJarsInstaller.java b/server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginJarsInstaller.java index 1d23bfebe59..93273c9b666 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginJarsInstaller.java +++ b/server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginJarsInstaller.java @@ -28,9 +28,9 @@ import org.sonar.api.platform.PluginMetadata; import org.sonar.api.platform.Server; import org.sonar.api.platform.ServerUpgradeStatus; import org.sonar.api.utils.MessageException; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.core.plugins.DefaultPluginMetadata; import org.sonar.server.platform.DefaultServerFileSystem; import org.sonar.updatecenter.common.PluginReferential; @@ -64,14 +64,14 @@ public class ServerPluginJarsInstaller { } public void install() { - TimeProfiler profiler = new TimeProfiler().start("Install plugins"); + Profiler profiler = Profiler.create(LOG).startInfo("Install plugins"); deleteTrash(); loadInstalledPlugins(); copyBundledPlugins(); moveDownloadedPlugins(); loadCorePlugins(); deployPlugins(); - profiler.stop(); + profiler.stopDebug(); } private void deleteTrash() { diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java index 7ee0390bc9e..4655acaf905 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java @@ -31,10 +31,10 @@ import org.sonar.api.profiles.RulesProfile; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.ActiveRuleParam; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.ValidationMessages; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.core.persistence.DbSession; import org.sonar.core.qualityprofile.db.QualityProfileDto; import org.sonar.core.template.LoadedTemplateDto; @@ -42,7 +42,6 @@ import org.sonar.server.db.DbClient; import org.sonar.server.platform.PersistentSettings; import javax.annotation.Nullable; - import java.util.Collection; import java.util.Collections; import java.util.List; @@ -69,13 +68,13 @@ public class RegisterQualityProfiles implements ServerComponent { * To be kept when no ProfileDefinition are injected */ public RegisterQualityProfiles(PersistentSettings settings, BuiltInProfiles builtInProfiles, - DbClient dbClient, QProfileFactory profileFactory, RuleActivator ruleActivator, Languages languages) { + DbClient dbClient, QProfileFactory profileFactory, RuleActivator ruleActivator, Languages languages) { this(settings, builtInProfiles, dbClient, profileFactory, ruleActivator, Collections.<ProfileDefinition>emptyList(), languages); } public RegisterQualityProfiles(PersistentSettings settings, BuiltInProfiles builtInProfiles, - DbClient dbClient, QProfileFactory profileFactory, RuleActivator ruleActivator, - List<ProfileDefinition> definitions, Languages languages) { + DbClient dbClient, QProfileFactory profileFactory, RuleActivator ruleActivator, + List<ProfileDefinition> definitions, Languages languages) { this.settings = settings; this.builtInProfiles = builtInProfiles; this.dbClient = dbClient; @@ -86,8 +85,7 @@ public class RegisterQualityProfiles implements ServerComponent { } public void start() { - TimeProfiler profiler = new TimeProfiler(LOGGER).start("Register Quality Profiles"); - + Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register quality profiles"); DbSession session = dbClient.openSession(false); try { ListMultimap<String, RulesProfile> profilesByLanguage = profilesByLanguage(); @@ -107,10 +105,10 @@ public class RegisterQualityProfiles implements ServerComponent { session.commit(); } } + profiler.stopDebug(); } finally { session.close(); - profiler.stop(); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/rule/RegisterRules.java b/server/sonar-server/src/main/java/org/sonar/server/rule/RegisterRules.java index 2d16e250dce..e2ea5e4ff98 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/rule/RegisterRules.java +++ b/server/sonar-server/src/main/java/org/sonar/server/rule/RegisterRules.java @@ -34,9 +34,9 @@ import org.sonar.api.rule.RuleStatus; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.utils.MessageException; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.core.persistence.DbSession; import org.sonar.core.qualityprofile.db.ActiveRuleDto; import org.sonar.core.qualityprofile.db.ActiveRuleParamDto; @@ -51,7 +51,6 @@ import org.sonar.server.startup.RegisterDebtModel; import javax.annotation.CheckForNull; import javax.annotation.Nullable; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -93,7 +92,7 @@ public class RegisterRules implements Startable { @Override public void start() { - TimeProfiler profiler = new TimeProfiler().start("Register rules"); + Profiler profiler = Profiler.create(LOG).startInfo("Register rules"); DbSession session = dbClient.openSession(false); try { Map<RuleKey, RuleDto> allRules = loadRules(session); @@ -111,12 +110,10 @@ public class RegisterRules implements Startable { List<RuleDto> activeRules = processRemainingDbRules(allRules.values(), session); removeActiveRulesOnStillExistingRepositories(session, activeRules, context); session.commit(); - + profiler.stopDebug(); } finally { session.close(); - profiler.stop(); } - } @Override diff --git a/server/sonar-server/src/main/java/org/sonar/server/search/SearchClient.java b/server/sonar-server/src/main/java/org/sonar/server/search/SearchClient.java index 2e1c3511c18..0a75ce63a32 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/search/SearchClient.java +++ b/server/sonar-server/src/main/java/org/sonar/server/search/SearchClient.java @@ -20,7 +20,6 @@ package org.sonar.server.search; -import com.google.common.annotations.VisibleForTesting; import org.apache.commons.lang.StringUtils; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequestBuilder; @@ -60,7 +59,6 @@ import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.picocontainer.Startable; import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; import org.sonar.process.LoopbackAddress; import org.sonar.process.ProcessConstants; import org.sonar.server.es.request.ProxyBulkRequestBuilder; @@ -86,14 +84,7 @@ import org.sonar.server.es.request.ProxySearchScrollRequestBuilder; */ public class SearchClient extends TransportClient implements Startable { - private final Profiling profiling; - public SearchClient(Settings settings) { - this(settings, new Profiling(settings)); - } - - @VisibleForTesting - public SearchClient(Settings settings, Profiling profiling) { super(ImmutableSettings.settingsBuilder() .put("node.name", StringUtils.defaultIfEmpty(settings.getString(ProcessConstants.CLUSTER_NODE_NAME), "sq_local_client")) .put("network.bind_host", "localhost") @@ -103,11 +94,6 @@ public class SearchClient extends TransportClient implements Startable { initLogging(); this.addTransportAddress(new InetSocketTransportAddress(LoopbackAddress.get().getHostAddress(), settings.getInt(ProcessConstants.SEARCH_PORT))); - this.profiling = profiling; - } - - public Profiling getProfiling() { - return profiling; } public ClusterHealth getClusterHealth() { @@ -128,74 +114,74 @@ public class SearchClient extends TransportClient implements Startable { } public RefreshRequestBuilder prepareRefresh(String... indices) { - return new ProxyRefreshRequestBuilder(this, profiling).setIndices(indices); + return new ProxyRefreshRequestBuilder(this).setIndices(indices); } public FlushRequestBuilder prepareFlush(String... indices) { - return new ProxyFlushRequestBuilder(this, profiling).setIndices(indices); + return new ProxyFlushRequestBuilder(this).setIndices(indices); } public IndicesStatsRequestBuilder prepareStats(String... indices) { - return new ProxyIndicesStatsRequestBuilder(this, profiling).setIndices(indices); + return new ProxyIndicesStatsRequestBuilder(this).setIndices(indices); } public NodesStatsRequestBuilder prepareNodesStats(String... nodesIds) { - return new ProxyNodesStatsRequestBuilder(this, profiling).setNodesIds(nodesIds); + return new ProxyNodesStatsRequestBuilder(this).setNodesIds(nodesIds); } public ClusterStatsRequestBuilder prepareClusterStats() { - return new ProxyClusterStatsRequestBuilder(this, profiling); + return new ProxyClusterStatsRequestBuilder(this); } public ClusterStateRequestBuilder prepareState() { - return new ProxyClusterStateRequestBuilder(this, profiling); + return new ProxyClusterStateRequestBuilder(this); } public IndicesExistsRequestBuilder prepareIndicesExist(String... indices) { - return new ProxyIndicesExistsRequestBuilder(this, profiling, indices); + return new ProxyIndicesExistsRequestBuilder(this, indices); } public CreateIndexRequestBuilder prepareCreate(String index) { - return new ProxyCreateIndexRequestBuilder(this, profiling, index); + return new ProxyCreateIndexRequestBuilder(this, index); } public PutMappingRequestBuilder preparePutMapping(String... indices) { - return new ProxyPutMappingRequestBuilder(this, profiling).setIndices(indices); + return new ProxyPutMappingRequestBuilder(this).setIndices(indices); } @Override public SearchRequestBuilder prepareSearch(String... indices) { - return new ProxySearchRequestBuilder(this, profiling).setIndices(indices); + return new ProxySearchRequestBuilder(this).setIndices(indices); } @Override public SearchScrollRequestBuilder prepareSearchScroll(String scrollId) { - return new ProxySearchScrollRequestBuilder(scrollId, this, profiling); + return new ProxySearchScrollRequestBuilder(scrollId, this); } @Override public GetRequestBuilder prepareGet() { - return new ProxyGetRequestBuilder(this, profiling); + return new ProxyGetRequestBuilder(this); } @Override public MultiGetRequestBuilder prepareMultiGet() { - return new ProxyMultiGetRequestBuilder(this, profiling); + return new ProxyMultiGetRequestBuilder(this); } @Override public CountRequestBuilder prepareCount(String... indices) { - return new ProxyCountRequestBuilder(this, profiling).setIndices(indices); + return new ProxyCountRequestBuilder(this).setIndices(indices); } @Override public BulkRequestBuilder prepareBulk() { - return new ProxyBulkRequestBuilder(this, profiling); + return new ProxyBulkRequestBuilder(this); } @Override public DeleteByQueryRequestBuilder prepareDeleteByQuery(String... indices) { - return new ProxyDeleteByQueryRequestBuilder(this, profiling).setIndices(indices); + return new ProxyDeleteByQueryRequestBuilder(this).setIndices(indices); } // **************************************************************************************************************** @@ -244,7 +230,7 @@ public class SearchClient extends TransportClient implements Startable { @Override public DeleteRequestBuilder prepareDelete(String index, String type, String id) { - return new ProxyDeleteRequestBuilder(profiling, this, index).setType(type).setId(id); + return new ProxyDeleteRequestBuilder(this, index).setType(type).setId(id); } @Override diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDashboards.java b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDashboards.java index 6848c52aa21..baea633bb32 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDashboards.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDashboards.java @@ -22,9 +22,9 @@ package org.sonar.server.startup; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import org.picocontainer.Startable; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.api.web.Dashboard; import org.sonar.api.web.DashboardTemplate; import org.sonar.core.dashboard.ActiveDashboardDao; @@ -71,7 +71,7 @@ public class RegisterDashboards implements Startable { @Override public void start() { - TimeProfiler profiler = new TimeProfiler(LOG).start("Register dashboards"); + Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register dashboards"); List<DashboardDto> registeredDashboards = Lists.newArrayList(); for (DashboardTemplate template : dashboardTemplates) { @@ -85,8 +85,7 @@ public class RegisterDashboards implements Startable { } activate(registeredDashboards); - - profiler.stop(); + profiler.stopDebug(); } @Override diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDebtModel.java b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDebtModel.java index 1319f3463b4..219f33d0b60 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDebtModel.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterDebtModel.java @@ -21,16 +21,13 @@ package org.sonar.server.startup; -import org.sonar.api.utils.TimeProfiler; -import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.core.technicaldebt.db.CharacteristicDao; import org.sonar.server.debt.DebtModelBackup; public class RegisterDebtModel { - private static final Logger LOGGER = Loggers.get(RegisterDebtModel.class); - private final CharacteristicDao dao; private final DebtModelBackup debtModelBackup; @@ -40,11 +37,11 @@ public class RegisterDebtModel { } public void start() { - TimeProfiler profiler = new TimeProfiler(LOGGER).start("Register technical debt model"); + Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register technical debt model"); if (dao.selectEnabledCharacteristics().isEmpty()) { debtModelBackup.reset(); } - profiler.stop(); + profiler.stopDebug(); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java index 01160def8fb..5c15b01414a 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java @@ -26,9 +26,9 @@ import com.google.common.collect.Maps; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.core.qualitygate.db.QualityGateConditionDao; import org.sonar.jpa.dao.MeasuresDao; @@ -59,7 +59,7 @@ public class RegisterMetrics { } public void start() { - TimeProfiler profiler = new TimeProfiler().start("Load metrics"); + Profiler profiler = Profiler.create(LOG).startInfo("Register metrics"); measuresDao.disableAutomaticMetrics(); List<Metric> metricsToRegister = newArrayList(); @@ -67,7 +67,7 @@ public class RegisterMetrics { metricsToRegister.addAll(getMetricsRepositories()); register(metricsToRegister); cleanAlerts(); - profiler.stop(); + profiler.stopDebug(); } @VisibleForTesting diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterNewMeasureFilters.java b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterNewMeasureFilters.java index 02c173aa621..769241f2de2 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterNewMeasureFilters.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterNewMeasureFilters.java @@ -23,9 +23,9 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.api.web.Criterion; import org.sonar.api.web.Filter; import org.sonar.api.web.FilterColumn; @@ -58,11 +58,11 @@ public final class RegisterNewMeasureFilters { * Used when no plugin is defining some FilterTemplate */ public RegisterNewMeasureFilters(MeasureFilterDao filterDao, LoadedTemplateDao loadedTemplateDao) { - this(new FilterTemplate[]{}, filterDao, loadedTemplateDao); + this(new FilterTemplate[] {}, filterDao, loadedTemplateDao); } public void start() { - TimeProfiler profiler = new TimeProfiler(LOG).start("Register measure filters"); + Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register measure filters"); for (FilterTemplate template : filterTemplates) { if (shouldRegister(template.getName())) { @@ -71,7 +71,7 @@ public final class RegisterNewMeasureFilters { } } - profiler.stop(); + profiler.stopDebug(); } private boolean shouldRegister(String filterName) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java index bf468fdf55f..adb33bf9562 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java @@ -20,11 +20,10 @@ package org.sonar.server.startup; - import org.sonar.api.security.DefaultGroups; -import org.sonar.api.utils.TimeProfiler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.api.web.UserRole; import org.sonar.core.permission.PermissionTemplateDao; import org.sonar.core.permission.PermissionTemplateDto; @@ -55,7 +54,7 @@ public class RegisterPermissionTemplates { } public void start() { - TimeProfiler profiler = new TimeProfiler(LOG).start("Register permission templates"); + Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register permission templates"); if (shouldRegister()) { if (hasExistingPermissionsConfig()) { @@ -67,7 +66,7 @@ public class RegisterPermissionTemplates { } registerInitialization(); } - profiler.stop(); + profiler.stopDebug(); } private boolean hasExistingPermissionsConfig() { diff --git a/server/sonar-server/src/main/java/org/sonar/server/ui/JRubyProfiling.java b/server/sonar-server/src/main/java/org/sonar/server/ui/JRubyProfiling.java deleted file mode 100644 index 3d8f3930cea..00000000000 --- a/server/sonar-server/src/main/java/org/sonar/server/ui/JRubyProfiling.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package org.sonar.server.ui; - - -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.Profiling.Level; -import org.sonar.core.profiling.StopWatch; - -/** - * @since 4.1 - */ -public class JRubyProfiling { - - private static final Logger LOG = Loggers.get(JRubyProfiling.class); - - private Profiling profiling; - - public JRubyProfiling(Profiling profiling) { - this.profiling = profiling; - } - - public StopWatch start(String domain, String level) { - Level profilingLevel = Level.NONE; - try { - profilingLevel = Level.valueOf(level); - } catch (IllegalArgumentException iae) { - LOG.warn("Unknown profiling level, defaulting to NONE: " + level, iae); - } - return profiling.start(domain, profilingLevel); - } -} diff --git a/server/sonar-server/src/test/java/org/sonar/server/app/WebLoggingTest.java b/server/sonar-server/src/test/java/org/sonar/server/app/WebLoggingTest.java index 6aac3ce769e..6bc5f9c6d00 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/app/WebLoggingTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/app/WebLoggingTest.java @@ -59,8 +59,15 @@ public class WebLoggingTest { @Test public void enable_debug_logs() throws Exception { - props.set("sonar.log.debug", "true"); + props.set("sonar.log.level", "DEBUG"); LoggerContext ctx = sut.configure(props); assertThat(ctx.getLogger(Logger.ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.DEBUG); } + + @Test + public void enable_trace_logs() throws Exception { + props.set("sonar.log.level", "TRACE"); + LoggerContext ctx = sut.configure(props); + assertThat(ctx.getLogger(Logger.ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.TRACE); + } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java b/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java index 2c01714b687..47a1954dac5 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java @@ -41,9 +41,7 @@ import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.elasticsearch.search.SearchHit; import org.junit.rules.ExternalResource; -import org.sonar.api.config.Settings; import org.sonar.api.platform.ComponentContainer; -import org.sonar.core.profiling.Profiling; import org.sonar.server.search.BaseDoc; import org.sonar.test.TestUtils; @@ -62,7 +60,6 @@ public class EsTester extends ExternalResource { private Node node; private EsClient client; private final List<IndexDefinition> definitions = newArrayList(); - private Settings settings = new Settings(); public EsTester addDefinitions(IndexDefinition... defs) { Collections.addAll(definitions, defs); @@ -99,7 +96,7 @@ public class EsTester extends ExternalResource { DeleteIndexResponse response = node.client().admin().indices().prepareDelete("_all").get(); assertThat(response.isAcknowledged()).isTrue(); - client = new EsClient(new Profiling(settings), node.client()); + client = new EsClient(node.client()); client.start(); if (!definitions.isEmpty()) { @@ -121,15 +118,6 @@ public class EsTester extends ExternalResource { node.stop(); node.close(); } - settings = null; - } - - /** - * Default level is NONE. - */ - public EsTester setProfilingLevel(Profiling.Level level) { - settings.setProperty(Profiling.CONFIG_PROFILING_LEVEL, level.name()); - return this; } public void truncateIndices() { diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java index e79cc839d28..7a6c911f6a4 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java @@ -26,10 +26,11 @@ import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -40,25 +41,24 @@ public class ProxyBulkRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test - public void bulk() { - testBulk(Profiling.Level.NONE); + public void no_trace_logs() { + logTester.setLevel(LoggerLevel.INFO); + testBulk(); + assertThat(logTester.logs()).isEmpty(); } @Test - public void with_profiling_full() { - testBulk(Profiling.Level.FULL); - // TODO assert profiling + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); + testBulk(); + assertThat(logTester.logs()).hasSize(1); } - private void testBulk(Profiling.Level profilingLevel) { - esTester.setProfilingLevel(profilingLevel); - + private void testBulk() { BulkRequestBuilder req = esTester.client().prepareBulk(); req.add(new UpdateRequest(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE, "key1") .doc(FakeIndexDefinition.newDoc(1))); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java index 63909a98c4e..abaf9cf7e01 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java @@ -22,10 +22,11 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; @@ -36,10 +37,8 @@ public class ProxyClearCacheRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester(); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void clear_cache() { @@ -59,12 +58,21 @@ public class ProxyClearCacheRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); + ClearIndicesCacheRequestBuilder requestBuilder = esTester.client().prepareClearCache(); + requestBuilder.get(); + + assertThat(logTester.logs()).hasSize(1); + } + + @Test + public void no_trace_logs() { + logTester.setLevel(LoggerLevel.DEBUG); ClearIndicesCacheRequestBuilder requestBuilder = esTester.client().prepareClearCache(); requestBuilder.get(); - // TODO assert profiling + assertThat(logTester.logs()).isEmpty(); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilderTest.java index 3e2d2cd59e7..f784e6d092c 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterHealthRequestBuilderTest.java @@ -24,10 +24,11 @@ import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; @@ -38,10 +39,8 @@ public class ProxyClusterHealthRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester(); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void state() { @@ -57,14 +56,14 @@ public class ProxyClusterHealthRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); ClusterHealthRequestBuilder requestBuilder = esTester.client().prepareHealth(); ClusterHealthResponse state = requestBuilder.get(); assertThat(state.getStatus()).isEqualTo(ClusterHealthStatus.GREEN); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilderTest.java index d33e2258ebf..ba11fd38f7b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStateRequestBuilderTest.java @@ -22,10 +22,11 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; @@ -36,10 +37,8 @@ public class ProxyClusterStateRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester(); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void state() { @@ -54,13 +53,13 @@ public class ProxyClusterStateRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); ClusterStateRequestBuilder requestBuilder = esTester.client().prepareState(); requestBuilder.get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilderTest.java index d20f6d77717..6d8a293cd01 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClusterStatsRequestBuilderTest.java @@ -22,10 +22,11 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; @@ -36,10 +37,8 @@ public class ProxyClusterStatsRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester(); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void stats() { @@ -54,13 +53,12 @@ public class ProxyClusterStatsRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); ClusterStatsRequestBuilder requestBuilder = esTester.client().prepareClusterStats(); requestBuilder.get(); - - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCountRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCountRequestBuilderTest.java index 2defc836a78..88b26fa6483 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCountRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCountRequestBuilderTest.java @@ -21,10 +21,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -36,10 +37,8 @@ public class ProxyCountRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void count() { @@ -54,12 +53,11 @@ public class ProxyCountRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareCount(FakeIndexDefinition.INDEX).get(); - - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java index 6f749f26a1c..4f57c0aba93 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java @@ -22,11 +22,12 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; @@ -37,10 +38,8 @@ public class ProxyCreateIndexRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester(); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void create_index() { @@ -55,13 +54,12 @@ public class ProxyCreateIndexRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); CreateIndexRequestBuilder requestBuilder = esTester.client().prepareCreate(generateNewIndexName()); requestBuilder.get(); - - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilderTest.java index e602a69ab21..6cd0df505de 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteByQueryRequestBuilderTest.java @@ -22,10 +22,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilders; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -37,10 +38,8 @@ public class ProxyDeleteByQueryRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void delete_by_query() { @@ -55,12 +54,12 @@ public class ProxyDeleteByQueryRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareDeleteByQuery(FakeIndexDefinition.INDEX).setQuery(QueryBuilders.matchAllQuery()).get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java index e8bcca0b7df..f22d22a60c8 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java @@ -20,10 +20,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; @@ -34,10 +35,8 @@ public class ProxyDeleteRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester(); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void delete() { @@ -50,11 +49,11 @@ public class ProxyDeleteRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareDelete("fakes", "fake", "the_id").get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java index cd0ee9935a7..86b2960d80e 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java @@ -21,10 +21,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -36,10 +37,8 @@ public class ProxyFlushRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void flush() { @@ -53,12 +52,11 @@ public class ProxyFlushRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareFlush(FakeIndexDefinition.INDEX).get(); - - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java index 66d4ea9bd05..8c1621ba6b4 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java @@ -22,10 +22,11 @@ package org.sonar.server.es.request; import org.elasticsearch.action.get.GetRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -37,10 +38,8 @@ public class ProxyGetRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void get() { @@ -52,16 +51,15 @@ public class ProxyGetRequestBuilderTest { } @Test - public void with_profiling_basic() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareGet() .setIndex(FakeIndexDefinition.INDEX) .setType(FakeIndexDefinition.TYPE) .setId("ruleKey") .get(); - - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java index 236dab71931..f445f8bbc27 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java @@ -23,10 +23,11 @@ package org.sonar.server.es.request; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -38,10 +39,8 @@ public class ProxyIndexRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void index_with_index_type_and_id() { @@ -52,13 +51,13 @@ public class ProxyIndexRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); IndexResponse response = esTester.client().prepareIndex(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE) .setSource(FakeIndexDefinition.newDoc(42)) .get(); assertThat(response.isCreated()).isTrue(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java index ab868d82e85..56ffd572599 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java @@ -21,10 +21,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -36,10 +37,8 @@ public class ProxyIndicesExistsRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void exists() { @@ -48,12 +47,12 @@ public class ProxyIndicesExistsRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareIndicesExist(FakeIndexDefinition.INDEX).get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java index 6d0bfe6cdc4..c9470f3fdae 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java @@ -21,10 +21,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -36,10 +37,8 @@ public class ProxyIndicesStatsRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void stats() { @@ -53,12 +52,12 @@ public class ProxyIndicesStatsRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareStats(FakeIndexDefinition.INDEX).get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java index 7a29e3bb51e..482a197cfbd 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java @@ -24,10 +24,11 @@ import org.elasticsearch.action.get.MultiGetRequest; import org.elasticsearch.action.get.MultiGetRequestBuilder; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.search.fetch.source.FetchSourceContext; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -39,10 +40,8 @@ public class ProxyMultiGetRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void multi_get() { @@ -63,15 +62,15 @@ public class ProxyMultiGetRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); MultiGetRequestBuilder request = esTester.client().prepareMultiGet(); request.add(new MultiGetRequest.Item(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE, "ruleKey") .fetchSourceContext(FetchSourceContext.FETCH_SOURCE)); request.get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java index e40abca7b13..f94c744c226 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java @@ -21,10 +21,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -36,10 +37,8 @@ public class ProxyNodesStatsRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester(); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void stats() { @@ -53,12 +52,12 @@ public class ProxyNodesStatsRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareNodesStats().get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java index 13f43287fbb..7a1aaaa6272 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java @@ -23,10 +23,11 @@ package org.sonar.server.es.request; import com.google.common.collect.ImmutableMap; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -41,10 +42,8 @@ public class ProxyPutMappingRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void put_mapping() { @@ -64,8 +63,8 @@ public class ProxyPutMappingRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); PutMappingRequestBuilder requestBuilder = esTester.client().preparePutMapping(FakeIndexDefinition.INDEX) .setType(FakeIndexDefinition.TYPE) @@ -73,7 +72,7 @@ public class ProxyPutMappingRequestBuilderTest { .setSource(mapDomain()); requestBuilder.get(); - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java index 87e6379d00f..089c7ebde80 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java @@ -22,10 +22,11 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.indices.refresh.RefreshRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -37,10 +38,8 @@ public class ProxyRefreshRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void refresh() { @@ -55,13 +54,12 @@ public class ProxyRefreshRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); RefreshRequestBuilder requestBuilder = esTester.client().prepareRefresh(FakeIndexDefinition.INDEX); requestBuilder.get(); - - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java index 8c033b6da87..8603d06183f 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java @@ -21,10 +21,11 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -36,10 +37,8 @@ public class ProxySearchRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test public void search() { @@ -55,12 +54,11 @@ public class ProxySearchRequestBuilderTest { } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); esTester.client().prepareSearch(FakeIndexDefinition.INDEX).get(); - - // TODO assert profiling + assertThat(logTester.logs()).hasSize(1); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java index 496139b38b8..2b984e53eb4 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java @@ -23,10 +23,11 @@ package org.sonar.server.es.request; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.unit.TimeValue; -import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.es.EsTester; import org.sonar.server.es.FakeIndexDefinition; @@ -38,31 +39,33 @@ public class ProxySearchScrollRequestBuilderTest { @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition()); - @Before - public void setUp() throws Exception { - esTester.setProfilingLevel(Profiling.Level.NONE); - } + @Rule + public LogTester logTester = new LogTester(); @Test - public void search_scroll() { + public void trace_logs() { + logTester.setLevel(LoggerLevel.TRACE); + SearchResponse response = esTester.client().prepareSearch(FakeIndexDefinition.INDEX) .setSearchType(SearchType.SCAN) .setScroll(TimeValue.timeValueMinutes(1)) .get(); + logTester.clear(); esTester.client().prepareSearchScroll(response.getScrollId()).get(); + assertThat(logTester.logs()).hasSize(1); } @Test - public void with_profiling_full() { - esTester.setProfilingLevel(Profiling.Level.FULL); + public void no_trace_logs() { + logTester.setLevel(LoggerLevel.DEBUG); SearchResponse response = esTester.client().prepareSearch(FakeIndexDefinition.INDEX) .setSearchType(SearchType.SCAN) .setScroll(TimeValue.timeValueMinutes(1)) .get(); + logTester.clear(); esTester.client().prepareSearchScroll(response.getScrollId()).get(); - - // TODO assert profiling + assertThat(logTester.logs()).isEmpty(); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/MeasureFilterEngineTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/MeasureFilterEngineTest.java index efba9273d2f..0df8c2bf72e 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/MeasureFilterEngineTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/MeasureFilterEngineTest.java @@ -23,17 +23,13 @@ import com.google.common.collect.ImmutableMap; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Test; -import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.refEq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; public class MeasureFilterEngineTest { @@ -45,7 +41,7 @@ public class MeasureFilterEngineTest { when(factory.create(filterMap)).thenReturn(filter); MeasureFilterExecutor executor = mock(MeasureFilterExecutor.class); - MeasureFilterEngine engine = new MeasureFilterEngine(factory, executor, new Profiling(new Settings())); + MeasureFilterEngine engine = new MeasureFilterEngine(factory, executor); final long userId = 50L; engine.execute(filterMap, userId); @@ -67,7 +63,7 @@ public class MeasureFilterEngineTest { when(factory.create(filterMap)).thenThrow(new IllegalArgumentException()); MeasureFilterExecutor executor = mock(MeasureFilterExecutor.class); - MeasureFilterEngine engine = new MeasureFilterEngine(factory, executor, new Profiling(new Settings())); + MeasureFilterEngine engine = new MeasureFilterEngine(factory, executor); MeasureFilterResult result = engine.execute(filterMap, 50L); assertThat(result.isSuccess()).isFalse(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/ProfilingFilterTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/ProfilingFilterTest.java index 465d4252f3e..25608fd10df 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/ProfilingFilterTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/ProfilingFilterTest.java @@ -23,18 +23,19 @@ package org.sonar.server.platform; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; -import javax.servlet.*; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; - public class ProfilingFilterTest { private ProfilingFilter filter; @@ -42,7 +43,6 @@ public class ProfilingFilterTest { @Before public void initialize() throws Exception { - FilterConfig filterConfig = mock(FilterConfig.class); when(filterConfig.getInitParameter("staticDirs")).thenReturn("/static,/assets"); ServletContext context = mock(ServletContext.class); @@ -50,12 +50,7 @@ public class ProfilingFilterTest { when(filterConfig.getServletContext()).thenReturn(context); chain = mock(FilterChain.class); - Settings settings = new Settings(); - settings.setProperty("sonar.log.profilingLevel", "BASIC"); - Profiling profiling = new Profiling(settings); - - filter = spy(new ProfilingFilter()); - when(filter.getProfiling()).thenReturn(profiling); + filter = new ProfilingFilter(); filter.init(filterConfig); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/tester/ServerTester.java b/server/sonar-server/src/test/java/org/sonar/server/tester/ServerTester.java index 3644a921813..3d8f2e1ccdd 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/tester/ServerTester.java +++ b/server/sonar-server/src/test/java/org/sonar/server/tester/ServerTester.java @@ -48,7 +48,7 @@ import java.util.Properties; * Entry point to implement medium tests of server components. * <p/> * The system properties starting with "mediumTests." override the programmatic settings, for example: - * <code>-DmediumTests.sonar.log.profilingLevel=FULL</code> + * <code>-DmediumTests.sonar.log.level=TRACE</code> * * @since 4.4 */ diff --git a/server/sonar-web/src/main/webapp/WEB-INF/app/models/internal.rb b/server/sonar-web/src/main/webapp/WEB-INF/app/models/internal.rb index dc2e9aaa395..29e8a960a6d 100644 --- a/server/sonar-web/src/main/webapp/WEB-INF/app/models/internal.rb +++ b/server/sonar-web/src/main/webapp/WEB-INF/app/models/internal.rb @@ -50,10 +50,6 @@ class Internal component(Java::OrgSonarServerDebt::DebtModelService.java_class) end - def self.profiling - component(Java::OrgSonarServerUi::JRubyProfiling.java_class) - end - def self.group_membership component(Java::OrgSonarServerUser::GroupMembershipService.java_class) end diff --git a/sonar-application/src/main/assembly/conf/sonar.properties b/sonar-application/src/main/assembly/conf/sonar.properties index e953a9d5546..f01fac2ebd2 100644 --- a/sonar-application/src/main/assembly/conf/sonar.properties +++ b/sonar-application/src/main/assembly/conf/sonar.properties @@ -245,8 +245,8 @@ #-------------------------------------------------------------------------------------------------- # LOGGING -# Enable debug logs in file sonar.log. -#sonar.log.debug=false +# Level of logs. Supported values are INFO, DEBUG and TRACE +#sonar.log.level=INFO # Path to log files. Can be absolute or relative to installation directory. # Default is <installation home>/logs diff --git a/sonar-batch/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java b/sonar-batch/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java index b8350757ad3..a3c42a7efa1 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java +++ b/sonar-batch/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java @@ -19,9 +19,6 @@ */ package org.sonar.batch.bootstrapper; -import org.sonar.core.profiling.Profiling.Level; - -import org.sonar.core.profiling.Profiling; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import org.apache.commons.lang.StringUtils; @@ -69,8 +66,8 @@ public final class LoggingConfiguration { } public LoggingConfiguration setProperties(Map<String, String> properties) { - Profiling.Level profilingLevel = Profiling.Level.fromConfigString(properties.get("sonar.log.profilingLevel")); - setShowSqlResults(profilingLevel == Level.FULL); + //TODO + setShowSqlResults(false); setVerbose("true".equals(properties.get("sonar.verbose"))); return this; } diff --git a/sonar-batch/src/main/java/org/sonar/batch/debt/DebtModelProvider.java b/sonar-batch/src/main/java/org/sonar/batch/debt/DebtModelProvider.java index bb434c22737..7ce8c610ba5 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/debt/DebtModelProvider.java +++ b/sonar-batch/src/main/java/org/sonar/batch/debt/DebtModelProvider.java @@ -27,27 +27,23 @@ import org.sonar.api.batch.debt.DebtCharacteristic; import org.sonar.api.batch.debt.DebtModel; import org.sonar.api.batch.debt.internal.DefaultDebtCharacteristic; import org.sonar.api.batch.debt.internal.DefaultDebtModel; -import org.sonar.api.utils.TimeProfiler; -import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.core.technicaldebt.db.CharacteristicDao; import org.sonar.core.technicaldebt.db.CharacteristicDto; import javax.annotation.Nullable; - import java.util.List; public class DebtModelProvider extends ProviderAdapter { - private static final Logger LOG = Loggers.get(DebtModelProvider.class); - private DebtModel model; public DebtModel provide(CharacteristicDao dao) { if (model == null) { - TimeProfiler profiler = new TimeProfiler(LOG).start("Loading technical debt model"); + Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Load technical debt model"); model = load(dao); - profiler.stop(); + profiler.stopDebug(); } return model; } diff --git a/sonar-batch/src/main/java/org/sonar/batch/issue/tracking/PreviousIssueRepository.java b/sonar-batch/src/main/java/org/sonar/batch/issue/tracking/PreviousIssueRepository.java index dc19f79818a..ce9ff46803f 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/issue/tracking/PreviousIssueRepository.java +++ b/sonar-batch/src/main/java/org/sonar/batch/issue/tracking/PreviousIssueRepository.java @@ -20,12 +20,12 @@ package org.sonar.batch.issue.tracking; import com.google.common.base.Function; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.sonar.api.BatchComponent; import org.sonar.api.batch.InstantiationStrategy; import org.sonar.api.batch.bootstrap.ProjectReactor; -import org.sonar.api.utils.TimeProfiler; +import org.sonar.api.utils.log.Logger; +import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.batch.index.BatchResource; import org.sonar.batch.index.Cache; import org.sonar.batch.index.Caches; @@ -38,7 +38,7 @@ import javax.annotation.Nullable; @InstantiationStrategy(InstantiationStrategy.PER_BATCH) public class PreviousIssueRepository implements BatchComponent { - private static final Logger LOG = LoggerFactory.getLogger(PreviousIssueRepository.class); + private static final Logger LOG = Loggers.get(PreviousIssueRepository.class); private final Caches caches; private Cache<PreviousIssue> issuesCache; @@ -54,30 +54,27 @@ public class PreviousIssueRepository implements BatchComponent { } public void load() { - TimeProfiler profiler = new TimeProfiler(LOG).start("Load previous issues"); - try { - this.issuesCache = caches.createCache("previousIssues"); - previousIssuesLoader.load(reactor, new Function<PreviousIssue, Void>() { + Profiler profiler = Profiler.create(LOG).startInfo("Load previous issues"); + this.issuesCache = caches.createCache("previousIssues"); + previousIssuesLoader.load(reactor, new Function<PreviousIssue, Void>() { - @Override - public Void apply(@Nullable PreviousIssue issue) { - if (issue == null) { - return null; - } - String componentKey = issue.componentKey(); - BatchResource r = resourceCache.get(componentKey); - if (r == null) { - // Deleted resource - issuesCache.put(0, issue.key(), issue); - } else { - issuesCache.put(r.batchId(), issue.key(), issue); - } + @Override + public Void apply(@Nullable PreviousIssue issue) { + if (issue == null) { return null; } - }); - } finally { - profiler.stop(); - } + String componentKey = issue.componentKey(); + BatchResource r = resourceCache.get(componentKey); + if (r == null) { + // Deleted resource + issuesCache.put(0, issue.key(), issue); + } else { + issuesCache.put(r.batchId(), issue.key(), issue); + } + return null; + } + }); + profiler.stopDebug(); } public Iterable<PreviousIssue> byComponent(BatchResource component) { diff --git a/sonar-batch/src/main/java/org/sonar/batch/rule/RulesProvider.java b/sonar-batch/src/main/java/org/sonar/batch/rule/RulesProvider.java index e5125616e9c..c886d93bf51 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/rule/RulesProvider.java +++ b/sonar-batch/src/main/java/org/sonar/batch/rule/RulesProvider.java @@ -32,15 +32,13 @@ import org.sonar.api.batch.rule.internal.NewRule; import org.sonar.api.batch.rule.internal.RulesBuilder; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.Durations; -import org.sonar.api.utils.TimeProfiler; -import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.core.rule.RuleDao; import org.sonar.core.rule.RuleDto; import org.sonar.core.rule.RuleParamDto; import javax.annotation.Nullable; - import java.util.List; /** @@ -48,15 +46,13 @@ import java.util.List; */ public class RulesProvider extends ProviderAdapter { - private static final Logger LOG = Loggers.get(RulesProvider.class); - private Rules singleton = null; public Rules provide(RuleDao ruleDao, DebtModel debtModel, Durations durations) { if (singleton == null) { - TimeProfiler profiler = new TimeProfiler(LOG).start("Loading rules"); + Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Load rules"); singleton = load(ruleDao, (DefaultDebtModel) debtModel, durations); - profiler.stop(); + profiler.stopDebug(); } return singleton; } @@ -125,7 +121,7 @@ public class RulesProvider extends ProviderAdapter { * Return true is the characteristic has not been overridden and a default characteristic is existing or * if the characteristic has been overridden but is not disabled */ - private boolean hasCharacteristic(RuleDto ruleDto){ + private boolean hasCharacteristic(RuleDto ruleDto) { Integer subCharacteristicId = ruleDto.getSubCharacteristicId(); return (subCharacteristicId == null && ruleDto.getDefaultSubCharacteristicId() != null) || (subCharacteristicId != null && !RuleDto.DISABLED_CHARACTERISTIC_ID.equals(subCharacteristicId)); diff --git a/sonar-batch/src/main/java/org/sonar/batch/scan/LastLineHashes.java b/sonar-batch/src/main/java/org/sonar/batch/scan/LastLineHashes.java index 5dc690a9da6..ed359265713 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/scan/LastLineHashes.java +++ b/sonar-batch/src/main/java/org/sonar/batch/scan/LastLineHashes.java @@ -22,15 +22,12 @@ package org.sonar.batch.scan; import com.google.common.base.Splitter; import com.google.common.collect.Iterators; import org.sonar.api.BatchComponent; -import org.sonar.api.utils.TimeProfiler; -import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.api.utils.log.Profiler; import org.sonar.batch.bootstrap.ServerClient; public class LastLineHashes implements BatchComponent { - private static final Logger LOG = Loggers.get(LastLineHashes.class); - private final ServerClient server; public LastLineHashes(ServerClient server) { @@ -43,11 +40,13 @@ public class LastLineHashes implements BatchComponent { } private String loadHashesFromWs(String fileKey) { - TimeProfiler profiler = new TimeProfiler(LOG).setLevelToDebug().start("Load previous line hashes of: " + fileKey); + Profiler profiler = Profiler.createIfDebug(Loggers.get(getClass())) + .addContext("file", fileKey) + .startDebug("Load line hashes"); try { return server.request("/api/sources/hash?key=" + ServerClient.encodeForUrl(fileKey)); } finally { - profiler.stop(); + profiler.stopDebug(); } } } diff --git a/sonar-batch/src/test/java/org/sonar/batch/bootstrapper/LoggingConfigurationTest.java b/sonar-batch/src/test/java/org/sonar/batch/bootstrapper/LoggingConfigurationTest.java index f8783192273..0da23d622c6 100644 --- a/sonar-batch/src/test/java/org/sonar/batch/bootstrapper/LoggingConfigurationTest.java +++ b/sonar-batch/src/test/java/org/sonar/batch/bootstrapper/LoggingConfigurationTest.java @@ -62,25 +62,6 @@ public class LoggingConfigurationTest { } @Test - public void testSetShowSqlProperty() { - Map<String, String> properties = Maps.newHashMap(); - assertThat(LoggingConfiguration.create(null).setProperties(properties) - .getSubstitutionVariable(LoggingConfiguration.PROPERTY_SQL_RESULTS_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_SQL_DEFAULT); - - properties.put("sonar.log.profilingLevel", "FULL"); - assertThat(LoggingConfiguration.create(null).setProperties(properties) - .getSubstitutionVariable(LoggingConfiguration.PROPERTY_SQL_RESULTS_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_SQL_VERBOSE); - - properties.put("sonar.log.profilingLevel", "BASIC"); - assertThat(LoggingConfiguration.create(null).setProperties(properties) - .getSubstitutionVariable(LoggingConfiguration.PROPERTY_SQL_RESULTS_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_SQL_DEFAULT); - - properties.put("sonar.log.profilingLevel", "NONE"); - assertThat(LoggingConfiguration.create(null).setProperties(properties) - .getSubstitutionVariable(LoggingConfiguration.PROPERTY_SQL_RESULTS_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_SQL_DEFAULT); - } - - @Test public void testDefaultFormat() { assertThat(LoggingConfiguration.create(null) .getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo(LoggingConfiguration.FORMAT_DEFAULT); diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java b/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java index a5eebcd5114..46fbd4ef2fc 100644 --- a/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java +++ b/sonar-core/src/main/java/org/sonar/core/persistence/DefaultDatabase.java @@ -31,7 +31,7 @@ import org.sonar.api.config.Settings; import org.sonar.api.database.DatabaseProperties; import org.sonar.core.persistence.dialect.Dialect; import org.sonar.core.persistence.dialect.DialectUtils; -import org.sonar.core.persistence.profiling.PersistenceProfiling; +import org.sonar.core.persistence.profiling.ProfiledDataSource; import org.sonar.jpa.session.CustomHibernateConnectionProvider; import javax.sql.DataSource; @@ -103,7 +103,9 @@ public class DefaultDatabase implements Database { datasource = (BasicDataSource) BasicDataSourceFactory.createDataSource(extractCommonsDbcpProperties(properties)); datasource.setConnectionInitSqls(dialect.getConnectionInitStatements()); datasource.setValidationQuery(dialect.getValidationQuery()); - datasource = PersistenceProfiling.addProfilingIfNeeded(datasource, settings); + if ("TRACE".equals(settings.getString("sonar.log.level"))) { + datasource = new ProfiledDataSource(datasource); + } } private void checkConnection() { diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/MyBatis.java b/sonar-core/src/main/java/org/sonar/core/persistence/MyBatis.java index 2b5fa87277f..5badc79490f 100644 --- a/sonar-core/src/main/java/org/sonar/core/persistence/MyBatis.java +++ b/sonar-core/src/main/java/org/sonar/core/persistence/MyBatis.java @@ -25,7 +25,11 @@ import com.google.common.io.Closeables; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.mapping.Environment; -import org.apache.ibatis.session.*; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.ExecutorType; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import org.apache.ibatis.type.JdbcType; import org.slf4j.LoggerFactory; @@ -45,7 +49,14 @@ import org.sonar.core.component.db.SnapshotMapper; import org.sonar.core.computation.db.AnalysisReportDto; import org.sonar.core.computation.db.AnalysisReportMapper; import org.sonar.core.config.Logback; -import org.sonar.core.dashboard.*; +import org.sonar.core.dashboard.ActiveDashboardDto; +import org.sonar.core.dashboard.ActiveDashboardMapper; +import org.sonar.core.dashboard.DashboardDto; +import org.sonar.core.dashboard.DashboardMapper; +import org.sonar.core.dashboard.WidgetDto; +import org.sonar.core.dashboard.WidgetMapper; +import org.sonar.core.dashboard.WidgetPropertyDto; +import org.sonar.core.dashboard.WidgetPropertyMapper; import org.sonar.core.dependency.DependencyDto; import org.sonar.core.dependency.DependencyMapper; import org.sonar.core.dependency.ResourceSnapshotDto; @@ -54,11 +65,33 @@ import org.sonar.core.duplication.DuplicationMapper; import org.sonar.core.duplication.DuplicationUnitDto; import org.sonar.core.graph.jdbc.GraphDto; import org.sonar.core.graph.jdbc.GraphDtoMapper; -import org.sonar.core.issue.db.*; -import org.sonar.core.measure.db.*; +import org.sonar.core.issue.db.ActionPlanDto; +import org.sonar.core.issue.db.ActionPlanMapper; +import org.sonar.core.issue.db.ActionPlanStatsDto; +import org.sonar.core.issue.db.ActionPlanStatsMapper; +import org.sonar.core.issue.db.BatchIssueDto; +import org.sonar.core.issue.db.IssueChangeDto; +import org.sonar.core.issue.db.IssueChangeMapper; +import org.sonar.core.issue.db.IssueDto; +import org.sonar.core.issue.db.IssueFilterDto; +import org.sonar.core.issue.db.IssueFilterFavouriteDto; +import org.sonar.core.issue.db.IssueFilterFavouriteMapper; +import org.sonar.core.issue.db.IssueFilterMapper; +import org.sonar.core.issue.db.IssueMapper; +import org.sonar.core.measure.db.MeasureDto; +import org.sonar.core.measure.db.MeasureFilterDto; +import org.sonar.core.measure.db.MeasureFilterMapper; +import org.sonar.core.measure.db.MeasureMapper; +import org.sonar.core.measure.db.MetricDto; +import org.sonar.core.measure.db.MetricMapper; import org.sonar.core.notification.db.NotificationQueueDto; import org.sonar.core.notification.db.NotificationQueueMapper; -import org.sonar.core.permission.*; +import org.sonar.core.permission.GroupWithPermissionDto; +import org.sonar.core.permission.PermissionTemplateDto; +import org.sonar.core.permission.PermissionTemplateGroupDto; +import org.sonar.core.permission.PermissionTemplateMapper; +import org.sonar.core.permission.PermissionTemplateUserDto; +import org.sonar.core.permission.UserWithPermissionDto; import org.sonar.core.persistence.dialect.Dialect; import org.sonar.core.persistence.migration.v44.Migration44Mapper; import org.sonar.core.persistence.migration.v45.Migration45Mapper; @@ -68,9 +101,22 @@ import org.sonar.core.properties.PropertyDto; import org.sonar.core.purge.IdUuidPair; import org.sonar.core.purge.PurgeMapper; import org.sonar.core.purge.PurgeableSnapshotDto; -import org.sonar.core.qualitygate.db.*; -import org.sonar.core.qualityprofile.db.*; -import org.sonar.core.resource.*; +import org.sonar.core.qualitygate.db.ProjectQgateAssociationDto; +import org.sonar.core.qualitygate.db.ProjectQgateAssociationMapper; +import org.sonar.core.qualitygate.db.QualityGateConditionDto; +import org.sonar.core.qualitygate.db.QualityGateConditionMapper; +import org.sonar.core.qualitygate.db.QualityGateDto; +import org.sonar.core.qualitygate.db.QualityGateMapper; +import org.sonar.core.qualityprofile.db.ActiveRuleDto; +import org.sonar.core.qualityprofile.db.ActiveRuleMapper; +import org.sonar.core.qualityprofile.db.ActiveRuleParamDto; +import org.sonar.core.qualityprofile.db.QualityProfileDto; +import org.sonar.core.qualityprofile.db.QualityProfileMapper; +import org.sonar.core.resource.ResourceDto; +import org.sonar.core.resource.ResourceIndexDto; +import org.sonar.core.resource.ResourceIndexerMapper; +import org.sonar.core.resource.ResourceKeyUpdaterMapper; +import org.sonar.core.resource.ResourceMapper; import org.sonar.core.rule.RuleDto; import org.sonar.core.rule.RuleMapper; import org.sonar.core.rule.RuleParamDto; @@ -80,10 +126,21 @@ import org.sonar.core.technicaldebt.db.CharacteristicMapper; import org.sonar.core.technicaldebt.db.RequirementMigrationDto; import org.sonar.core.template.LoadedTemplateDto; import org.sonar.core.template.LoadedTemplateMapper; -import org.sonar.core.user.*; +import org.sonar.core.user.AuthorDto; +import org.sonar.core.user.AuthorMapper; +import org.sonar.core.user.GroupDto; +import org.sonar.core.user.GroupMapper; +import org.sonar.core.user.GroupMembershipDto; +import org.sonar.core.user.GroupMembershipMapper; +import org.sonar.core.user.GroupRoleDto; +import org.sonar.core.user.RoleMapper; +import org.sonar.core.user.UserDto; +import org.sonar.core.user.UserGroupDto; +import org.sonar.core.user.UserGroupMapper; +import org.sonar.core.user.UserMapper; +import org.sonar.core.user.UserRoleDto; import javax.annotation.Nullable; - import java.io.InputStream; public class MyBatis implements BatchComponent, ServerComponent { @@ -209,7 +266,6 @@ public class MyBatis implements BatchComponent, ServerComponent { Migration45Mapper.class, Migration50Mapper.class }; loadMappers(conf, mappers); - configureLogback(mappers); sessionFactory = new SqlSessionFactoryBuilder().build(conf); return this; @@ -253,15 +309,6 @@ public class MyBatis implements BatchComponent, ServerComponent { } } - /** - * See http://www.mybatis.org/core/logging.html : - */ - private void configureLogback(Class<?>... mapperClasses) { - for (Class mapperClass : mapperClasses) { - logback.setLoggerLevel(mapperClass.getName(), Level.INFO); - } - } - private void loadMapper(Configuration configuration, Class mapperClass) { loadMapper(configuration, mapperClass.getName()); } @@ -272,6 +319,7 @@ public class MyBatis implements BatchComponent, ServerComponent { input = getClass().getResourceAsStream("/" + mapperName.replace('.', '/') + ".xml"); new XMLMapperBuilder(input, configuration, mapperName, configuration.getSqlFragments()).parse(); configuration.addLoadedResource(mapperName); + logback.setLoggerLevel(mapperName, Level.INFO); } catch (Exception e) { throw new IllegalArgumentException("Unable to load mapper " + mapperName, e); } finally { diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/PersistenceProfiling.java b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/PersistenceProfiling.java deleted file mode 100644 index 76ec195a456..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/PersistenceProfiling.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.persistence.profiling; - -import org.apache.commons.dbcp.BasicDataSource; -import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; - -/** - * @since 4.2 - */ -public final class PersistenceProfiling { - - private PersistenceProfiling() { - // Static stuff only - } - - public static BasicDataSource addProfilingIfNeeded(BasicDataSource datasource, Settings settings) { - Profiling.Level level = Profiling.Level.fromConfigString(settings.getString(Profiling.CONFIG_PROFILING_LEVEL)); - if (level == Profiling.Level.FULL) { - return new ProfilingDataSource(datasource); - } - return datasource; - } -} diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingDataSource.java b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfiledDataSource.java index c97909f4d2c..5fbc4d49dab 100644 --- a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingDataSource.java +++ b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfiledDataSource.java @@ -20,6 +20,8 @@ package org.sonar.core.persistence.profiling; import org.apache.commons.dbcp.BasicDataSource; +import org.sonar.api.utils.log.Logger; +import org.sonar.api.utils.log.Loggers; import java.io.PrintWriter; import java.lang.reflect.Proxy; @@ -27,11 +29,13 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; -class ProfilingDataSource extends BasicDataSource { +public class ProfiledDataSource extends BasicDataSource { + + public static final Logger SQL_LOGGER = Loggers.get("sql"); private final BasicDataSource delegate; - public ProfilingDataSource(BasicDataSource delegate) { + public ProfiledDataSource(BasicDataSource delegate) { this.delegate = delegate; } diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingPreparedStatementHandler.java b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingPreparedStatementHandler.java index 88461fc6be8..0bfb0d27cf6 100644 --- a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingPreparedStatementHandler.java +++ b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingPreparedStatementHandler.java @@ -21,7 +21,7 @@ package org.sonar.core.persistence.profiling; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; -import org.sonar.core.profiling.StopWatch; +import org.sonar.api.utils.log.Profiler; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -33,7 +33,6 @@ class ProfilingPreparedStatementHandler implements InvocationHandler { private static final String PARAM_PREFIX = "<"; private static final String PARAM_SUFFIX = ">"; private static final String PARAM_SEPARATOR = ", "; - private static final SqlProfiling PROFILING = new SqlProfiling(); private final PreparedStatement statement; private final List<Object> arguments; @@ -43,7 +42,7 @@ class ProfilingPreparedStatementHandler implements InvocationHandler { this.statement = statement; this.sql = sql; this.arguments = Lists.newArrayList(); - for (int argCount = 0; argCount < StringUtils.countMatches(sql, "?"); argCount ++) { + for (int argCount = 0; argCount < StringUtils.countMatches(sql, "?"); argCount++) { arguments.add("!"); } } @@ -51,19 +50,13 @@ class ProfilingPreparedStatementHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().startsWith("execute")) { - StopWatch watch = PROFILING.start(); + Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); Object result = null; try { result = InvocationUtils.invokeQuietly(statement, method, args); } finally { - StringBuilder sqlBuilder = new StringBuilder().append(sql); - if (!arguments.isEmpty()) { - sqlBuilder.append(" - parameters are: "); - for (Object arg: arguments) { - sqlBuilder.append(PARAM_PREFIX).append(arg).append(PARAM_SUFFIX).append(PARAM_SEPARATOR); - } - } - PROFILING.stop(watch, StringUtils.removeEnd(sqlBuilder.toString(), PARAM_SEPARATOR)); + profiler.addContext("sql", StringUtils.remove(sql, '\n')); + profiler.stopTrace(""); } return result; } else if (method.getName().startsWith("set") && args.length > 1) { diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingStatementHandler.java b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingStatementHandler.java index ba2875b8226..d2f2522c821 100644 --- a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingStatementHandler.java +++ b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/ProfilingStatementHandler.java @@ -19,7 +19,8 @@ */ package org.sonar.core.persistence.profiling; -import org.sonar.core.profiling.StopWatch; +import org.apache.commons.lang.StringUtils; +import org.sonar.api.utils.log.Profiler; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -27,8 +28,6 @@ import java.sql.Statement; class ProfilingStatementHandler implements InvocationHandler { - private static final SqlProfiling PROFILING = new SqlProfiling(); - private final Statement statement; ProfilingStatementHandler(Statement statement) { @@ -38,12 +37,13 @@ class ProfilingStatementHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().startsWith("execute")) { - StopWatch watch = PROFILING.start(); + Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); Object result = null; try { result = InvocationUtils.invokeQuietly(statement, method, args); } finally { - PROFILING.stop(watch, (String) args[0]); + profiler.addContext("sql", StringUtils.remove((String)args[0], '\n')); + profiler.stopTrace(""); } return result; } else { diff --git a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/SqlProfiling.java b/sonar-core/src/main/java/org/sonar/core/persistence/profiling/SqlProfiling.java deleted file mode 100644 index 7c30293473a..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/persistence/profiling/SqlProfiling.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.persistence.profiling; - -import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.Profiling.Level; -import org.sonar.core.profiling.StopWatch; - -class SqlProfiling { - - private final Profiling profiling; - - SqlProfiling() { - Settings settings = new Settings(); - settings.setProperty(Profiling.CONFIG_PROFILING_LEVEL, Profiling.Level.FULL.toString()); - profiling = new Profiling(settings); - } - - StopWatch start() { - return profiling.start("sql", Level.FULL); - } - - void stop(StopWatch watch, String sql) { - watch.stop(String.format("Executed SQL: %s", sql.replaceAll("\\s+", " "))); - } -} diff --git a/sonar-core/src/main/java/org/sonar/core/profiling/LoggingWatch.java b/sonar-core/src/main/java/org/sonar/core/profiling/LoggingWatch.java deleted file mode 100644 index d0ef0c47510..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/profiling/LoggingWatch.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.profiling; - -import com.google.common.annotations.VisibleForTesting; -import org.slf4j.Logger; -import org.sonar.api.utils.System2; - -class LoggingWatch implements StopWatch { - - private Logger logger; - private System2 system; - private long startTimeInMillis; - - LoggingWatch(Logger logger) { - this(logger, System2.INSTANCE); - } - - @VisibleForTesting - LoggingWatch(Logger logger, System2 system) { - this.system = system; - this.logger = logger; - this.startTimeInMillis = system.now(); - } - - @Override - public void stop(String message, Object... args) { - long endTimeInMillis = system.now(); - String messageToDisplay = (args.length == 0) ? message : String.format(message, args); - logger.info("{}ms {}", Long.valueOf(endTimeInMillis - startTimeInMillis), messageToDisplay); - } - -} diff --git a/sonar-core/src/main/java/org/sonar/core/profiling/NoopWatch.java b/sonar-core/src/main/java/org/sonar/core/profiling/NoopWatch.java deleted file mode 100644 index 61b9a30271c..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/profiling/NoopWatch.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.profiling; - - -class NoopWatch implements StopWatch { - - @Override - public void stop(String message, Object... args) { - // Nothing logged - } -} diff --git a/sonar-core/src/main/java/org/sonar/core/profiling/Profiling.java b/sonar-core/src/main/java/org/sonar/core/profiling/Profiling.java deleted file mode 100644 index 68cf9e84f57..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/profiling/Profiling.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.profiling; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.config.Settings; - -/** - * @since 4.1 - */ -public class Profiling { - - public static final String CONFIG_PROFILING_LEVEL = "sonar.log.profilingLevel"; - - private static final Logger LOGGER = LoggerFactory.getLogger(Profiling.class); - - private Settings settings; - private ProfilingLogFactory logFactory; - - public enum Level { - NONE, BASIC, FULL; - - public static Level fromConfigString(String settingsValue) { - Level settingsLevel = NONE; - if (settingsValue != null) { - try { - settingsLevel = Level.valueOf(settingsValue); - } catch (IllegalArgumentException invalidSettings) { - LOGGER.debug("Bad profiling settings, profiling is disabled", invalidSettings); - } - } - return settingsLevel; - } - } - - public Profiling(Settings settings) { - this(settings, new ProfilingLogFactory()); - } - - Profiling(Settings settings, ProfilingLogFactory logFactory) { - this.settings = settings; - this.logFactory = logFactory; - } - - - public StopWatch start(String domain, Level level) { - StopWatch watch; - if (isProfilingEnabled(level)) { - watch = new LoggingWatch(logFactory.getLogger(domain)); - } else { - watch = new NoopWatch(); - } - return watch; - } - - public boolean isProfilingEnabled(Level level) { - String settingsValue = settings.getString(CONFIG_PROFILING_LEVEL); - Level settingsLevel = Level.fromConfigString(settingsValue); - return settingsLevel != Level.NONE && level.ordinal() <= settingsLevel.ordinal(); - } -} diff --git a/sonar-core/src/main/java/org/sonar/core/profiling/ProfilingLogFactory.java b/sonar-core/src/main/java/org/sonar/core/profiling/ProfilingLogFactory.java deleted file mode 100644 index 5c12d5b1cc2..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/profiling/ProfilingLogFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.profiling; - -import org.slf4j.LoggerFactory; - -import org.slf4j.Logger; - -class ProfilingLogFactory { - - public Logger getLogger(String domain) { - return LoggerFactory.getLogger(domain); - } -} diff --git a/sonar-core/src/main/java/org/sonar/core/profiling/StopWatch.java b/sonar-core/src/main/java/org/sonar/core/profiling/StopWatch.java deleted file mode 100644 index cd9ca655bb5..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/profiling/StopWatch.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.profiling; - -public interface StopWatch { - - /** - * Stop the watch and print provided profiling message - */ - void stop(String message, Object... args); -} diff --git a/sonar-core/src/main/java/org/sonar/core/profiling/package-info.java b/sonar-core/src/main/java/org/sonar/core/profiling/package-info.java deleted file mode 100644 index 5edc8c7cdb0..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/profiling/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -@ParametersAreNonnullByDefault -package org.sonar.core.profiling; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-core/src/test/java/org/sonar/core/persistence/profiling/InvocationUtilsTest.java b/sonar-core/src/test/java/org/sonar/core/persistence/profiling/InvocationUtilsTest.java index 728eb940982..9fbdfbd7845 100644 --- a/sonar-core/src/test/java/org/sonar/core/persistence/profiling/InvocationUtilsTest.java +++ b/sonar-core/src/test/java/org/sonar/core/persistence/profiling/InvocationUtilsTest.java @@ -20,6 +20,7 @@ package org.sonar.core.persistence.profiling; import org.junit.Test; +import org.sonar.test.TestUtils; import java.sql.Connection; import java.sql.SQLException; @@ -67,4 +68,10 @@ public class InvocationUtilsTest { assertThat(t).isInstanceOf(IllegalStateException.class); } } + + @Test + public void only_static_methods() throws Exception { + assertThat(TestUtils.hasOnlyPrivateConstructors(InvocationUtils.class)).isTrue(); + + } } diff --git a/sonar-core/src/test/java/org/sonar/core/persistence/profiling/PersistenceProfilingTest.java b/sonar-core/src/test/java/org/sonar/core/persistence/profiling/ProfiledDataSourceTest.java index 11e637661c9..26d6e9dbc6e 100644 --- a/sonar-core/src/test/java/org/sonar/core/persistence/profiling/PersistenceProfilingTest.java +++ b/sonar-core/src/test/java/org/sonar/core/persistence/profiling/ProfiledDataSourceTest.java @@ -19,40 +19,30 @@ */ package org.sonar.core.persistence.profiling; -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.ContextBase; -import ch.qos.logback.core.read.ListAppender; import org.apache.commons.dbcp.BasicDataSource; +import org.junit.Rule; import org.junit.Test; -import org.slf4j.LoggerFactory; -import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; +import org.sonar.api.utils.log.LogTester; import java.io.ByteArrayInputStream; -import java.sql.*; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.sql.Connection; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.Statement; +import java.sql.Timestamp; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; -public class PersistenceProfilingTest { +public class ProfiledDataSourceTest { - @Test - public void should_be_transparent_when_profiling_less_than_full() { - BasicDataSource datasource = mock(BasicDataSource.class); - assertThat(PersistenceProfiling.addProfilingIfNeeded(datasource , new Settings())).isEqualTo(datasource); - } + @Rule + public LogTester logTester = new LogTester(); @Test - public void should_enable_profiling_when_profiling_is_full() throws Exception { - final Logger sqlLogger = (Logger) LoggerFactory.getLogger("sql"); - ListAppender<ILoggingEvent> appender = new ListAppender<ILoggingEvent>(); - appender.setContext(new ContextBase()); - appender.start(); - sqlLogger.addAppender(appender); - + public void log_sql_requests() throws Exception { BasicDataSource originDataSource = mock(BasicDataSource.class); Connection connection = mock(Connection.class); @@ -74,15 +64,11 @@ public class PersistenceProfilingTest { when(connection.createStatement()).thenReturn(statement); when(statement.execute(sql)).thenReturn(true); - Settings settings = new Settings(); - settings.setProperty(Profiling.CONFIG_PROFILING_LEVEL, Profiling.Level.FULL.toString()); - - BasicDataSource resultDataSource = PersistenceProfiling.addProfilingIfNeeded(originDataSource , settings); + ProfiledDataSource ds = new ProfiledDataSource(originDataSource); - assertThat(resultDataSource).isInstanceOf(ProfilingDataSource.class); - assertThat(resultDataSource.getUrl()).isNull(); - assertThat(resultDataSource.getConnection().getClientInfo()).isNull(); - PreparedStatement preparedStatementProxy = resultDataSource.getConnection().prepareStatement(sqlWithParams); + assertThat(ds.getUrl()).isNull(); + assertThat(ds.getConnection().getClientInfo()).isNull(); + PreparedStatement preparedStatementProxy = ds.getConnection().prepareStatement(sqlWithParams); preparedStatementProxy.setInt(1, param1); preparedStatementProxy.setString(2, param2); preparedStatementProxy.setDate(3, param3); @@ -90,14 +76,27 @@ public class PersistenceProfilingTest { preparedStatementProxy.setBlob(5, new ByteArrayInputStream(param5)); assertThat(preparedStatementProxy.getConnection()).isNull(); assertThat(preparedStatementProxy.execute()).isTrue(); - final Statement statementProxy = resultDataSource.getConnection().createStatement(); + final Statement statementProxy = ds.getConnection().createStatement(); assertThat(statementProxy.getConnection()).isNull(); assertThat(statementProxy.execute(sql)).isTrue(); - assertThat(appender.list).hasSize(2); - assertThat(appender.list.get(0).getLevel()).isEqualTo(Level.INFO); - assertThat(appender.list.get(0).getFormattedMessage()).contains(sqlWithParams).contains(" - parameters are: ").contains(Integer.toString(param1)).contains(param2); - assertThat(appender.list.get(1).getLevel()).isEqualTo(Level.INFO); - assertThat(appender.list.get(1).getFormattedMessage()).contains(sql); + assertThat(logTester.logs()).hasSize(2); + assertThat(logTester.logs().get(1)).contains(sql); + } + + @Test + public void delegate_to_underlying_datasource() throws Exception { + BasicDataSource delegate = mock(BasicDataSource.class); + ProfiledDataSource proxy = new ProfiledDataSource(delegate); + + // painful to call all methods + // so using reflection to check that calls does not fail + // Limitation: methods with parameters are not tested and calls to + // underlying datasource are not verified + for (Method method : ProfiledDataSource.class.getDeclaredMethods()) { + if (method.getParameterTypes().length == 0 && Modifier.isPublic(method.getModifiers())) { + method.invoke(proxy); + } + } } } diff --git a/sonar-core/src/test/java/org/sonar/core/profiling/LoggingWatchTest.java b/sonar-core/src/test/java/org/sonar/core/profiling/LoggingWatchTest.java deleted file mode 100644 index 6381017fd6b..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/profiling/LoggingWatchTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package org.sonar.core.profiling; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.slf4j.Logger; -import org.sonar.api.utils.System2; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - -@RunWith(MockitoJUnitRunner.class) -public class LoggingWatchTest { - - @Mock - Logger logger; - - @Mock - System2 system; - - LoggingWatch loggingWatch; - - @Before - public void setUp() throws Exception { - doReturn(1000l).when(system).now(); - loggingWatch = new LoggingWatch(logger, system); - } - - @Test - public void stop_with_params() throws Exception { - doReturn(1500l).when(system).now(); - - loggingWatch.stop("Create '%s' elements of type '%s'", 10, "test"); - verify(logger).info("{}ms {}", 500l, "Create '10' elements of type 'test'"); - } - - @Test - public void stop_without_params() throws Exception { - doReturn(1500l).when(system).now(); - - loggingWatch.stop("End of process"); - verify(logger).info("{}ms {}", 500l, "End of process"); - } - - @Test - public void stop_with_variable_but_without_params() throws Exception { - doReturn(1500l).when(system).now(); - - loggingWatch.stop("End of process at %s"); - verify(logger).info("{}ms {}", 500l, "End of process at %s"); - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/profiling/ProfilingActivityFactoryTest.java b/sonar-core/src/test/java/org/sonar/core/profiling/ProfilingActivityFactoryTest.java deleted file mode 100644 index 32ff4c43992..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/profiling/ProfilingActivityFactoryTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.profiling; - -import org.junit.Test; - -public class ProfilingActivityFactoryTest { - - @Test - public void just_for_coverage() throws Exception { - new ProfilingLogFactory().getLogger("domain"); - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/profiling/ProfilingTest.java b/sonar-core/src/test/java/org/sonar/core/profiling/ProfilingTest.java deleted file mode 100644 index b7d8ec9c41c..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/profiling/ProfilingTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.profiling; - -import static org.mockito.Mockito.mock; - -import org.slf4j.Logger; - -import org.mockito.Mockito; -import org.sonar.core.profiling.Profiling.Level; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.config.Settings; - -public class ProfilingTest { - - private Settings settings; - private ProfilingLogFactory logFactory; - private Logger logger; - private Profiling profiling; - - private static final String BASIC_MESSAGE = "Basic message"; - private static final String FULL_MESSAGE = "Full message"; - - @Before - public void prepare() { - settings = new Settings(); - logFactory = mock(ProfilingLogFactory.class); - logger = mock(Logger.class); - Mockito.when(logFactory.getLogger(Mockito.anyString())).thenReturn(logger); - profiling = new Profiling(settings, logFactory); - } - - @Test - public void should_silence_all_profiling_by_default() throws Exception { - doProfiling(); - Mockito.verifyZeroInteractions(logger); - } - - @Test - public void should_silence_all_profiling_when_faulty_config() throws Exception { - settings.setProperty("sonar.log.profilingLevel", "POLOP"); - doProfiling(); - Mockito.verifyZeroInteractions(logger); - } - - @Test - public void should_silence_all_profiling() throws Exception { - settings.setProperty("sonar.log.profilingLevel", "NONE"); - doProfiling(); - Mockito.verifyZeroInteractions(logger); - } - - @Test - public void should_log_basic_level() throws Exception { - settings.setProperty("sonar.log.profilingLevel", "BASIC"); - doProfiling(); - Mockito.verify(logger).info(Mockito.eq("{}ms {}"), Mockito.anyLong(), Mockito.eq(BASIC_MESSAGE)); - Mockito.verifyNoMoreInteractions(logger); - } - - @Test - public void should_log_everything() throws Exception { - settings.setProperty("sonar.log.profilingLevel", "FULL"); - doProfiling(); - Mockito.verify(logger).info(Mockito.eq("{}ms {}"), Mockito.anyLong(), Mockito.eq(FULL_MESSAGE)); - Mockito.verify(logger).info(Mockito.eq("{}ms {}"), Mockito.anyLong(), Mockito.eq(BASIC_MESSAGE)); - } - - private void doProfiling() throws InterruptedException { - StopWatch basicWatch = profiling.start("basic", Level.BASIC); - StopWatch fullWatch = profiling.start("full", Level.FULL); - Thread.sleep(42); - fullWatch.stop(FULL_MESSAGE); - basicWatch.stop(BASIC_MESSAGE); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java index ce86e880cdb..29ffa1c55cf 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java @@ -19,44 +19,35 @@ */ package org.sonar.api.utils; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; +import org.slf4j.LoggerFactory; /** * A very simple profiler to log the time elapsed performing some tasks. * This implementation is not thread-safe. * + * @deprecated since 5.1. Replaced by {@link org.sonar.api.utils.log.Profiler} * @since 2.0 */ public class TimeProfiler { - private Logger logger; + private org.slf4j.Logger logger; private long start = 0; private String name; private boolean debug = false; - public TimeProfiler(Logger logger) { - this.logger = logger; - } - - /** - * @deprecated do not use SLF4J but org.sonar.api.utils.log.Logger - * @since 5.1 - */ - @Deprecated public TimeProfiler(org.slf4j.Logger logger) { - this.logger = Loggers.get(logger.getName()); + this.logger = logger; } public TimeProfiler(Class clazz) { - this.logger = Loggers.get(clazz); + this.logger = LoggerFactory.getLogger(clazz); } /** * Use the default Sonar logger */ public TimeProfiler() { - this.logger = Loggers.get(getClass()); + this.logger = LoggerFactory.getLogger(getClass()); } public TimeProfiler start(String name) { @@ -70,12 +61,12 @@ public class TimeProfiler { return this; } - public TimeProfiler setLogger(Logger logger) { + public TimeProfiler setLogger(org.slf4j.Logger logger) { this.logger = logger; return this; } - public Logger getLogger() { + public org.slf4j.Logger getLogger() { return logger; } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/BaseLogger.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/BaseLogger.java index 7dbec222096..f4c7e3c95f9 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/BaseLogger.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/BaseLogger.java @@ -23,107 +23,139 @@ import javax.annotation.Nullable; abstract class BaseLogger implements Logger { @Override + public void trace(String msg) { + LogInterceptor.instance().log(msg); + doTrace(msg); + } + + @Override + public void trace(String pattern, @Nullable Object arg) { + LogInterceptor.instance().log(pattern, arg); + doTrace(pattern, arg); + } + + @Override + public void trace(String msg, @Nullable Object arg1, @Nullable Object arg2) { + LogInterceptor.instance().log(msg, arg1, arg2); + doTrace(msg, arg1, arg2); + } + + @Override + public void trace(String msg, Object... args) { + LogInterceptor.instance().log(msg, args); + doTrace(msg, args); + } + + @Override public void debug(String msg) { - LogInterceptor.instance.log(msg); + LogInterceptor.instance().log(msg); doDebug(msg); } @Override public void debug(String pattern, @Nullable Object arg) { - LogInterceptor.instance.log(pattern, arg); + LogInterceptor.instance().log(pattern, arg); doDebug(pattern, arg); } @Override public void debug(String msg, @Nullable Object arg1, @Nullable Object arg2) { - LogInterceptor.instance.log(msg, arg1, arg2); + LogInterceptor.instance().log(msg, arg1, arg2); doDebug(msg, arg1, arg2); } @Override public void debug(String msg, Object... args) { - LogInterceptor.instance.log(msg, args); + LogInterceptor.instance().log(msg, args); doDebug(msg, args); } @Override public void info(String msg) { - LogInterceptor.instance.log(msg); + LogInterceptor.instance().log(msg); doInfo(msg); } @Override public void info(String msg, @Nullable Object arg) { - LogInterceptor.instance.log(msg, arg); + LogInterceptor.instance().log(msg, arg); doInfo(msg, arg); } @Override public void info(String msg, @Nullable Object arg1, @Nullable Object arg2) { - LogInterceptor.instance.log(msg, arg1, arg2); + LogInterceptor.instance().log(msg, arg1, arg2); doInfo(msg, arg1, arg2); } @Override public void info(String msg, Object... args) { - LogInterceptor.instance.log(msg, args); + LogInterceptor.instance().log(msg, args); doInfo(msg, args); } @Override public void warn(String msg) { - LogInterceptor.instance.log(msg); + LogInterceptor.instance().log(msg); doWarn(msg); } @Override public void warn(String msg, @Nullable Object arg) { - LogInterceptor.instance.log(msg, arg); + LogInterceptor.instance().log(msg, arg); doWarn(msg, arg); } @Override public void warn(String msg, @Nullable Object arg1, @Nullable Object arg2) { - LogInterceptor.instance.log(msg, arg1, arg2); + LogInterceptor.instance().log(msg, arg1, arg2); doWarn(msg, arg1, arg2); } @Override public void warn(String msg, Object... args) { - LogInterceptor.instance.log(msg, args); + LogInterceptor.instance().log(msg, args); doWarn(msg, args); } @Override public void error(String msg) { - LogInterceptor.instance.log(msg); + LogInterceptor.instance().log(msg); doError(msg); } @Override public void error(String msg, @Nullable Object arg) { - LogInterceptor.instance.log(msg, arg); + LogInterceptor.instance().log(msg, arg); doError(msg, arg); } @Override public void error(String msg, @Nullable Object arg1, @Nullable Object arg2) { - LogInterceptor.instance.log(msg, arg1, arg2); + LogInterceptor.instance().log(msg, arg1, arg2); doError(msg, arg1, arg2); } @Override public void error(String msg, Object... args) { - LogInterceptor.instance.log(msg, args); + LogInterceptor.instance().log(msg, args); doError(msg, args); } @Override public void error(String msg, Throwable thrown) { - LogInterceptor.instance.log(msg, thrown); + LogInterceptor.instance().log(msg, thrown); doError(msg, thrown); } + abstract void doTrace(String msg); + + abstract void doTrace(String msg, @Nullable Object arg); + + abstract void doTrace(String msg, @Nullable Object arg1, @Nullable Object arg2); + + abstract void doTrace(String msg, Object... args); + abstract void doDebug(String msg); abstract void doDebug(String msg, @Nullable Object arg); @@ -132,9 +164,6 @@ abstract class BaseLogger implements Logger { abstract void doDebug(String msg, Object... args); - /** - * Logs an INFO level message. - */ abstract void doInfo(String msg); abstract void doInfo(String msg, @Nullable Object arg); @@ -143,9 +172,6 @@ abstract class BaseLogger implements Logger { abstract void doInfo(String msg, Object... args); - /** - * Logs a WARN level message. - */ abstract void doWarn(String msg); abstract void doWarn(String msg, @Nullable Object arg); @@ -154,9 +180,6 @@ abstract class BaseLogger implements Logger { abstract void doWarn(String msg, Object... args); - /** - * Logs an ERROR level message. - */ abstract void doError(String msg); abstract void doError(String msg, @Nullable Object arg); @@ -166,4 +189,24 @@ abstract class BaseLogger implements Logger { abstract void doError(String msg, Object... args); abstract void doError(String msg, Throwable thrown); + + void log(LoggerLevel level, String msg) { + switch (level) { + case TRACE: + trace(msg); + break; + case DEBUG: + debug(msg); + break; + case INFO: + info(msg); + break; + case WARN: + warn(msg); + break; + case ERROR: + error(msg); + break; + } + } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLogger.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLogger.java index 1dee60c11d6..35757ebb256 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLogger.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLogger.java @@ -44,8 +44,42 @@ class ConsoleLogger extends BaseLogger { } @Override + public boolean isTraceEnabled() { + return Loggers.getFactory().getLevel() == LoggerLevel.TRACE; + } + + @Override + protected void doTrace(String msg) { + if (isTraceEnabled()) { + log("TRACE", msg); + } + } + + @Override + protected void doTrace(String pattern, @Nullable Object arg) { + if (isTraceEnabled()) { + trace(format(pattern, arg)); + } + } + + @Override + protected void doTrace(String pattern, @Nullable Object arg1, @Nullable Object arg2) { + if (isTraceEnabled()) { + trace(format(pattern, arg1, arg2)); + } + } + + @Override + protected void doTrace(String pattern, Object... args) { + if (isTraceEnabled()) { + trace(format(pattern, args)); + } + } + + @Override public boolean isDebugEnabled() { - return Loggers.getFactory().isDebugEnabled(); + LoggerLevel level = Loggers.getFactory().getLevel(); + return level == LoggerLevel.TRACE || level == LoggerLevel.DEBUG; } @Override diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLoggers.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLoggers.java index 726321e2956..e920bcd49b6 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLoggers.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ConsoleLoggers.java @@ -21,7 +21,7 @@ package org.sonar.api.utils.log; class ConsoleLoggers extends Loggers { - private boolean debugEnabled = false; + private LoggerLevel level = LoggerLevel.INFO; @Override protected Logger newInstance(String name) { @@ -29,12 +29,14 @@ class ConsoleLoggers extends Loggers { } @Override - protected boolean isDebugEnabled() { - return debugEnabled; + protected LoggerLevel getLevel() { + return level; } @Override - protected void enableDebug(boolean b) { - this.debugEnabled = b; + protected void setLevel(LoggerLevel level) { + this.level = level; } + + } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/DefaultProfiler.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/DefaultProfiler.java new file mode 100644 index 00000000000..e72bf231c8b --- /dev/null +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/DefaultProfiler.java @@ -0,0 +1,180 @@ +/* + * SonarQube, open source software quality management tool. + * Copyright (C) 2008-2014 SonarSource + * mailto:contact AT sonarsource DOT com + * + * SonarQube is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * SonarQube is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.utils.log; + +import org.apache.commons.lang.StringUtils; +import org.sonar.api.utils.System2; + +import javax.annotation.Nullable; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +class DefaultProfiler extends Profiler { + + private static final String CONTEXT_SEPARATOR = " | "; + + private final LinkedHashMap<String, Object> context = new LinkedHashMap<>(); + private final BaseLogger logger; + + private long startTime = 0L; + private String startMessage = null; + private LoggerLevel startLevel = null; + + public DefaultProfiler(BaseLogger logger) { + this.logger = logger; + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public Profiler start() { + this.startTime = System2.INSTANCE.now(); + this.startMessage = null; + this.startLevel = null; + return this; + } + + @Override + public Profiler startTrace(String message) { + this.startTime = System2.INSTANCE.now(); + this.startMessage = message; + this.startLevel = LoggerLevel.TRACE; + StringBuilder sb = new StringBuilder(); + sb.append(message); + appendContext(sb); + logger.trace(sb.toString()); + return this; + } + + @Override + public Profiler startDebug(String message) { + this.startTime = System2.INSTANCE.now(); + this.startMessage = message; + this.startLevel = LoggerLevel.DEBUG; + StringBuilder sb = new StringBuilder(); + sb.append(message); + appendContext(sb); + logger.debug(sb.toString()); + return this; + } + + @Override + public Profiler startInfo(String message) { + this.startTime = System2.INSTANCE.now(); + this.startMessage = message; + this.startLevel = LoggerLevel.INFO; + StringBuilder sb = new StringBuilder(); + sb.append(message); + appendContext(sb); + logger.info(sb.toString()); + return this; + } + + + @Override + public Profiler stopTrace() { + return doStopWithoutMessage(LoggerLevel.TRACE); + } + + @Override + public Profiler stopDebug() { + return doStopWithoutMessage(LoggerLevel.DEBUG); + } + + @Override + public Profiler stopInfo() { + return doStopWithoutMessage(LoggerLevel.INFO); + } + + private Profiler doStopWithoutMessage(LoggerLevel level) { + if (startMessage == null) { + throw new IllegalStateException("Profiler#stopXXX() can't be called without any message defined in start methods"); + } + doStop(level, startMessage, " (done)"); + return this; + } + + @Override + public Profiler stopTrace(String message) { + doStop(LoggerLevel.TRACE, message, ""); + return this; + } + + @Override + public Profiler stopDebug(String message) { + doStop(LoggerLevel.DEBUG, message, ""); + return this; + } + + @Override + public Profiler stopInfo(String message) { + doStop(LoggerLevel.INFO, message, ""); + return this; + } + + private void doStop(LoggerLevel level, @Nullable String message, String messageSuffix) { + if (startTime == 0L) { + throw new IllegalStateException("Profiler must be started before being stopped"); + } + long duration = System2.INSTANCE.now() - startTime; + StringBuilder sb = new StringBuilder(); + if (!StringUtils.isEmpty(message)) { + sb.append(message); + sb.append(messageSuffix); + sb.append(CONTEXT_SEPARATOR); + } + sb.append("time=").append(duration).append("ms"); + appendContext(sb); + logger.log(level, sb.toString()); + startTime = 0L; + startMessage = null; + startLevel = null; + context.clear(); + } + + private void appendContext(StringBuilder sb) { + for (Map.Entry<String, Object> entry : context.entrySet()) { + if (sb.length() > 0) { + sb.append(CONTEXT_SEPARATOR); + } + sb.append(entry.getKey()).append("=").append(Objects.toString(entry.getValue())); + } + } + + @Override + public Profiler addContext(String key, @Nullable Object value) { + if (value == null) { + context.remove(key); + } else { + context.put(key, value); + } + return this; + } + +} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ListInterceptor.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ListInterceptor.java index 94aa6dad39a..58c86d8387a 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ListInterceptor.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/ListInterceptor.java @@ -54,4 +54,8 @@ class ListInterceptor extends LogInterceptor { public List<String> logs() { return logs; } + + public void clear() { + logs.clear(); + } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogInterceptor.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogInterceptor.java index aab01e6a359..ff844379d9e 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogInterceptor.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogInterceptor.java @@ -19,9 +19,11 @@ */ package org.sonar.api.utils.log; +import com.google.common.base.Preconditions; + abstract class LogInterceptor { - static LogInterceptor instance = NullInterceptor.NULL_INSTANCE; + private static LogInterceptor instance = NullInterceptor.NULL_INSTANCE; abstract void log(String msg); @@ -32,4 +34,13 @@ abstract class LogInterceptor { abstract void log(String msg, Object... args); abstract void log(String msg, Throwable thrown); + + static LogInterceptor instance() { + return instance; + } + + static void setInstance(LogInterceptor li) { + Preconditions.checkArgument(li != null); + instance = li; + } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogTester.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogTester.java index 98ddc36cbf5..ac63133bfc2 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogTester.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogTester.java @@ -27,7 +27,7 @@ import java.util.List; * <b>For tests only</b> * <p/> * This JUnit rule allows to configure and access logs in tests. By default - * debug logs are enabled. + * trace level is enabled. * <p/> * Warning - not compatible with parallel execution of tests in the same JVM fork. * <p/> @@ -58,36 +58,33 @@ import java.util.List; */ public class LogTester extends ExternalResource { - private boolean initialDebugMode; + private LoggerLevel initialLevel; @Override protected void before() throws Throwable { - initialDebugMode = Loggers.getFactory().isDebugEnabled(); + initialLevel = Loggers.getFactory().getLevel(); // this shared instance breaks compatibility with parallel execution of tests - LogInterceptor.instance = new ListInterceptor(); - enableDebug(true); + LogInterceptor.setInstance(new ListInterceptor()); + setLevel(LoggerLevel.TRACE); } @Override protected void after() { - enableDebug(initialDebugMode); - LogInterceptor.instance = NullInterceptor.NULL_INSTANCE; + LogInterceptor.setInstance(NullInterceptor.NULL_INSTANCE); + setLevel(initialLevel); } - /** - * @see #enableDebug(boolean) - */ - public boolean isDebugEnabled() { - return Loggers.getFactory().isDebugEnabled(); + protected LoggerLevel getLevel() { + return Loggers.getFactory().getLevel(); } /** * Enable/disable debug logs. Info, warn and error logs are always enabled. * By default debug logs are enabled when LogTester is started. */ - public LogTester enableDebug(boolean b) { - Loggers.getFactory().enableDebug(b); + public LogTester setLevel(LoggerLevel level) { + Loggers.getFactory().setLevel(level); return this; } @@ -95,6 +92,11 @@ public class LogTester extends ExternalResource { * Logs in chronological order (item at index 0 is the oldest one) */ public List<String> logs() { - return ((ListInterceptor) LogInterceptor.instance).logs(); + return ((ListInterceptor) LogInterceptor.instance()).logs(); + } + + public LogTester clear() { + ((ListInterceptor) LogInterceptor.instance()).clear(); + return this; } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLogger.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLogger.java index 7b42e877ac5..3d4c8aa732c 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLogger.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLogger.java @@ -36,10 +36,36 @@ class LogbackLogger extends BaseLogger { } @Override + public boolean isTraceEnabled() { + return logback.isTraceEnabled(); + } + + @Override + void doTrace(String msg) { + logback.trace(msg); + } + + @Override + void doTrace(String msg, @Nullable Object arg) { + logback.trace(msg, arg); + } + + @Override + void doTrace(String msg, @Nullable Object arg1, @Nullable Object arg2) { + logback.trace(msg, arg1, arg2); + } + + @Override + void doTrace(String msg, Object... args) { + logback.trace(msg, args); + } + + @Override public boolean isDebugEnabled() { return logback.isDebugEnabled(); } + @Override protected void doDebug(String msg) { logback.debug(msg); @@ -128,18 +154,17 @@ class LogbackLogger extends BaseLogger { @Override public boolean setLevel(LoggerLevel level) { switch (level) { + case TRACE: + logback.setLevel(Level.TRACE); + break; case DEBUG: logback.setLevel(Level.DEBUG); break; case INFO: logback.setLevel(Level.INFO); break; - case WARN: - logback.setLevel(Level.WARN); - break; - case ERROR: - logback.setLevel(Level.ERROR); - break; + default: + throw new IllegalArgumentException("Only TRACE, DEBUG and INFO logging levels are supported. Got: " + level); } return true; } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLoggers.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLoggers.java index 7d8ce45f94e..3c8c8e3d03d 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLoggers.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LogbackLoggers.java @@ -31,17 +31,25 @@ class LogbackLoggers extends Loggers { @Override protected Logger newInstance(String name) { // logback is accessed through SLF4J - return new LogbackLogger((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(name)); + return new LogbackLogger((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(name)); } @Override - protected boolean isDebugEnabled() { - return LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).isDebugEnabled(); + protected LoggerLevel getLevel() { + ch.qos.logback.classic.Logger logback = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); + switch (logback.getLevel().levelInt) { + case Level.TRACE_INT: + return LoggerLevel.TRACE; + case Level.DEBUG_INT: + return LoggerLevel.DEBUG; + default: + return LoggerLevel.INFO; + } } @Override - protected void enableDebug(boolean b) { + protected void setLevel(LoggerLevel level) { ch.qos.logback.classic.Logger logback = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); - logback.setLevel(b ? Level.DEBUG : Level.INFO); + new LogbackLogger(logback).setLevel(level); } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Logger.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Logger.java index d729a4b7f08..27a22668910 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Logger.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Logger.java @@ -40,14 +40,38 @@ import javax.annotation.Nullable; * * <p/> * INFO, WARN and ERROR levels are always enabled. They can't be disabled by users. - * DEBUG level can be enabled with properties <code>sonar.log.debug</code> (on server, see sonar.properties) - * and <code>sonar.verbose</code> (on batch) + * DEBUG and TRACE levels are enabled on demand with the property <code>sonar.log.level</code>. * <p/> * See {@link org.sonar.api.utils.log.LogTester} for testing facilities. * @since 5.1 */ public interface Logger { + boolean isTraceEnabled(); + + /** + * Logs a TRACE message. TRACE messages must + * be valuable for diagnosing production problems. They must not be used for development debugging. + * They can significantly slow down performances. The standard use-case is logging of + * SQL and Elasticsearch requests. + */ + void trace(String msg); + + /** + * @see #trace(String) + */ + void trace(String pattern, @Nullable Object arg); + + /** + * @see #trace(String) + */ + void trace(String msg, @Nullable Object arg1, @Nullable Object arg2); + + /** + * @see #trace(String) + */ + void trace(String msg, Object... args); + boolean isDebugEnabled(); /** @@ -148,4 +172,5 @@ public interface Logger { * libraries. */ boolean setLevel(LoggerLevel level); + } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LoggerLevel.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LoggerLevel.java index 5ff6fd27f54..5f8ee88ff5e 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LoggerLevel.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/LoggerLevel.java @@ -20,5 +20,13 @@ package org.sonar.api.utils.log; public enum LoggerLevel { - DEBUG, INFO, WARN, ERROR + TRACE, + + DEBUG, + + INFO, + + WARN, + + ERROR } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Loggers.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Loggers.java index 4f2627fc5e9..dc82b8b3f2b 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Loggers.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Loggers.java @@ -28,7 +28,7 @@ public abstract class Loggers { static { try { - Class.forName("org.slf4j.Logger"); + Class.forName("ch.qos.logback.classic.Logger"); factory = new LogbackLoggers(); } catch (Throwable e) { // no slf4j -> testing environment @@ -50,8 +50,8 @@ public abstract class Loggers { protected abstract Logger newInstance(String name); - protected abstract boolean isDebugEnabled(); + protected abstract LoggerLevel getLevel(); - protected abstract void enableDebug(boolean b); + protected abstract void setLevel(LoggerLevel level); } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/NullProfiler.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/NullProfiler.java new file mode 100644 index 00000000000..65a943e9447 --- /dev/null +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/NullProfiler.java @@ -0,0 +1,96 @@ +/* + * SonarQube, open source software quality management tool. + * Copyright (C) 2008-2014 SonarSource + * mailto:contact AT sonarsource DOT com + * + * SonarQube is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * SonarQube is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.utils.log; + +import javax.annotation.Nullable; + +class NullProfiler extends Profiler { + + static final NullProfiler NULL_INSTANCE = new NullProfiler(); + + private NullProfiler() { + } + + @Override + public boolean isDebugEnabled() { + return false; + } + + @Override + public boolean isTraceEnabled() { + return false; + } + + @Override + public Profiler start() { + return this; + } + + @Override + public Profiler startTrace(String message) { + return this; + } + + @Override + public Profiler startDebug(String message) { + return this; + } + + @Override + public Profiler startInfo(String message) { + return this; + } + + @Override + public Profiler stopTrace() { + return this; + } + + @Override + public Profiler stopDebug() { + return this; + } + + @Override + public Profiler stopInfo() { + return this; + } + + @Override + public Profiler stopTrace(String message) { + return this; + } + + @Override + public Profiler stopDebug(String message) { + return this; + } + + @Override + public Profiler stopInfo(String message) { + return this; + } + + @Override + public Profiler addContext(String key, @Nullable Object value) { + // nothing to do + return this; + } +} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Profiler.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Profiler.java new file mode 100644 index 00000000000..c22d4ed2939 --- /dev/null +++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/log/Profiler.java @@ -0,0 +1,80 @@ +/* + * SonarQube, open source software quality management tool. + * Copyright (C) 2008-2014 SonarSource + * mailto:contact AT sonarsource DOT com + * + * SonarQube is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * SonarQube is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.utils.log; + +import javax.annotation.Nullable; + +/** + * + * @since 5.1 + */ +public abstract class Profiler { + + public static Profiler create(Logger logger) { + return new DefaultProfiler((BaseLogger) logger); + } + + public static Profiler createIfTrace(Logger logger) { + if (logger.isTraceEnabled()) { + return create(logger); + } + return NullProfiler.NULL_INSTANCE; + } + + public static Profiler createIfDebug(Logger logger) { + if (logger.isDebugEnabled()) { + return create(logger); + } + return NullProfiler.NULL_INSTANCE; + } + + public abstract boolean isDebugEnabled(); + + public abstract boolean isTraceEnabled(); + + public abstract Profiler start(); + + public abstract Profiler startTrace(String message); + + public abstract Profiler startDebug(String message); + + public abstract Profiler startInfo(String message); + + /** + * Works only if a message have been set in startXXX() methods. + */ + public abstract Profiler stopTrace(); + + public abstract Profiler stopDebug(); + + public abstract Profiler stopInfo(); + + public abstract Profiler stopTrace(String message); + + public abstract Profiler stopDebug(String message); + + public abstract Profiler stopInfo(String message); + + /** + * Context information is removed if value is <code>null</code>. + */ + public abstract Profiler addContext(String key, @Nullable Object value); + +} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeProfilerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeProfilerTest.java index 3d7e3ac6177..713b4677abf 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeProfilerTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeProfilerTest.java @@ -21,7 +21,7 @@ package org.sonar.api.utils; import org.junit.Before; import org.junit.Test; -import org.sonar.api.utils.log.Logger; +import org.slf4j.Logger; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggerTest.java index 3f59d8d87e5..56d5f242dab 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggerTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggerTest.java @@ -38,8 +38,9 @@ public class ConsoleLoggerTest { @Test public void debug_enabled() throws Exception { - tester.enableDebug(true); + tester.setLevel(LoggerLevel.DEBUG); assertThat(sut.isDebugEnabled()).isTrue(); + assertThat(sut.isTraceEnabled()).isFalse(); sut.debug("message"); sut.debug("message {}", "foo"); sut.debug("message {} {}", "foo", "bar"); @@ -49,8 +50,9 @@ public class ConsoleLoggerTest { @Test public void debug_disabled() throws Exception { - tester.enableDebug(false); + tester.setLevel(LoggerLevel.INFO); assertThat(sut.isDebugEnabled()).isFalse(); + assertThat(sut.isTraceEnabled()).isFalse(); sut.debug("message"); sut.debug("message {}", "foo"); sut.debug("message {} {}", "foo", "bar"); @@ -59,6 +61,29 @@ public class ConsoleLoggerTest { } @Test + public void trace_enabled() throws Exception { + tester.setLevel(LoggerLevel.TRACE); + assertThat(sut.isDebugEnabled()).isTrue(); + assertThat(sut.isTraceEnabled()).isTrue(); + sut.trace("message"); + sut.trace("message {}", "foo"); + sut.trace("message {} {}", "foo", "bar"); + sut.trace("message {} {} {}", "foo", "bar", "baz"); + verify(stream, times(4)).println(anyString()); + } + + @Test + public void trace_disabled() throws Exception { + tester.setLevel(LoggerLevel.DEBUG); + assertThat(sut.isTraceEnabled()).isFalse(); + sut.trace("message"); + sut.trace("message {}", "foo"); + sut.trace("message {} {}", "foo", "bar"); + sut.trace("message {} {} {}", "foo", "bar", "baz"); + verifyZeroInteractions(stream); + } + + @Test public void log() throws Exception { sut.info("message"); sut.info("message {}", "foo"); diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggersTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggersTest.java index 64fa4cc7b96..a77cd98a18a 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggersTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggersTest.java @@ -34,14 +34,11 @@ public class ConsoleLoggersTest { } @Test - public void debugMode() throws Exception { - // disabled by default - assertThat(sut.isDebugEnabled()).isFalse(); + public void level() throws Exception { + // INFO by default + assertThat(sut.getLevel()).isEqualTo(LoggerLevel.INFO); - sut.enableDebug(true); - assertThat(sut.isDebugEnabled()).isTrue(); - - sut.enableDebug(false); - assertThat(sut.isDebugEnabled()).isFalse(); + sut.setLevel(LoggerLevel.DEBUG); + assertThat(sut.getLevel()).isEqualTo(LoggerLevel.DEBUG); } } diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/DefaultProfilerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/DefaultProfilerTest.java new file mode 100644 index 00000000000..3bf72652db7 --- /dev/null +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/DefaultProfilerTest.java @@ -0,0 +1,183 @@ +/* + * SonarQube, open source software quality management tool. + * Copyright (C) 2008-2014 SonarSource + * mailto:contact AT sonarsource DOT com + * + * SonarQube is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * SonarQube is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.utils.log; + +import org.junit.Rule; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public class DefaultProfilerTest { + + @Rule + public LogTester tester = new LogTester(); + + Profiler sut = Profiler.create(Loggers.get("DefaultProfilerTest")); + + @Test + public void test_levels() throws Exception { + // trace by default + assertThat(sut.isDebugEnabled()).isTrue(); + assertThat(sut.isTraceEnabled()).isTrue(); + + tester.setLevel(LoggerLevel.DEBUG); + assertThat(sut.isDebugEnabled()).isTrue(); + assertThat(sut.isTraceEnabled()).isFalse(); + + tester.setLevel(LoggerLevel.INFO); + assertThat(sut.isDebugEnabled()).isFalse(); + assertThat(sut.isTraceEnabled()).isFalse(); + } + + @Test + public void stop_reuses_start_message() throws Exception { + tester.setLevel(LoggerLevel.TRACE); + + // trace + sut.startTrace("Register rules"); + assertThat(tester.logs()).containsOnly("Register rules"); + sut.stopTrace(); + assertThat(tester.logs()).hasSize(2); + assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time="); + tester.clear(); + + // debug + sut.startDebug("Register rules"); + assertThat(tester.logs()).containsOnly("Register rules"); + sut.stopTrace(); + assertThat(tester.logs()).hasSize(2); + assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time="); + tester.clear(); + + // info + sut.startInfo("Register rules"); + assertThat(tester.logs()).containsOnly("Register rules"); + sut.stopTrace(); + assertThat(tester.logs()).hasSize(2); + assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time="); + } + + @Test + public void different_start_and_stop_messages() throws Exception { + tester.setLevel(LoggerLevel.TRACE); + + // start TRACE and stop DEBUG + sut.startTrace("Register rules"); + sut.stopDebug("Rules registered"); + assertThat(tester.logs()).hasSize(2); + assertThat(tester.logs().get(0)).contains("Register rules"); + assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); + tester.clear(); + + // start DEBUG and stop INFO + sut.startDebug("Register rules"); + sut.stopInfo("Rules registered"); + assertThat(tester.logs()).hasSize(2); + assertThat(tester.logs().get(0)).contains("Register rules"); + assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); + tester.clear(); + + // start INFO and stop TRACE + sut.startInfo("Register rules"); + sut.stopTrace("Rules registered"); + assertThat(tester.logs()).hasSize(2); + assertThat(tester.logs().get(0)).contains("Register rules"); + assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); + } + + @Test + public void log_on_at_stop() throws Exception { + tester.setLevel(LoggerLevel.TRACE); + + // trace + sut.start(); + sut.stopTrace("Rules registered"); + assertThat(tester.logs()).hasSize(1); + assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); + tester.clear(); + + // debug + sut.start(); + sut.stopDebug("Rules registered"); + assertThat(tester.logs()).hasSize(1); + assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); + tester.clear(); + + // info + sut.start(); + sut.stopInfo("Rules registered"); + assertThat(tester.logs()).hasSize(1); + assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); + } + + @Test + public void add_context() throws Exception { + Profiler profiler = Profiler.create(Loggers.get("DefaultProfilerTest")); + profiler.addContext("a_string", "bar"); + profiler.addContext("null_value", null); + profiler.addContext("an_int", 42); + profiler.start(); + // do not write context as there's no message + assertThat(tester.logs()).isEmpty(); + + profiler.addContext("after_start", true); + profiler.stopInfo("Rules registered"); + assertThat(tester.logs()).hasSize(1); + assertThat(tester.logs().get(0)) + .startsWith("Rules registered | time=") + .endsWith("ms | a_string=bar | an_int=42 | after_start=true"); + } + + @Test + public void empty_message() throws Exception { + sut.addContext("foo", "bar"); + sut.startInfo(""); + assertThat(tester.logs()).containsOnly("foo=bar"); + + sut.addContext("after_start", true); + sut.stopInfo(""); + assertThat(tester.logs()).hasSize(2); + assertThat(tester.logs().get(1)) + .startsWith("time=") + .endsWith("ms | foo=bar | after_start=true"); + } + + @Test + public void fail_if_stop_without_message() throws Exception { + sut.start(); + try { + sut.stopInfo(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Profiler#stopXXX() can't be called without any message defined in start methods"); + } + } + + @Test + public void fail_if_stop_without_start() throws Exception { + try { + sut.stopDebug("foo"); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Profiler must be started before being stopped"); + } + } +} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterTest.java index 32bb1000bd6..8b10230815b 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterTest.java @@ -29,22 +29,22 @@ public class LogTesterTest { @Test public void debugLevel() throws Throwable { - boolean initial = sut.isDebugEnabled(); + LoggerLevel initial = sut.getLevel(); // when LogTester is used, then debug logs are enabled by default sut.before(); - assertThat(sut.isDebugEnabled()).isTrue(); - assertThat(Loggers.getFactory().isDebugEnabled()).isTrue(); + assertThat(sut.getLevel()).isEqualTo(LoggerLevel.TRACE); + assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.TRACE); // change - sut.enableDebug(false); - assertThat(sut.isDebugEnabled()).isFalse(); - assertThat(Loggers.getFactory().isDebugEnabled()).isFalse(); + sut.setLevel(LoggerLevel.INFO); + assertThat(sut.getLevel()).isEqualTo(LoggerLevel.INFO); + assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.INFO); - // reset to initial level + // reset to initial level after execution of test sut.after(); - assertThat(sut.isDebugEnabled()).isEqualTo(initial); - assertThat(Loggers.getFactory().isDebugEnabled()).isEqualTo(initial); + assertThat(sut.getLevel()).isEqualTo(initial); + assertThat(Loggers.getFactory().getLevel()).isEqualTo(initial); } @Test @@ -55,7 +55,10 @@ public class LogTesterTest { assertThat(sut.logs()).containsExactly("an information", "warning: 42"); + sut.clear(); + assertThat(sut.logs()).isEmpty(); + sut.after(); - assertThat(LogInterceptor.instance).isSameAs(NullInterceptor.NULL_INSTANCE); + assertThat(LogInterceptor.instance()).isSameAs(NullInterceptor.NULL_INSTANCE); } } diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogbackLoggerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogbackLoggerTest.java index 7bb3ff87068..f17cb9f799f 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogbackLoggerTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogbackLoggerTest.java @@ -25,6 +25,7 @@ import org.junit.Test; import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; public class LogbackLoggerTest { @@ -34,17 +35,13 @@ public class LogbackLoggerTest { public LogTester tester = new LogTester(); @Test - public void debug_enabling() throws Exception { - tester.enableDebug(true); - assertThat(sut.isDebugEnabled()).isTrue(); - - tester.enableDebug(false); - assertThat(sut.isDebugEnabled()).isFalse(); - } - - @Test public void log() throws Exception { // no assertions. Simply verify that calls do not fail. + sut.trace("message"); + sut.trace("message {}", "foo"); + sut.trace("message {} {}", "foo", "bar"); + sut.trace("message {} {} {}", "foo", "bar", "baz"); + sut.debug("message"); sut.debug("message {}", "foo"); sut.debug("message {} {}", "foo", "bar"); @@ -69,17 +66,32 @@ public class LogbackLoggerTest { @Test public void change_level() throws Exception { - assertThat(sut.setLevel(LoggerLevel.ERROR)).isTrue(); - assertThat(sut.logbackLogger().getLevel()).isEqualTo(Level.ERROR); - - assertThat(sut.setLevel(LoggerLevel.WARN)).isTrue(); - assertThat(sut.logbackLogger().getLevel()).isEqualTo(Level.WARN); - assertThat(sut.setLevel(LoggerLevel.INFO)).isTrue(); assertThat(sut.logbackLogger().getLevel()).isEqualTo(Level.INFO); + assertThat(sut.isDebugEnabled()).isFalse(); + assertThat(sut.isTraceEnabled()).isFalse(); assertThat(sut.setLevel(LoggerLevel.DEBUG)).isTrue(); + assertThat(sut.isDebugEnabled()).isTrue(); + assertThat(sut.isTraceEnabled()).isFalse(); assertThat(sut.logbackLogger().getLevel()).isEqualTo(Level.DEBUG); + + assertThat(sut.setLevel(LoggerLevel.TRACE)).isTrue(); assertThat(sut.isDebugEnabled()).isTrue(); + assertThat(sut.isTraceEnabled()).isTrue(); + assertThat(sut.logbackLogger().getLevel()).isEqualTo(Level.TRACE); + } + + @Test + public void info_level_can_not_be_disabled() throws Exception { + try { + sut.setLevel(LoggerLevel.ERROR); + fail(); + + } catch (IllegalArgumentException e) { + assertThat(e).hasMessage("Only TRACE, DEBUG and INFO logging levels are supported. Got: ERROR"); + } + + } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/ui/JRubyProfilingTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullProfilerTest.java index 5682a59eda8..a094ebb368e 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/ui/JRubyProfilingTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullProfilerTest.java @@ -17,34 +17,32 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +package org.sonar.api.utils.log; -package org.sonar.server.ui; - -import org.junit.Before; import org.junit.Test; -import org.sonar.api.config.Settings; -import org.sonar.core.profiling.Profiling; import static org.assertj.core.api.Assertions.assertThat; -public class JRubyProfilingTest { - - private JRubyProfiling profilingFacade; - - @Before - public void initialize() { - profilingFacade = new JRubyProfiling(new Profiling(new Settings())); - } +public class NullProfilerTest { - @Test - public void should_provide_stop_watch() { - String domain = "domain"; - assertThat(profilingFacade.start(domain, "FULL")).isNotNull(); - } + NullProfiler sut = NullProfiler.NULL_INSTANCE; @Test - public void should_safely_ignore_bad_level_parameter() { - String domain = "domain"; - assertThat(profilingFacade.start(domain, "POLOP")).isNotNull(); + public void do_not_fail() throws Exception { + assertThat(sut.start()).isSameAs(sut); + assertThat(sut.startTrace("")).isSameAs(sut); + assertThat(sut.startDebug("")).isSameAs(sut); + assertThat(sut.startInfo("")).isSameAs(sut); + + assertThat(sut.stopTrace()).isSameAs(sut); + assertThat(sut.stopTrace("")).isSameAs(sut); + assertThat(sut.stopDebug("")).isSameAs(sut); + assertThat(sut.stopDebug()).isSameAs(sut); + assertThat(sut.stopInfo()).isSameAs(sut); + assertThat(sut.stopInfo("")).isSameAs(sut); + + assertThat(sut.isDebugEnabled()).isFalse(); + assertThat(sut.isTraceEnabled()).isFalse(); + assertThat(sut.addContext("foo", "bar")).isSameAs(sut); } } diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ProfilerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ProfilerTest.java new file mode 100644 index 00000000000..6a9e0b9c36d --- /dev/null +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ProfilerTest.java @@ -0,0 +1,58 @@ +/* + * SonarQube, open source software quality management tool. + * Copyright (C) 2008-2014 SonarSource + * mailto:contact AT sonarsource DOT com + * + * SonarQube is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * SonarQube is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.utils.log; + +import org.junit.Rule; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ProfilerTest { + @Rule + public LogTester tester = new LogTester(); + + @Test + public void create() throws Exception { + Profiler profiler = Profiler.create(Loggers.get("foo")); + assertThat(profiler).isInstanceOf(DefaultProfiler.class); + } + + @Test + public void create_null_profiler_if_trace_level_is_disabled() throws Exception { + tester.setLevel(LoggerLevel.TRACE); + Profiler profiler = Profiler.createIfTrace(Loggers.get("foo")); + assertThat(profiler).isInstanceOf(DefaultProfiler.class); + + tester.setLevel(LoggerLevel.DEBUG); + profiler = Profiler.createIfTrace(Loggers.get("foo")); + assertThat(profiler).isInstanceOf(NullProfiler.class); + } + + @Test + public void create_null_profiler_if_debug_level_is_disabled() throws Exception { + tester.setLevel(LoggerLevel.TRACE); + Profiler profiler = Profiler.createIfDebug(Loggers.get("foo")); + assertThat(profiler).isInstanceOf(DefaultProfiler.class); + + tester.setLevel(LoggerLevel.INFO); + profiler = Profiler.createIfDebug(Loggers.get("foo")); + assertThat(profiler).isInstanceOf(NullProfiler.class); + } +} |