Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

NUTCH-3112 Utilize parameterized logging

Sebastian Nagel25f5610cce12
diff --git a/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java b/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
index c05200e79..3c8fed957 100644
--- a/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/AbstractFetchSchedule.java
@@ -53,8 +53,8 @@ public abstract class AbstractFetchSchedule extends Configured implements
return;
defaultInterval = conf.getInt("db.fetch.interval.default", 0);
maxInterval = conf.getInt("db.fetch.interval.max", 0);
- LOG.info("defaultInterval=" + defaultInterval);
- LOG.info("maxInterval=" + maxInterval);
+ LOG.info("defaultInterval={}", defaultInterval);
+ LOG.info("maxInterval={}", maxInterval);
}
/**
diff --git a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
index c2eba92b1..6575ccb88 100644
--- a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
@@ -117,7 +117,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
setHostSpecificIntervals("adaptive-host-specific-intervals.txt",
MIN_INTERVAL, MAX_INTERVAL);
} catch (IOException e) {
- LOG.error("Failed reading the configuration file: " + e.toString());
+ LOG.error("Failed reading the configuration file:", e);
}
}
@@ -157,8 +157,9 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
// There should be three parts.
if (parts.length != 3) {
- LOG.error("Malformed (domain, min_interval, max_interval) triplet on line "
- + String.valueOf(lineNo) + " of config. file: `" + line + "`");
+ LOG.error(
+ "Malformed (domain, min_interval, max_interval) triplet on line {} of the config. file: `{}`",
+ lineNo, line);
continue;
}
@@ -177,16 +178,18 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
m = Float.parseFloat(minInt);
M = Float.parseFloat(maxInt);
} catch (NumberFormatException e) {
- LOG.error("Improper fetch intervals given on line " + String.valueOf(lineNo)
- + " of config. file: `" + line + "`: " + e.toString());
+ LOG.error(
+ "Improper fetch intervals given on line {} in the config. file `{}`: {}",
+ lineNo, line, e.toString());
continue;
}
// If both intervals are set to default,
// ignore the line and issue a warning.
if (m == 0 && M == 0) {
- LOG.warn("Ignoring default interval values on line " + String.valueOf(lineNo)
- + " of config. file: `" + line + "`");
+ LOG.warn(
+ "Ignoring default interval values on line {} of config. file: `{}`",
+ lineNo, line);
continue;
}
@@ -200,38 +203,40 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
// Intervals cannot be negative and the min cannot be above the max
// (we assume here that the default values satisfy this).
if (m < 0 || M < 0) {
- LOG.error("Improper fetch intervals given on line " + String.valueOf(lineNo)
- + " of config. file: `" + line
- + "`: intervals cannot be negative");
+ LOG.error(
+ "Improper fetch intervals given on line {} in the config. file: `{}`: intervals cannot be negative",
+ lineNo, line);
continue;
}
if (m > M) {
- LOG.error("Improper fetch intervals given on line " + String.valueOf(lineNo)
- + " of config. file: `" + line
- + "`: min. interval cannot be above max. interval");
+ LOG.error(
+ "Improper fetch intervals given on line {} in the config. file: `{}`: min. interval cannot be above max. interval",
+ lineNo, line);
continue;
}
// The custom intervals should respect the boundaries of the default values.
if (m < defaultMin) {
- LOG.error("Min. interval out of bounds on line " + String.valueOf(lineNo)
- + " of config. file: `" + line + "`");
+ LOG.error(
+ "Min. interval out of bounds on line {} in the config. file: `{}`",
+ lineNo, line);
continue;
}
if (M > defaultMax) {
- LOG.error("Max. interval out of bounds on line " + String.valueOf(lineNo)
- + " of config. file: `" + line + "`");
+ LOG.error(
+ "Max. interval out of bounds on line {} in the config. file: `{}`",
+ lineNo, line);
continue;
}
// If all is well, store the specific intervals.
hostSpecificMinInterval.put(host, m);
- LOG.debug("Added custom min. interval " + m + " for host " + host);
+ LOG.debug("Added custom min. interval {} for host {}.", m, host);
hostSpecificMaxInterval.put(host, M);
- LOG.debug("Added custom max. interval " + M + " for host " + host);
+ LOG.debug("Added custom max. interval {} for host {}.", M, host);
}
}
@@ -379,19 +384,18 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
changeCnt++;
lastModified = curTime;
}
- LOG.info(i + ". " + changed + "\twill fetch at "
- + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY) + " days" + "\t missed "
- + miss);
+ LOG.info("{}. {}\twill fetch at {}\tinterval {} days\tmissed {}", i,
+ changed, (p.getFetchTime() / delta),
+ (p.getFetchInterval() / SECONDS_PER_DAY), miss);
if (p.getFetchTime() <= curTime) {
fetchCnt++;
fs.setFetchSchedule(new Text("http://www.example.com"), p, p
.getFetchTime(), p.getModifiedTime(), curTime, lastModified,
changed ? FetchSchedule.STATUS_MODIFIED
: FetchSchedule.STATUS_NOTMODIFIED);
- LOG.info("\tfetched & adjusted: " + "\twill fetch at "
- + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY) + " days");
+ LOG.info("\tfetched and adjusted:\twill fetch at {}\tinterval {} days",
+ (p.getFetchTime() / delta),
+ (p.getFetchInterval() / SECONDS_PER_DAY));
if (!changed)
miss++;
if (miss > maxMiss)
@@ -404,8 +408,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
miss++;
curTime += delta;
}
- LOG.info("Total missed: " + totalMiss + ", max miss: " + maxMiss);
- LOG.info("Page changed " + changeCnt + " times, fetched " + fetchCnt
- + " times.");
+ LOG.info("Total missed: {}, max miss: {}", totalMiss, maxMiss);
+ LOG.info("Page changed {} times, fetched {} times.", changeCnt, fetchCnt);
}
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDb.java b/src/java/org/apache/nutch/crawl/CrawlDb.java
index 2b609c0a6..01598a5f1 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDb.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDb.java
@@ -40,7 +40,6 @@ import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.metadata.Nutch;
@@ -370,7 +369,7 @@ public class CrawlDb extends NutchTool implements Tool {
results.put(Nutch.VAL_RESULT, Integer.toString(0));
return results;
} catch (Exception e) {
- LOG.error("CrawlDb update: " + StringUtils.stringifyException(e));
+ LOG.error("CrawlDb update:", e);
results.put(Nutch.VAL_RESULT, Integer.toString(-1));
return results;
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
index 8abe4b4bd..d9ab0d3cc 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
@@ -95,7 +95,7 @@ public class CrawlDbFilter extends
try {
url = normalizers.normalize(url, scope); // normalize the url
} catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
+ LOG.warn("Skipping {}: ", url, e);
url = null;
}
}
@@ -103,7 +103,7 @@ public class CrawlDbFilter extends
try {
url = filters.filter(url); // filter the url
} catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
+ LOG.warn("Skipping {}: ", url, e);
url = null;
}
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java b/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
index 6ee4b43cd..7b4cbfa04 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
@@ -40,7 +40,6 @@ import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.util.NutchConfiguration;
@@ -229,7 +228,7 @@ public class CrawlDbMerger extends Configured implements Tool {
merge(output, dbs.toArray(new Path[dbs.size()]), normalize, filter);
return 0;
} catch (Exception e) {
- LOG.error("CrawlDb merge: " + StringUtils.stringifyException(e));
+ LOG.error("CrawlDb merge:", e);
return -1;
}
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
index 29e8efe17..03cf0fbd3 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReader.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
@@ -732,68 +732,66 @@ public class CrawlDbReader extends AbstractChecker implements Closeable {
TreeMap<String, Writable> stats = processStatJobHelper(crawlDb, config,
sort);
- if (LOG.isInfoEnabled()) {
- LOG.info("Statistics for CrawlDb: {}", crawlDb);
- LongWritable totalCnt = new LongWritable(0);
- if (stats.containsKey("T")) {
- totalCnt = ((LongWritable) stats.get("T"));
- stats.remove("T");
+ LOG.info("Statistics for CrawlDb: {}", crawlDb);
+ LongWritable totalCnt = new LongWritable(0);
+ if (stats.containsKey("T")) {
+ totalCnt = ((LongWritable) stats.get("T"));
+ stats.remove("T");
+ }
+ LOG.info("TOTAL urls:\t{}", totalCnt.get());
+ for (Map.Entry<String, Writable> entry : stats.entrySet()) {
+ String k = entry.getKey();
+ long value = 0;
+ double fvalue = 0.0;
+ byte[] bytesValue = null;
+ Writable val = entry.getValue();
+ if (val instanceof LongWritable) {
+ value = ((LongWritable) val).get();
+ } else if (val instanceof FloatWritable) {
+ fvalue = ((FloatWritable) val).get();
+ } else if (val instanceof BytesWritable) {
+ bytesValue = ((BytesWritable) val).getBytes();
}
- LOG.info("TOTAL urls:\t" + totalCnt.get());
- for (Map.Entry<String, Writable> entry : stats.entrySet()) {
- String k = entry.getKey();
- long value = 0;
- double fvalue = 0.0;
- byte[] bytesValue = null;
- Writable val = entry.getValue();
- if (val instanceof LongWritable) {
- value = ((LongWritable) val).get();
- } else if (val instanceof FloatWritable) {
- fvalue = ((FloatWritable) val).get();
- } else if (val instanceof BytesWritable) {
- bytesValue = ((BytesWritable) val).getBytes();
- }
- if (k.equals("scn")) {
- LOG.info("min score:\t" + fvalue);
- } else if (k.equals("scx")) {
- LOG.info("max score:\t" + fvalue);
- } else if (k.equals("sct")) {
- LOG.info("avg score:\t" + (fvalue / totalCnt.get()));
- } else if (k.equals("scNaN")) {
- LOG.info("score == NaN:\t" + value);
- } else if (k.equals("ftn")) {
- LOG.info("earliest fetch time:\t" + new Date(1000 * 60 * value));
- } else if (k.equals("ftx")) {
- LOG.info("latest fetch time:\t" + new Date(1000 * 60 * value));
- } else if (k.equals("ftt")) {
- LOG.info("avg of fetch times:\t"
- + new Date(1000 * 60 * (value / totalCnt.get())));
- } else if (k.equals("fin")) {
- LOG.info("shortest fetch interval:\t{}",
- TimingUtil.secondsToDaysHMS(value));
- } else if (k.equals("fix")) {
- LOG.info("longest fetch interval:\t{}",
- TimingUtil.secondsToDaysHMS(value));
- } else if (k.equals("fit")) {
- LOG.info("avg fetch interval:\t{}",
- TimingUtil.secondsToDaysHMS(value / totalCnt.get()));
- } else if (k.startsWith("status")) {
- String[] st = k.split(" ");
- int code = Integer.parseInt(st[1]);
- if (st.length > 2)
- LOG.info(" " + st[2] + " :\t" + val);
- else
- LOG.info(st[0] + " " + code + " ("
- + CrawlDatum.getStatusName((byte) code) + "):\t" + val);
- } else if (k.equals("scd")) {
- MergingDigest tdigest = MergingDigest
- .fromBytes(ByteBuffer.wrap(bytesValue));
- for (double q : quantiles) {
- LOG.info("score quantile {}:\t{}", q, tdigest.quantile(q));
- }
- } else {
- LOG.info(k + ":\t" + val);
+ if (k.equals("scn")) {
+ LOG.info("min score:\t{}", fvalue);
+ } else if (k.equals("scx")) {
+ LOG.info("max score:\t{}", fvalue);
+ } else if (k.equals("sct")) {
+ LOG.info("avg score:\t{}", (fvalue / totalCnt.get()));
+ } else if (k.equals("scNaN")) {
+ LOG.info("score == NaN:\t{}", value);
+ } else if (k.equals("ftn")) {
+ LOG.info("earliest fetch time:\t{}", new Date(1000 * 60 * value));
+ } else if (k.equals("ftx")) {
+ LOG.info("latest fetch time:\t{}", new Date(1000 * 60 * value));
+ } else if (k.equals("ftt")) {
+ LOG.info("avg of fetch times:\t{}",
+ new Date(1000 * 60 * (value / totalCnt.get())));
+ } else if (k.equals("fin")) {
+ LOG.info("shortest fetch interval:\t{}",
+ TimingUtil.secondsToDaysHMS(value));
+ } else if (k.equals("fix")) {
+ LOG.info("longest fetch interval:\t{}",
+ TimingUtil.secondsToDaysHMS(value));
+ } else if (k.equals("fit")) {
+ LOG.info("avg fetch interval:\t{}",
+ TimingUtil.secondsToDaysHMS(value / totalCnt.get()));
+ } else if (k.startsWith("status")) {
+ String[] st = k.split(" ");
+ int code = Integer.parseInt(st[1]);
+ if (st.length > 2)
+ LOG.info(" {} :\t{}", st[2], val);
+ else
+ LOG.info("{} {} ({}):\t{}", st[0], code,
+ CrawlDatum.getStatusName((byte) code), val);
+ } else if (k.equals("scd")) {
+ MergingDigest tdigest = MergingDigest
+ .fromBytes(ByteBuffer.wrap(bytesValue));
+ for (double q : quantiles) {
+ LOG.info("score quantile {}:\t{}", q, tdigest.quantile(q));
}
+ } else {
+ LOG.info("{}:\t{}", k, val);
}
}
LOG.info("CrawlDb statistics: done");
@@ -956,7 +954,7 @@ public class CrawlDbReader extends AbstractChecker implements Closeable {
String output, Configuration config)
throws IOException, ClassNotFoundException, InterruptedException {
- LOG.info("CrawlDb topN: starting (topN=" + topN + ", min=" + min + ")");
+ LOG.info("CrawlDb topN: starting (topN={}, min={})", topN, min);
LOG.info("CrawlDb db: {}", crawlDb);
Path outFolder = new Path(output);
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
index f00cfc5f8..deb266af6 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
@@ -129,7 +129,7 @@ public class CrawlDbReducer extends
metaFromParse = datum.getMetaData();
break;
default:
- LOG.warn("Unknown status, key: " + key + ", datum: " + datum);
+ LOG.warn("Unknown status, key: {}, datum: {}", key, datum);
}
}
@@ -263,8 +263,8 @@ public class CrawlDbReducer extends
result.setStatus(CrawlDatum.STATUS_DB_REDIR_TEMP);
break;
default:
- LOG.warn("Unexpected status: " + fetch.getStatus()
- + " resetting to old status.");
+ LOG.warn("Unexpected status: {} resetting to old status.",
+ fetch.getStatus());
if (oldSet)
result.setStatus(old.getStatus());
else
diff --git a/src/java/org/apache/nutch/crawl/DeduplicationJob.java b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
index e37001354..3e12d4598 100644
--- a/src/java/org/apache/nutch/crawl/DeduplicationJob.java
+++ b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
@@ -42,7 +42,6 @@ import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.metadata.Nutch;
@@ -339,11 +338,10 @@ public class DeduplicationJob extends NutchTool implements Tool {
if (g != null) {
Counter counter = g.findCounter("Documents marked as duplicate");
long dups = counter.getValue();
- LOG.info("Deduplication: " + (int) dups
- + " documents marked as duplicates");
+ LOG.info("Deduplication: {} documents marked as duplicates", dups);
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
- LOG.error("DeduplicationJob: " + StringUtils.stringifyException(e));
+ LOG.error("DeduplicationJob:", e);
fs.delete(tempDir, true);
return -1;
}
@@ -369,7 +367,7 @@ public class DeduplicationJob extends NutchTool implements Tool {
throw new RuntimeException(message);
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
- LOG.error("DeduplicationMergeJob: " + StringUtils.stringifyException(e));
+ LOG.error("DeduplicationMergeJob:", e);
fs.delete(tempDir, true);
NutchJob.cleanupAfterFailure(outPath, lock, fs);
return -1;
@@ -381,8 +379,8 @@ public class DeduplicationJob extends NutchTool implements Tool {
fs.delete(tempDir, true);
stopWatch.stop();
- LOG.info("Deduplication finished, elapsed: {} ms", stopWatch.getTime(
- TimeUnit.MILLISECONDS));
+ LOG.info("Deduplication finished, elapsed: {} ms",
+ stopWatch.getTime(TimeUnit.MILLISECONDS));
return 0;
}
diff --git a/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java b/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
index 9cad94c78..4922bb08a 100644
--- a/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
+++ b/src/java/org/apache/nutch/crawl/FetchScheduleFactory.java
@@ -46,7 +46,7 @@ public class FetchScheduleFactory {
FetchSchedule impl = (FetchSchedule) objectCache.getObject(clazz);
if (impl == null) {
try {
- LOG.info("Using FetchSchedule impl: " + clazz);
+ LOG.info("Using FetchSchedule impl: {}", clazz);
Class<?> implClass = Class.forName(clazz);
impl = (FetchSchedule) implClass.getConstructor().newInstance();
impl.setConf(conf);
diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.java
index 570b19d93..82475af5b 100644
--- a/src/java/org/apache/nutch/crawl/Generator.java
+++ b/src/java/org/apache/nutch/crawl/Generator.java
@@ -447,21 +447,30 @@ public class Generator extends NutchTool implements Tool {
if (host != null) {
if (maxCountExpr != null) {
try {
- long variableMaxCount = Math.round((double)maxCountExpr.execute(createContext(host)));
- LOG.debug("Generator: variable maxCount: {} for {}", variableMaxCount, hostname);
- maxCount = (int)variableMaxCount;
+ long variableMaxCount = Math
+ .round((double) maxCountExpr.execute(createContext(host)));
+ LOG.debug("Generator: variable maxCount: {} for {}",
+ variableMaxCount, hostname);
+ maxCount = (int) variableMaxCount;
} catch (Exception e) {
- LOG.error("Unable to execute variable maxCount expression because: " + e.getMessage(), e);
+ LOG.error(
+ "Unable to execute variable maxCount expression because: {}",
+ e.getMessage(), e);
}
}
if (fetchDelayExpr != null) {
try {
- long variableFetchDelay = Math.round((double)fetchDelayExpr.execute(createContext(host)));
- LOG.debug("Generator: variable fetchDelay: {} ms for {}", variableFetchDelay, hostname);
- variableFetchDelayWritable = new LongWritable(variableFetchDelay);
+ long variableFetchDelay = Math.round(
+ (double) fetchDelayExpr.execute(createContext(host)));
+ LOG.debug("Generator: variable fetchDelay: {} ms for {}",
+ variableFetchDelay, hostname);
+ variableFetchDelayWritable = new LongWritable(
+ variableFetchDelay);
} catch (Exception e) {
- LOG.error("Unable to execute fetch delay expression because: " + e.getMessage(), e);
+ LOG.error(
+ "Unable to execute fetch delay expression because: {}",
+ e.getMessage(), e);
}
}
}
@@ -880,8 +889,8 @@ public class Generator extends NutchTool implements Tool {
stopWatch.start();
LOG.info("Generator: starting");
LOG.info("Generator: selecting best-scoring urls due for fetch.");
- LOG.info("Generator: filtering: " + filter);
- LOG.info("Generator: normalizing: " + norm);
+ LOG.info("Generator: filtering: {}", filter);
+ LOG.info("Generator: normalizing: {}", norm);
if (topN != Long.MAX_VALUE) {
LOG.info("Generator: topN: {}", topN);
}
@@ -1051,7 +1060,7 @@ public class Generator extends NutchTool implements Tool {
Path segment = new Path(segmentsDir, generateSegmentName());
Path output = new Path(segment, CrawlDatum.GENERATE_DIR_NAME);
- LOG.info("Generator: segment: " + segment);
+ LOG.info("Generator: segment: {}", segment);
Job job = Job.getInstance(getConf(), "Nutch Generator: partition segment " + segment);
Configuration conf = job.getConfiguration();
@@ -1163,7 +1172,7 @@ public class Generator extends NutchTool implements Tool {
if (segs == null)
return 1;
} catch (Exception e) {
- LOG.error("Generator: " + StringUtils.stringifyException(e));
+ LOG.error("Generator:", e);
return -1;
}
return 0;
@@ -1247,7 +1256,7 @@ public class Generator extends NutchTool implements Tool {
}
} catch (Exception e) {
- LOG.error("Generator: " + StringUtils.stringifyException(e));
+ LOG.error("Generator: {}", StringUtils.stringifyException(e));
results.put(Nutch.VAL_RESULT, Integer.toString(-1));
return results;
}
diff --git a/src/java/org/apache/nutch/crawl/Injector.java b/src/java/org/apache/nutch/crawl/Injector.java
index 314cf448d..819c91e3a 100644
--- a/src/java/org/apache/nutch/crawl/Injector.java
+++ b/src/java/org/apache/nutch/crawl/Injector.java
@@ -32,7 +32,6 @@ import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -158,7 +157,7 @@ public class Injector extends NutchTool implements Tool {
if (filters != null)
url = filters.filter(url); // filter the url
} catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
+ LOG.warn("Skipping {}: {}", url, e);
url = null;
}
}
@@ -200,8 +199,8 @@ public class Injector extends NutchTool implements Tool {
datum.getMetaData().put(new Text(metaname), new Text(metavalue));
}
} catch (NumberFormatException nfe) {
- LOG.error("Invalid number '" + metavalue + "' in metadata '"
- + metaname + "' for url " + url);
+ LOG.error("Invalid number '{}' in metadata '{}' for url {}",
+ metavalue, metaname, url);
}
}
}
@@ -285,8 +284,8 @@ public class Injector extends NutchTool implements Tool {
scoreInjected = conf.getFloat("db.score.injected", 1.0f);
overwrite = conf.getBoolean("db.injector.overwrite", false);
update = conf.getBoolean("db.injector.update", false);
- LOG.info("Injector: overwrite: " + overwrite);
- LOG.info("Injector: update: " + update);
+ LOG.info("Injector: overwrite: {}", overwrite);
+ LOG.info("Injector: update: {}", update);
}
/**
@@ -581,7 +580,7 @@ public class Injector extends NutchTool implements Tool {
filter, filterNormalizeAll);
return 0;
} catch (Exception e) {
- LOG.error("Injector: " + StringUtils.stringifyException(e));
+ LOG.error("Injector:", e);
return -1;
}
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbFilter.java b/src/java/org/apache/nutch/crawl/LinkDbFilter.java
index ed9151ae8..f507ad65e 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbFilter.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbFilter.java
@@ -79,7 +79,7 @@ public class LinkDbFilter extends Mapper<Text, Inlinks, Text, Inlinks> {
try {
url = normalizers.normalize(url, scope); // normalize the url
} catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
+ LOG.warn("Skipping {}: {}", url, e);
url = null;
}
}
@@ -87,7 +87,7 @@ public class LinkDbFilter extends Mapper<Text, Inlinks, Text, Inlinks> {
try {
url = filters.filter(url); // filter the url
} catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
+ LOG.warn("Skipping {}: {}", url, e);
url = null;
}
}
@@ -102,7 +102,7 @@ public class LinkDbFilter extends Mapper<Text, Inlinks, Text, Inlinks> {
try {
fromUrl = normalizers.normalize(fromUrl, scope); // normalize the url
} catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
+ LOG.warn("Skipping {}: {}", fromUrl, e);
fromUrl = null;
}
}
@@ -110,7 +110,7 @@ public class LinkDbFilter extends Mapper<Text, Inlinks, Text, Inlinks> {
try {
fromUrl = filters.filter(fromUrl); // filter the url
} catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
+ LOG.warn("Skipping {}: {}", fromUrl, e);
fromUrl = null;
}
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbMerger.java b/src/java/org/apache/nutch/crawl/LinkDbMerger.java
index c3da2031e..39c23c825 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbMerger.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbMerger.java
@@ -138,8 +138,8 @@ public class LinkDbMerger extends Configured implements Tool {
LinkDb.CURRENT_NAME));
stopWatch.stop();
- LOG.info("LinkDb merge: finished, elapsed: {} ms" + stopWatch.getTime(
- TimeUnit.MILLISECONDS));
+ LOG.info("LinkDb merge: finished, elapsed: {} ms",
+ stopWatch.getTime(TimeUnit.MILLISECONDS));
}
public static Job createMergeJob(Configuration config, Path linkDb,
@@ -211,7 +211,7 @@ public class LinkDbMerger extends Configured implements Tool {
merge(output, dbs.toArray(new Path[dbs.size()]), normalize, filter);
return 0;
} catch (Exception e) {
- LOG.error("LinkDbMerger: " + StringUtils.stringifyException(e));
+ LOG.error("LinkDbMerger: {}", StringUtils.stringifyException(e));
return -1;
}
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbReader.java b/src/java/org/apache/nutch/crawl/LinkDbReader.java
index 9ae356683..976e1a2a7 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbReader.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbReader.java
@@ -260,7 +260,7 @@ public class LinkDbReader extends AbstractChecker implements Closeable {
}
}
} catch (Exception e) {
- LOG.error("LinkDbReader: " + StringUtils.stringifyException(e));
+ LOG.error("LinkDbReader:", e);
return -1;
}
diff --git a/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java b/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
index 6a7f13e85..d441acacf 100644
--- a/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
@@ -155,7 +155,7 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
mimeMap.put(StringUtils.lowerCase(splits[0]), new AdaptiveRate(
Float.valueOf(splits[1]), Float.valueOf(splits[2])));
} else {
- LOG.warn("Invalid configuration line in: " + line);
+ LOG.warn("Invalid configuration line in: {}", line);
}
}
}
@@ -199,10 +199,9 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
lastModified = curTime;
}
- LOG.info(i + ". " + changed + "\twill fetch at "
- + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY) + " days" + "\t missed "
- + miss);
+ LOG.info("{}. {}\twill fetch at {}\tinterval {} days\t missed {}", i,
+ changed, (p.getFetchTime() / delta),
+ (p.getFetchInterval() / SECONDS_PER_DAY), miss);
if (p.getFetchTime() <= curTime) {
fetchCnt++;
@@ -211,9 +210,10 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
changed ? FetchSchedule.STATUS_MODIFIED
: FetchSchedule.STATUS_NOTMODIFIED);
- LOG.info("\tfetched & adjusted: " + "\twill fetch at "
- + (p.getFetchTime() / delta) + "\tinterval "
- + (p.getFetchInterval() / SECONDS_PER_DAY) + " days");
+ LOG.info(
+ "\tfetched and adjusted:\twill fetch at {}\tinterval {} days",
+ (p.getFetchTime() / delta),
+ (p.getFetchInterval() / SECONDS_PER_DAY));
if (!changed)
miss++;
@@ -228,9 +228,8 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
miss++;
curTime += delta;
}
- LOG.info("Total missed: " + totalMiss + ", max miss: " + maxMiss);
- LOG.info("Page changed " + changeCnt + " times, fetched " + fetchCnt
- + " times.");
+ LOG.info("Total missed: {}, max miss: {}", totalMiss, maxMiss);
+ LOG.info("Page changed {} times, fetched {} times.", changeCnt, fetchCnt);
}
}
diff --git a/src/java/org/apache/nutch/crawl/URLPartitioner.java b/src/java/org/apache/nutch/crawl/URLPartitioner.java
index 8f0764aab..cd1140a69 100644
--- a/src/java/org/apache/nutch/crawl/URLPartitioner.java
+++ b/src/java/org/apache/nutch/crawl/URLPartitioner.java
@@ -60,7 +60,7 @@ public class URLPartitioner extends Partitioner<Text, Writable> implements Confi
// check that the mode is known
if (!mode.equals(PARTITION_MODE_IP) && !mode.equals(PARTITION_MODE_DOMAIN)
&& !mode.equals(PARTITION_MODE_HOST)) {
- LOG.error("Unknown partition mode : " + mode + " - forcing to byHost");
+ LOG.error("Unknown partition mode : {} - forcing to byHost", mode);
mode = PARTITION_MODE_HOST;
}
normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_PARTITION);
@@ -82,7 +82,7 @@ public class URLPartitioner extends Partitioner<Text, Writable> implements Confi
URLNormalizers.SCOPE_PARTITION);
url = new URL(urlString);
} catch (MalformedURLException e) {
- LOG.warn("Malformed URL: '" + urlString + "'");
+ LOG.warn("Malformed URL: '{}'", urlString);
}
if (url == null) {
@@ -97,7 +97,7 @@ public class URLPartitioner extends Partitioner<Text, Writable> implements Confi
InetAddress address = InetAddress.getByName(url.getHost());
hashCode = address.getHostAddress().hashCode();
} catch (UnknownHostException e) {
- Generator.LOG.info("Couldn't find IP for host: " + url.getHost());
+ Generator.LOG.info("Couldn't find IP for host: {}", url.getHost());
}
}
diff --git a/src/java/org/apache/nutch/fetcher/FetchItem.java b/src/java/org/apache/nutch/fetcher/FetchItem.java
index b3b2bc2ec..9b4fc991b 100644
--- a/src/java/org/apache/nutch/fetcher/FetchItem.java
+++ b/src/java/org/apache/nutch/fetcher/FetchItem.java
@@ -90,7 +90,7 @@ public class FetchItem {
try {
u = new URL(url.toString());
} catch (Exception e) {
- LOG.warn("Cannot parse url: " + url, e);
+ LOG.warn("Cannot parse url: {}", url, e);
return null;
}
String key;
@@ -100,20 +100,19 @@ public class FetchItem {
key = addr.getHostAddress();
} catch (final UnknownHostException e) {
// unable to resolve it, so don't fall back to host name
- LOG.warn("Unable to resolve: " + u.getHost() + ", skipping.");
+ LOG.warn("Unable to resolve: {}, skipping.", u.getHost());
return null;
}
} else if (FetchItemQueues.QUEUE_MODE_DOMAIN.equalsIgnoreCase(queueMode)) {
key = URLUtil.getDomainName(u).toLowerCase(Locale.ROOT);
if (key == null) {
- LOG.warn("Unknown domain for url: " + url
- + ", using URL string as key");
+ LOG.warn("Unknown domain for url: {}, using URL string as key", url);
key = u.toExternalForm();
}
} else {
key = u.getHost().toLowerCase(Locale.ROOT);
if (key == null) {
- LOG.warn("Unknown host for url: " + url + ", using URL string as key");
+ LOG.warn("Unknown host for url: {}, using URL string as key", url);
key = u.toExternalForm();
}
}
diff --git a/src/java/org/apache/nutch/fetcher/FetchItemQueue.java b/src/java/org/apache/nutch/fetcher/FetchItemQueue.java
index 62434e483..77715b8b3 100644
--- a/src/java/org/apache/nutch/fetcher/FetchItemQueue.java
+++ b/src/java/org/apache/nutch/fetcher/FetchItemQueue.java
@@ -149,15 +149,15 @@ public class FetchItemQueue {
}
public synchronized void dump() {
- LOG.info(" maxThreads = " + maxThreads);
- LOG.info(" inProgress = " + inProgress.get());
- LOG.info(" crawlDelay = " + crawlDelay);
- LOG.info(" minCrawlDelay = " + minCrawlDelay);
- LOG.info(" nextFetchTime = " + nextFetchTime.get());
- LOG.info(" now = " + System.currentTimeMillis());
+ LOG.info(" maxThreads = {}", maxThreads);
+ LOG.info(" inProgress = {}", inProgress.get());
+ LOG.info(" crawlDelay = {}", crawlDelay);
+ LOG.info(" minCrawlDelay = {}", minCrawlDelay);
+ LOG.info(" nextFetchTime = {}", nextFetchTime.get());
+ LOG.info(" now = {}", System.currentTimeMillis());
for (int i = 0; i < queue.size(); i++) {
FetchItem it = queue.get(i);
- LOG.info(" " + i + ". " + it.url);
+ LOG.info(" {}. {}", i, it.url);
}
}
diff --git a/src/java/org/apache/nutch/fetcher/FetchItemQueues.java b/src/java/org/apache/nutch/fetcher/FetchItemQueues.java
index 2a6cb5e51..8cf9dd6e3 100644
--- a/src/java/org/apache/nutch/fetcher/FetchItemQueues.java
+++ b/src/java/org/apache/nutch/fetcher/FetchItemQueues.java
@@ -81,7 +81,7 @@ public class FetchItemQueues {
this.maxThreads = conf.getInt("fetcher.threads.per.queue", 1);
queueMode = conf.get("fetcher.queue.mode", QUEUE_MODE_HOST);
queueMode = checkQueueMode(queueMode);
- LOG.info("Using queue mode : " + queueMode);
+ LOG.info("Using queue mode : {}", queueMode);
this.crawlDelay = (long) (conf.getFloat("fetcher.server.delay", 1.0f) * 1000);
this.minCrawlDelay = (long) (conf.getFloat("fetcher.server.min.delay",
@@ -161,7 +161,7 @@ public class FetchItemQueues {
public void finishFetchItem(FetchItem it, boolean asap) {
FetchItemQueue fiq = queues.get(it.queueID);
if (fiq == null) {
- LOG.warn("Attempting to finish item from unknown queue: " + it);
+ LOG.warn("Attempting to finish item from unknown queue: {}", it);
return;
}
fiq.finishFetchItem(it, asap);
@@ -413,7 +413,7 @@ public class FetchItemQueues {
FetchItemQueue fiq = queues.get(id);
if (fiq.getQueueSize() == 0)
continue;
- LOG.info("* queue: " + id);
+ LOG.info("* queue: {}", id);
fiq.dump();
}
}
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index 2db52fb5d..ead0167db 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -296,10 +296,10 @@ public class Fetcher extends NutchTool implements Tool {
reportStatus(innerContext, fetchQueues, pagesLastSec, bytesLastSec);
- LOG.info("-activeThreads=" + activeThreads + ", spinWaiting="
- + spinWaiting.get() + ", fetchQueues.totalSize="
- + fetchQueues.getTotalSize() + ", fetchQueues.getQueueCount="
- + fetchQueues.getQueueCount());
+ LOG.info(
+ "-activeThreads={}, spinWaiting={}, fetchQueues.totalSize={}, fetchQueues.getQueueCount={}",
+ activeThreads, spinWaiting.get(), fetchQueues.getTotalSize(),
+ fetchQueues.getQueueCount());
if (!feeder.isAlive() && fetchQueues.getTotalSize() < 5) {
fetchQueues.dump();
@@ -612,9 +612,7 @@ public class Fetcher extends NutchTool implements Tool {
if (agentName == null || agentName.trim().length() == 0) {
String message = "Fetcher: No agents listed in 'http.agent.name'"
+ " property.";
- if (LOG.isErrorEnabled()) {
- LOG.error(message);
- }
+ LOG.error(message);
throw new IllegalArgumentException(message);
}
}
diff --git a/src/java/org/apache/nutch/fetcher/FetcherThread.java b/src/java/org/apache/nutch/fetcher/FetcherThread.java
index ebb28aadb..f886aed42 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherThread.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherThread.java
@@ -309,11 +309,9 @@ public class FetcherThread extends Thread {
}
do {
- if (LOG.isInfoEnabled()) {
- LOG.info("{} {} fetching {} (queue crawl delay={}ms)", getName(),
- Thread.currentThread().getId(), fit.url,
- fetchQueues.getFetchItemQueue(fit.queueID).crawlDelay);
- }
+ LOG.info("{} {} fetching {} (queue crawl delay={}ms)", getName(),
+ Thread.currentThread().getId(), fit.url,
+ fetchQueues.getFetchItemQueue(fit.queueID).crawlDelay);
LOG.debug("redirectCount={}", redirectCount);
redirecting = false;
Protocol protocol = this.protocolFactory.getProtocol(fit.u);
@@ -375,7 +373,7 @@ public class FetcherThread extends Thread {
}
fiq.crawlDelay = crawlDelay;
LOG.debug(
- "Crawl delay for queue: {} is set to {} as per robots.txt. url: ",
+ "Crawl delay for queue: {} is set to {} as per robots.txt. url: {}",
fit.queueID, fiq.crawlDelay, fit.url);
}
}
@@ -472,10 +470,8 @@ public class FetcherThread extends Thread {
break;
default:
- if (LOG.isWarnEnabled()) {
- LOG.warn("{} {} Unknown ProtocolStatus: {}", getName(),
- Thread.currentThread().getId(), status.getCode());
- }
+ LOG.warn("{} {} Unknown ProtocolStatus: {}", getName(),
+ Thread.currentThread().getId(), status.getCode());
output(fit.url, fit.datum, null, status,
CrawlDatum.STATUS_FETCH_RETRY);
}
@@ -484,11 +480,9 @@ public class FetcherThread extends Thread {
fetchQueues.finishFetchItem(fit);
context.getCounter("FetcherStatus", "redirect_count_exceeded")
.increment(1);
- if (LOG.isInfoEnabled()) {
- LOG.info("{} {} - redirect count exceeded {} ({})", getName(),
- Thread.currentThread().getId(), fit.url,
- maxRedirectExceededSkip ? "skipped" : "linked");
- }
+ LOG.info("{} {} - redirect count exceeded {} ({})", getName(),
+ Thread.currentThread().getId(), fit.url,
+ maxRedirectExceededSkip ? "skipped" : "linked");
if (maxRedirectExceededSkip) {
// skip redirect target when redirect count is exceeded
} else {
@@ -519,9 +513,7 @@ public class FetcherThread extends Thread {
}
} catch (Throwable e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("fetcher caught:", e);
- }
+ LOG.error("fetcher caught:", e);
} finally {
if (fit != null) {
fetchQueues.finishFetchItem(fit);
@@ -646,10 +638,8 @@ public class FetcherThread extends Thread {
}
private void logError(Text url, String message) {
- if (LOG.isInfoEnabled()) {
- LOG.info("{} {} fetch of {} failed with: {}", getName(),
- Thread.currentThread().getId(), url, message);
- }
+ LOG.info("{} {} fetch of {} failed with: {}", getName(),
+ Thread.currentThread().getId(), url, message);
errors.incrementAndGet();
}
@@ -681,10 +671,8 @@ public class FetcherThread extends Thread {
try {
scfilters.passScoreBeforeParsing(key, datum, content);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("{} {} Couldn't pass score, url {} ({})", getName(),
- Thread.currentThread().getId(), key, e);
- }
+ LOG.warn("{} {} Couldn't pass score, url {} ({})", getName(),
+ Thread.currentThread().getId(), key, e);
}
if (status == CrawlDatum.STATUS_FETCH_SUCCESS) {
@@ -746,10 +734,8 @@ public class FetcherThread extends Thread {
try {
scfilters.passScoreAfterParsing(url, content, parse);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("{} {} Couldn't pass score, url {} ({})", getName(),
- Thread.currentThread().getId(), key, e);
- }
+ LOG.warn("{} {} Couldn't pass score, url {} ({})", getName(),
+ Thread.currentThread().getId(), key, e);
}
String origin = null;
@@ -870,9 +856,7 @@ public class FetcherThread extends Thread {
}
}
} catch (IOException e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("fetcher caught:", e);
- }
+ LOG.error("fetcher caught:", e);
}
// return parse status (of the "original" URL if the ParseResult contains
@@ -890,13 +874,13 @@ public class FetcherThread extends Thread {
private void outputRobotsTxt(List<Content> robotsTxtContent) throws InterruptedException {
for (Content robotsTxt : robotsTxtContent) {
- LOG.debug("fetched and stored robots.txt {}",
+ LOG.debug("Fetched and stored robots.txt {}",
robotsTxt.getUrl());
try {
context.write(new Text(robotsTxt.getUrl()),
new NutchWritable(robotsTxt));
} catch (IOException e) {
- LOG.error("fetcher caught:", e);
+ LOG.error("Fetcher failed to store the robots.txt:", e);
}
}
}
diff --git a/src/java/org/apache/nutch/fetcher/QueueFeeder.java b/src/java/org/apache/nutch/fetcher/QueueFeeder.java
index 19fb128eb..c48c4b8f3 100644
--- a/src/java/org/apache/nutch/fetcher/QueueFeeder.java
+++ b/src/java/org/apache/nutch/fetcher/QueueFeeder.java
@@ -106,7 +106,7 @@ public class QueueFeeder extends Thread {
try {
hasMore = context.nextKeyValue();
} catch (IOException e) {
- LOG.error("QueueFeeder error reading input, record " + cnt, e);
+ LOG.error("QueueFeeder error reading input, record {}", cnt, e);
return;
} catch (InterruptedException e) {
LOG.info("QueueFeeder interrupted, exception:", e);
@@ -158,7 +158,7 @@ public class QueueFeeder extends Thread {
feed--;
}
} catch (IOException e) {
- LOG.error("QueueFeeder error reading input, record " + cnt, e);
+ LOG.error("QueueFeeder error reading input, record {}", cnt, e);
return;
} catch (InterruptedException e) {
LOG.info("QueueFeeder interrupted, exception:", e);
diff --git a/src/java/org/apache/nutch/hostdb/ReadHostDb.java b/src/java/org/apache/nutch/hostdb/ReadHostDb.java
index 036b78650..9f2e4a384 100644
--- a/src/java/org/apache/nutch/hostdb/ReadHostDb.java
+++ b/src/java/org/apache/nutch/hostdb/ReadHostDb.java
@@ -38,7 +38,6 @@ import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.util.NutchConfiguration;
@@ -136,7 +135,7 @@ public class ReadHostDb extends Configured implements Tool {
return;
}
} catch (Exception e) {
- LOG.info(e.toString() + " for " + key.toString());
+ LOG.info("{} for {}", e.toString(), key.toString());
}
}
@@ -266,12 +265,12 @@ public class ReadHostDb extends Configured implements Tool {
}
if (args[i].equals("-get")) {
get = args[i + 1];
- LOG.info("ReadHostDb: get: "+ get);
+ LOG.info("ReadHostDb: get: {}", get);
i++;
}
if (args[i].equals("-expr")) {
expr = args[i + 1];
- LOG.info("ReadHostDb: evaluating expression: " + expr);
+ LOG.info("ReadHostDb: evaluating expression: {}", expr);
i++;
}
}
@@ -284,7 +283,7 @@ public class ReadHostDb extends Configured implements Tool {
}
return 0;
} catch (Exception e) {
- LOG.error("ReadHostDb: " + StringUtils.stringifyException(e));
+ LOG.error("ReadHostDb:", e);
return -1;
}
}
diff --git a/src/java/org/apache/nutch/hostdb/ResolverThread.java b/src/java/org/apache/nutch/hostdb/ResolverThread.java
index c0a4f124b..2140ea52d 100644
--- a/src/java/org/apache/nutch/hostdb/ResolverThread.java
+++ b/src/java/org/apache/nutch/hostdb/ResolverThread.java
@@ -74,16 +74,16 @@ public class ResolverThread implements Runnable {
if (datum.isEmpty()) {
context.getCounter("UpdateHostDb", "new_known_host").increment(1);
datum.setLastCheck();
- LOG.info(host + ": new_known_host " + datum);
+ LOG.info("{}: new_known_host {}", host, datum);
} else if (datum.getDnsFailures() > 0) {
context.getCounter("UpdateHostDb", "rediscovered_host").increment(1);
datum.setLastCheck();
datum.setDnsFailures(0l);
- LOG.info(host + ": rediscovered_host " + datum);
+ LOG.info("{}: rediscovered_host {}", host, datum);
} else {
context.getCounter("UpdateHostDb", "existing_known_host").increment(1);
datum.setLastCheck();
- LOG.info(host + ": existing_known_host " + datum);
+ LOG.info("{}: existing_known_host {}", host, datum);
}
// Write the host datum
@@ -96,7 +96,7 @@ public class ResolverThread implements Runnable {
datum.setDnsFailures(1l);
context.write(hostText, datum);
context.getCounter("UpdateHostDb", "new_unknown_host").increment(1);
- LOG.info(host + ": new_unknown_host " + datum);
+ LOG.info("{}: new_unknown_host {}", host, datum);
} else {
datum.setLastCheck();
datum.incDnsFailures();
@@ -107,10 +107,10 @@ public class ResolverThread implements Runnable {
context.write(hostText, datum);
context.getCounter("UpdateHostDb", "existing_unknown_host").increment(1);
- LOG.info(host + ": existing_unknown_host " + datum);
+ LOG.info("{}: existing_unknown_host {}", host, datum);
} else {
context.getCounter("UpdateHostDb", "purged_unknown_host").increment(1);
- LOG.info(host + ": purged_unknown_host " + datum);
+ LOG.info("{}: purged_unknown_host {}", host, datum);
}
}
diff --git a/src/java/org/apache/nutch/hostdb/UpdateHostDb.java b/src/java/org/apache/nutch/hostdb/UpdateHostDb.java
index c8b8c43cf..a3115c4f1 100644
--- a/src/java/org/apache/nutch/hostdb/UpdateHostDb.java
+++ b/src/java/org/apache/nutch/hostdb/UpdateHostDb.java
@@ -32,7 +32,6 @@ import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDb;
@@ -184,17 +183,17 @@ public class UpdateHostDb extends Configured implements Tool {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-hostdb")) {
hostDb = new Path(args[i + 1]);
- LOG.info("UpdateHostDb: hostdb: " + hostDb);
+ LOG.info("UpdateHostDb: hostdb: {}", hostDb);
i++;
}
if (args[i].equals("-crawldb")) {
crawlDb = new Path(args[i + 1]);
- LOG.info("UpdateHostDb: crawldb: " + crawlDb);
+ LOG.info("UpdateHostDb: crawldb: {}", crawlDb);
i++;
}
if (args[i].equals("-tophosts")) {
topHosts = new Path(args[i + 1]);
- LOG.info("UpdateHostDb: tophosts: " + topHosts);
+ LOG.info("UpdateHostDb: tophosts: {}", topHosts);
i++;
}
@@ -230,7 +229,7 @@ public class UpdateHostDb extends Configured implements Tool {
}
if (args[i].equals("-urlLimit")) {
urlLimit = Long.valueOf(args[i + 1]);
- LOG.info("UpdateHostDb: URL limit set to " + urlLimit);
+ LOG.info("UpdateHostDb: URL limit set to {}", urlLimit);
i++;
}
}
@@ -246,7 +245,7 @@ public class UpdateHostDb extends Configured implements Tool {
return 0;
} catch (Exception e) {
- LOG.error("UpdateHostDb: " + StringUtils.stringifyException(e));
+ LOG.error("UpdateHostDb:", e);
return -1;
}
}
diff --git a/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java b/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java
index 2c13756ab..1431b5636 100644
--- a/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java
+++ b/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java
@@ -115,9 +115,9 @@ public class UpdateHostDbReducer
// Add to array
crawlDatumProcessors[i] = processorImpl;
} catch (Exception e) {
- LOG.error("Unable to instantiate crawldatum processor: "
- + crawlDatumProcessorClassnames[i] + " because: "
- + e.getMessage(), e);
+ LOG.error(
+ "Unable to instantiate crawldatum processor: {} because: {}",
+ crawlDatumProcessorClassnames[i], e.getMessage(), e);
}
}
}
@@ -223,7 +223,7 @@ public class UpdateHostDbReducer
try {
metadataValue = buffer.getMetaData().get(stringFieldWritables[i]).toString();
} catch (Exception e) {
- LOG.error("Metadata field " + stringFields[i] + " is probably not a numeric value");
+ LOG.error("Metadata field {} is probably not a numeric value", stringFields[i]);
}
// Does the value exist?
@@ -395,7 +395,7 @@ public class UpdateHostDbReducer
try {
queue.put(resolverThread);
} catch (InterruptedException e) {
- LOG.error("UpdateHostDb: " + StringUtils.stringifyException(e));
+ LOG.error("UpdateHostDb:", e);
}
// Do not progress, the datum will be written in the resolver thread
diff --git a/src/java/org/apache/nutch/indexer/CleaningJob.java b/src/java/org/apache/nutch/indexer/CleaningJob.java
index 8334ac353..cedee8e34 100644
--- a/src/java/org/apache/nutch/indexer/CleaningJob.java
+++ b/src/java/org/apache/nutch/indexer/CleaningJob.java
@@ -102,12 +102,6 @@ public class CleaningJob implements Tool {
@Override
public void cleanup(Context context) throws IOException {
- // BUFFERING OF CALLS TO INDEXER SHOULD BE HANDLED AT INDEXER LEVEL
- // if (numDeletes > 0) {
- // LOG.info("CleaningJob: deleting " + numDeletes + " documents");
- // // TODO updateRequest.process(solr);
- // totalDeleted += numDeletes;
- // }
if (totalDeleted > 0 && !noCommit) {
writers.commit();
@@ -115,7 +109,7 @@ public class CleaningJob implements Tool {
writers.close();
- LOG.info("CleaningJob: deleted a total of " + totalDeleted + " documents");
+ LOG.info("CleaningJob: deleted a total of {} documents", totalDeleted);
}
@Override
@@ -125,15 +119,6 @@ public class CleaningJob implements Tool {
writers.delete(document.toString());
totalDeleted++;
context.getCounter("CleaningJobStatus", "Deleted documents").increment(1);
- // if (numDeletes >= NUM_MAX_DELETE_REQUEST) {
- // LOG.info("CleaningJob: deleting " + numDeletes
- // + " documents");
- // // TODO updateRequest.process(solr);
- // // TODO updateRequest = new UpdateRequest();
- // writers.delete(key.toString());
- // totalDeleted += numDeletes;
- // numDeletes = 0;
- // }
}
}
}
@@ -180,8 +165,7 @@ public class CleaningJob implements Tool {
public int run(String[] args) throws IOException {
if (args.length < 1) {
String usage = "Usage: CleaningJob <crawldb> [-noCommit]";
- LOG.error("Missing crawldb. " + usage);
- System.err.println(usage);
+ LOG.error("Missing crawldb.\n{}", usage);
return 1;
}
@@ -193,9 +177,7 @@ public class CleaningJob implements Tool {
try {
delete(args[0], noCommit);
} catch (final Exception e) {
- LOG.error("CleaningJob: " + StringUtils.stringifyException(e));
- System.err.println("ERROR CleaningJob: "
- + StringUtils.stringifyException(e));
+ LOG.error("CleaningJob:", e);
return -1;
}
return 0;
diff --git a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java b/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
index 1b8ff52eb..9fb800771 100644
--- a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
+++ b/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
@@ -389,9 +389,7 @@ public class IndexerMapReduce extends Configured {
// run indexing filters
doc = filters.filter(doc, parse, key, fetchDatum, inlinks);
} catch (final IndexingException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Error indexing " + key + ": ", e);
- }
+ LOG.warn("Error indexing {}: ", key, e);
context.getCounter("IndexerStatus", "errors (IndexingFilter)").increment(1);
return;
}
diff --git a/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java b/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
index 1931c360d..f985dc9a7 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
@@ -146,7 +146,7 @@ public class IndexingFiltersChecker extends AbstractChecker {
url = normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT);
}
- LOG.info("fetching: " + url);
+ LOG.info("fetching: {}", url);
CrawlDatum datum = new CrawlDatum();
@@ -255,10 +255,10 @@ public class IndexingFiltersChecker extends AbstractChecker {
LOG.error("Failed to get parse from parse result");
LOG.error("Available parses in parse result (by URL key):");
for (Map.Entry<Text, Parse> entry : parseResult) {
- LOG.error(" " + entry.getKey());
+ LOG.error(" {}", entry.getKey());
}
LOG.error("Parse result does not contain a parse for URL to be checked:");
- LOG.error(" " + urlText);
+ LOG.error(" {}", urlText);
return -1;
}
diff --git a/src/java/org/apache/nutch/net/URLNormalizers.java b/src/java/org/apache/nutch/net/URLNormalizers.java
index bf947f7f6..a3a4b1bf5 100644
--- a/src/java/org/apache/nutch/net/URLNormalizers.java
+++ b/src/java/org/apache/nutch/net/URLNormalizers.java
@@ -198,12 +198,10 @@ public final class URLNormalizers {
}
normalizers.add(normalizer);
} catch (PluginRuntimeException e) {
- e.printStackTrace();
LOG.warn("URLNormalizers:PluginRuntimeException when "
- + "initializing url normalizer plugin "
- + ext.getDescriptor().getPluginId()
- + " instance in getURLNormalizers "
- + "function: attempting to continue instantiating plugins");
+ + "initializing URLNormalizer plugin {} instance in getURLNormalizers "
+ + "function: attempting to continue instantiating plugins",
+ ext.getDescriptor().getPluginId(), e);
}
}
return normalizers.toArray(new URLNormalizer[normalizers.size()]);
diff --git a/src/java/org/apache/nutch/parse/OutlinkExtractor.java b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
index 3e85025a2..1f90948af 100644
--- a/src/java/org/apache/nutch/parse/OutlinkExtractor.java
+++ b/src/java/org/apache/nutch/parse/OutlinkExtractor.java
@@ -101,9 +101,7 @@ public class OutlinkExtractor {
// (SHOULD really check cpu time used so that heavily loaded systems
// do not unnecessarily hit this limit.)
if (System.currentTimeMillis() - start >= 60000L) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Time limit exceeded for getOutLinks");
- }
+ LOG.warn("Time limit exceeded for getOutLinks");
break;
}
@@ -112,15 +110,13 @@ public class OutlinkExtractor {
try {
outlinks.add(new Outlink(url, anchor));
} catch (MalformedURLException mue) {
- LOG.warn("Invalid url: '" + url + "', skipping.");
+ LOG.warn("Invalid url: '{}', skipping.", url);
}
}
} catch (Exception ex) {
// if the matcher fails (perhaps a malformed URL) we just log it and move
// on
- if (LOG.isErrorEnabled()) {
- LOG.error("getOutlinks", ex);
- }
+ LOG.error("getOutlinks", ex);
}
final Outlink[] retval;
diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
index 27ece06c1..295c5e853 100644
--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java
+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
@@ -330,8 +330,8 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
try {
scfilters.initialScore(targetUrl, target);
} catch (ScoringFilterException e) {
- LOG.warn("Cannot filter init score for url " + key
- + ", using default: " + e.getMessage());
+ LOG.warn("Cannot filter init score for url {}, using default: {}",
+ key, e.getMessage());
target.setScore(0.0f);
}
@@ -348,8 +348,7 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
adjust = scfilters.distributeScoreToOutlinks(key, parseData, targets,
null, links.length);
} catch (ScoringFilterException e) {
- LOG.warn("Cannot distribute score from " + key + ": "
- + e.getMessage());
+ LOG.warn("Cannot distribute score from {}: {}", key, e.getMessage());
}
for (Entry<Text, CrawlDatum> target : targets) {
crawlOut.append(target.getKey(), target.getValue());
@@ -370,7 +369,7 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
try {
datum.setFetchTime(Long.parseLong(timeString));
} catch (Exception e) {
- LOG.warn("Can't read fetch time for: " + key);
+ LOG.warn("Can't read fetch time for: {}", key);
datum.setFetchTime(System.currentTimeMillis());
}
crawlOut.append(key, datum);
diff --git a/src/java/org/apache/nutch/parse/ParsePluginsReader.java b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
index 4420111ac..978e3c097 100644
--- a/src/java/org/apache/nutch/parse/ParsePluginsReader.java
+++ b/src/java/org/apache/nutch/parse/ParsePluginsReader.java
@@ -90,10 +90,9 @@ class ParsePluginsReader {
parsePluginUrl = new URL(fParsePluginsFile);
ppInputStream = parsePluginUrl.openStream();
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to load parse plugins file from URL " + "["
- + fParsePluginsFile + "]. Reason is [" + e + "]");
- }
+ LOG.warn(
+ "Unable to load parse plugins file from URL [{}]. Reason is [{}]",
+ fParsePluginsFile, e);
return pList;
}
} else {
@@ -107,10 +106,7 @@ class ParsePluginsReader {
parser = factory.newDocumentBuilder();
document = parser.parse(inputSource);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to parse [" + fParsePluginsFile + "]." + "Reason is ["
- + e + "]");
- }
+ LOG.warn("Unable to parse [{}]. Reason is [{}]", fParsePluginsFile, e);
return null;
}
@@ -163,9 +159,9 @@ class ParsePluginsReader {
// now add the plugin list and map it to this mimeType
pList.setPluginList(mimeTypeStr, plugList);
- } else if (LOG.isWarnEnabled()) {
- LOG.warn("ParsePluginsReader:ERROR:no plugins defined for mime type: "
- + mimeTypeStr + ", continuing parse");
+ } else {
+ LOG.warn("No plugins defined for mime type: {}, continuing parse",
+ mimeTypeStr);
}
}
return pList;
@@ -239,17 +235,13 @@ class ParsePluginsReader {
NodeList aliasRoot = parsePluginsRoot.getElementsByTagName("aliases");
if (aliasRoot == null || aliasRoot.getLength() == 0) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("No aliases defined in parse-plugins.xml!");
- }
+ LOG.warn("No aliases defined in parse-plugins.xml!");
return aliases;
}
if (aliasRoot.getLength() > 1) {
// log a warning, but try and continue processing
- if (LOG.isWarnEnabled()) {
- LOG.warn("There should only be one \"aliases\" tag in parse-plugins.xml");
- }
+ LOG.warn("There should only be one \"aliases\" tag in parse-plugins.xml");
}
Element aliasRootElem = (Element) aliasRoot.item(0);
@@ -260,10 +252,8 @@ class ParsePluginsReader {
Element aliasElem = (Element) aliasElements.item(i);
String parsePluginId = aliasElem.getAttribute("name");
String extensionId = aliasElem.getAttribute("extension-id");
- if (LOG.isTraceEnabled()) {
- LOG.trace("Found alias: plugin-id: " + parsePluginId
- + ", extension-id: " + extensionId);
- }
+ LOG.trace("Found alias: plugin-id: {}, extension-id: {}", parsePluginId,
+ extensionId);
if (parsePluginId != null && extensionId != null) {
aliases.put(parsePluginId, extensionId);
}
diff --git a/src/java/org/apache/nutch/parse/ParseResult.java b/src/java/org/apache/nutch/parse/ParseResult.java
index 30370516b..4a4dbf362 100644
--- a/src/java/org/apache/nutch/parse/ParseResult.java
+++ b/src/java/org/apache/nutch/parse/ParseResult.java
@@ -158,7 +158,7 @@ public class ParseResult implements Iterable<Map.Entry<Text, Parse>> {
for (Iterator<Entry<Text, Parse>> i = iterator(); i.hasNext();) {
Entry<Text, Parse> entry = i.next();
if (!entry.getValue().getData().getStatus().isSuccess()) {
- LOG.warn(entry.getKey() + " is not parsed successfully, filtering");
+ LOG.warn("{} is not parsed successfully, filtering", entry.getKey());
i.remove();
}
}
diff --git a/src/java/org/apache/nutch/parse/ParseSegment.java b/src/java/org/apache/nutch/parse/ParseSegment.java
index e9f041a5f..6b2fb5cee 100644
--- a/src/java/org/apache/nutch/parse/ParseSegment.java
+++ b/src/java/org/apache/nutch/parse/ParseSegment.java
@@ -120,8 +120,7 @@ public class ParseSegment extends NutchTool implements Tool {
parseUtil = new ParseUtil(context.getConfiguration());
parseResult = parseUtil.parse(content);
} catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": "
- + StringUtils.stringifyException(e));
+ LOG.warn("Error parsing: {}: {}", key, StringUtils.stringifyException(e));
return;
}
@@ -134,7 +133,7 @@ public class ParseSegment extends NutchTool implements Tool {
ParseStatus.majorCodes[parseStatus.getMajorCode()]).increment(1);
if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
+ LOG.warn("Error parsing: {}: {}", key, parseStatus);
parse = parseStatus.getEmptyParse(context.getConfiguration());
}
@@ -184,8 +183,9 @@ public class ParseSegment extends NutchTool implements Tool {
//if the flag is there, no matter the value, trust it.
if (metadata.get(Response.TRUNCATED_CONTENT) != null) {
if ("true".equals(metadata.get(Response.TRUNCATED_CONTENT))) {
- LOG.info(content.getUrl() + " skipped. Protocol metadata indicates truncated content, " +
- "actualSize= " + content.getContent().length);
+ LOG.info(
+ "{} skipped. Protocol metadata indicates truncated content, actualSize= {}",
+ content.getUrl(), content.getContent().length);
return true;
}
return false;
@@ -202,19 +202,15 @@ public class ParseSegment extends NutchTool implements Tool {
try {
inHeaderSize = Integer.parseInt(lengthStr);
} catch (NumberFormatException e) {
- LOG.warn("Wrong contentlength format for " + url, e);
+ LOG.warn("Wrong contentlength format for {}", url, e);
return false;
}
int actualSize = contentBytes.length;
if (inHeaderSize > actualSize) {
- LOG.info(url + " skipped. Content of size " + inHeaderSize
- + " was truncated to " + actualSize);
+ LOG.info("{} skipped. Content of size {} was truncated to {}", url, inHeaderSize, actualSize);
return true;
}
- if (LOG.isDebugEnabled()) {
- LOG.debug(url + " actualSize=" + actualSize + " inHeaderSize="
- + inHeaderSize);
- }
+ LOG.debug("{} actualSize={} inHeaderSize={}", url, actualSize, inHeaderSize);
return false;
}
@@ -233,8 +229,7 @@ public class ParseSegment extends NutchTool implements Tool {
public void parse(Path segment) throws IOException,
InterruptedException, ClassNotFoundException {
if (SegmentChecker.isParsed(segment, segment.getFileSystem(getConf()))) {
- LOG.warn("Segment: " + segment
- + " already parsed!! Skipped parsing this segment!!"); // NUTCH-1854
+ LOG.warn("Segment: {} already parsed!! Skipped parsing this segment!!", segment); // NUTCH-1854
return;
}
diff --git a/src/java/org/apache/nutch/parse/ParseUtil.java b/src/java/org/apache/nutch/parse/ParseUtil.java
index 933ef83c1..c974a1054 100644
--- a/src/java/org/apache/nutch/parse/ParseUtil.java
+++ b/src/java/org/apache/nutch/parse/ParseUtil.java
@@ -75,27 +75,23 @@ public class ParseUtil {
parsers = this.parserFactory.getParsers(content.getContentType(),
content.getUrl() != null ? content.getUrl() : "");
} catch (ParserNotFound e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("No suitable parser found when trying to parse content "
- + content.getUrl() + " of type " + content.getContentType());
- }
+ LOG.warn(
+ "No suitable parser found when trying to parse content {} of type {}",
+ content.getUrl(), content.getContentType());
throw new ParseException(e.getMessage());
}
ParseResult parseResult = null;
for (int i = 0; i < parsers.length; i++) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Parsing [" + content.getUrl() + "] with [" + parsers[i]
- + "]");
- }
+ LOG.debug("Parsing [{}] with [{}]", content.getUrl(), parsers[i]);
if (maxParseTime != -1) {
parseResult = runParser(parsers[i], content);
} else {
try {
parseResult = parsers[i].getParse(content);
} catch (Throwable e) {
- LOG.warn("Error parsing " + content.getUrl() + " with "
- + parsers[i].getClass().getName(), e);
+ LOG.warn("Error parsing {} with {}", content.getUrl(),
+ parsers[i].getClass().getName(), e);
}
}
@@ -111,10 +107,9 @@ public class ParseUtil {
return parseResult;
}
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to successfully parse content " + content.getUrl()
- + " of type " + content.getContentType());
- }
+ LOG.warn("Unable to successfully parse content {} of type {}",
+ content.getUrl(), content.getContentType());
+
return new ParseStatus(new ParseException(
"Unable to successfully parse content")).getEmptyParseResult(
content.getUrl(), null);
@@ -149,10 +144,9 @@ public class ParseUtil {
try {
p = this.parserFactory.getParserById(extId);
} catch (ParserNotFound e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("No suitable parser found when trying to parse content "
- + content.getUrl() + " of type " + content.getContentType());
- }
+ LOG.warn(
+ "No suitable parser found when trying to parse content {} of type {}",
+ content.getUrl(), content.getContentType());
throw new ParseException(e.getMessage());
}
@@ -163,17 +157,15 @@ public class ParseUtil {
try {
parseResult = p.getParse(content);
} catch (Throwable e) {
- LOG.warn("Error parsing " + content.getUrl() + " with "
- + p.getClass().getName(), e);
+ LOG.warn("Error parsing {} with {}", content.getUrl(),
+ p.getClass().getName(), e);
}
}
if (parseResult != null && !parseResult.isEmpty()) {
return parseResult;
} else {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unable to successfully parse content " + content.getUrl()
- + " of type " + content.getContentType());
- }
+ LOG.warn("Unable to successfully parse content {} of type {}",
+ content.getUrl(), content.getContentType());
return new ParseStatus(new ParseException(
"Unable to successfully parse content")).getEmptyParseResult(
content.getUrl(), null);
@@ -187,8 +179,8 @@ public class ParseUtil {
try {
res = task.get(maxParseTime, TimeUnit.SECONDS);
} catch (Exception e) {
- LOG.warn("Error parsing " + content.getUrl() + " with "
- + p.getClass().getName(), e);
+ LOG.warn("Error parsing {} with {}", content.getUrl(),
+ p.getClass().getName(), e);
task.cancel(true);
} finally {
pc = null;
diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.java
index 10eec4b24..b65d475d8 100644
--- a/src/java/org/apache/nutch/parse/ParserChecker.java
+++ b/src/java/org/apache/nutch/parse/ParserChecker.java
@@ -160,7 +160,7 @@ public class ParserChecker extends AbstractChecker {
url = this.normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT);
}
- LOG.info("fetching: " + url);
+ LOG.info("fetching: {}", url);
CrawlDatum datum = new CrawlDatum();
@@ -256,11 +256,8 @@ public class ParserChecker extends AbstractChecker {
try {
this.scfilters.passScoreBeforeParsing(turl, datum, content);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score before parsing, url " + turl + " (" + e
- + ")");
- LOG.warn(StringUtils.stringifyException(e));
- }
+ LOG.warn("Couldn't pass score before parsing, url {} ({})", turl, e);
+ LOG.warn(StringUtils.stringifyException(e));
}
ParseResult parseResult = new ParseUtil(getConf()).parse(content);
@@ -274,11 +271,9 @@ public class ParserChecker extends AbstractChecker {
byte[] signature = SignatureFactory.getSignature(getConf()).calculate(
content, parseResult.get(new Text(url)));
- if (LOG.isInfoEnabled()) {
- LOG.info("parsing: {}", url);
- LOG.info("contentType: {}", contentType);
- LOG.info("signature: {}", StringUtil.toHexString(signature));
- }
+ LOG.info("parsing: {}", url);
+ LOG.info("contentType: {}", contentType);
+ LOG.info("signature: {}", StringUtil.toHexString(signature));
for (Map.Entry<Text, Parse> entry : parseResult) {
turl = entry.getKey();
@@ -287,11 +282,8 @@ public class ParserChecker extends AbstractChecker {
try {
this.scfilters.passScoreAfterParsing(turl, content, parse);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score after parsing, url " + turl + " (" + e
- + ")");
- LOG.warn(StringUtils.stringifyException(e));
- }
+ LOG.warn("Couldn't pass score after parsing, url {} ({})", turl, e);
+ LOG.warn(StringUtils.stringifyException(e));
}
output.append(turl).append("\n");
diff --git a/src/java/org/apache/nutch/parse/ParserFactory.java b/src/java/org/apache/nutch/parse/ParserFactory.java
index 6c0b569f4..e089679fa 100644
--- a/src/java/org/apache/nutch/parse/ParserFactory.java
+++ b/src/java/org/apache/nutch/parse/ParserFactory.java
@@ -138,15 +138,9 @@ public final class ParserFactory {
}
parsers.add(p);
} catch (PluginRuntimeException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn(
- "ParserFactory:PluginRuntimeException when "
- + "initializing parser plugin "
- + ext.getDescriptor().getPluginId()
- + " instance because: " + e.getMessage()
- + " - attempting to continue instantiating parsers",
- e);
- }
+ LOG.warn("ParserFactory:PluginRuntimeException when "
+ + "initializing parser plugin {} instance because: {} - attempting to continue instantiating parsers",
+ ext.getDescriptor().getPluginId(), e.getMessage(), e);
}
}
return parsers.toArray(new Parser[] {});
@@ -203,11 +197,8 @@ public final class ParserFactory {
objectCache.setObject(parserExt.getId(), p);
return p;
} catch (PluginRuntimeException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Canno initialize parser "
- + parserExt.getDescriptor().getPluginId() + " (cause: "
- + e.toString());
- }
+ LOG.warn("Cannot initialize parser {} (cause: {})",
+ parserExt.getDescriptor().getPluginId(), e.toString());
throw new ParserNotFound("Cannot init parser for id [" + id + "]");
}
}
@@ -319,23 +310,21 @@ public final class ParserFactory {
// try to get it just by its pluginId
ext = getExtension(extensions, parsePluginId);
- if (LOG.isWarnEnabled()) {
- if (ext != null) {
- // plugin was enabled via plugin.includes
- // its plugin.xml just doesn't claim to support that
- // particular mimeType
- LOG.warn("ParserFactory:Plugin: " + parsePluginId
- + " mapped to contentType " + contentType
- + " via parse-plugins.xml, but " + "its plugin.xml "
- + "file does not claim to support contentType: "
- + contentType);
- } else {
- // plugin wasn't enabled via plugin.includes
- LOG.warn("ParserFactory: Plugin: " + parsePluginId
- + " mapped to contentType " + contentType
- + " via parse-plugins.xml, but not enabled via "
- + "plugin.includes in nutch-default.xml");
- }
+ if (ext != null) {
+ /*
+ * plugin was enabled via plugin.includes its plugin.xml just
+ * doesn't claim to support that particular mimeType
+ */
+ LOG.warn(
+ "ParserFactory:Plugin: {} mapped to contentType {} via parse-plugins.xml, "
+ + "but its plugin.xml file does not claim to support contentType: {}",
+ parsePluginId, contentType, contentType);
+ } else {
+ // plugin wasn't enabled via plugin.includes
+ LOG.warn(
+ "ParserFactory: Plugin: {} mapped to contentType {} via parse-plugins.xml, "
+ + "but not enabled via plugin.includes in nutch-default.xml",
+ parsePluginId, contentType);
}
}
@@ -366,7 +355,7 @@ public final class ParserFactory {
if (extList.size() > 0) {
if (LOG.isInfoEnabled()) {
- StringBuffer extensionsIDs = new StringBuffer("[");
+ StringBuilder extensionsIDs = new StringBuilder("[");
boolean isFirst = true;
for (Extension ext : extList) {
if (!isFirst)
@@ -376,15 +365,16 @@ public final class ParserFactory {
extensionsIDs.append(ext.getId());
}
extensionsIDs.append("]");
- LOG.info("The parsing plugins: " + extensionsIDs.toString()
- + " are enabled via the plugin.includes system "
- + "property, and all claim to support the content type "
- + contentType + ", but they are not mapped to it in the "
- + "parse-plugins.xml file");
+ LOG.info(
+ "The parsing plugins: {} are enabled via the plugin.includes system "
+ + "property, and all claim to support the content type {}, "
+ + "but they are not mapped to it in the parse-plugins.xml file",
+ extensionsIDs.toString(), contentType);
}
- } else if (LOG.isDebugEnabled()) {
- LOG.debug("ParserFactory:No parse plugins mapped or enabled for "
- + "contentType " + contentType);
+ } else {
+ LOG.debug(
+ "ParserFactory: No parse plugins mapped or enabled for contentType {}",
+ contentType);
}
}
diff --git a/src/java/org/apache/nutch/plugin/PluginDescriptor.java b/src/java/org/apache/nutch/plugin/PluginDescriptor.java
index b22409af4..7a93c863e 100644
--- a/src/java/org/apache/nutch/plugin/PluginDescriptor.java
+++ b/src/java/org/apache/nutch/plugin/PluginDescriptor.java
@@ -303,7 +303,7 @@ public class PluginDescriptor {
arrayList.add(file2.getParentFile().toURI().toURL());
}
} catch (MalformedURLException e) {
- LOG.debug(getPluginId() + " " + e.toString());
+ LOG.debug("{} {}", getPluginId(), e.toString());
}
URL[] urls = arrayList.toArray(new URL[arrayList.size()]);
fClassLoader = new PluginClassLoader(urls,
diff --git a/src/java/org/apache/nutch/plugin/PluginManifestParser.java b/src/java/org/apache/nutch/plugin/PluginManifestParser.java
index ccae5827d..10ce4fdb7 100644
--- a/src/java/org/apache/nutch/plugin/PluginManifestParser.java
+++ b/src/java/org/apache/nutch/plugin/PluginManifestParser.java
@@ -283,7 +283,7 @@ public class PluginManifestParser {
Element oneImplementation = (Element) node;
String id = oneImplementation.getAttribute(ATTR_ID);
String extensionClass = oneImplementation.getAttribute(ATTR_CLASS);
- LOG.debug("impl: point=" + pointId + " class=" + extensionClass);
+ LOG.debug("impl: point={} class={}", pointId, extensionClass);
Extension extension = new Extension(pPluginDescriptor, pointId, id,
extensionClass, this.conf, this.pluginRepository);
NodeList parameters = oneImplementation
diff --git a/src/java/org/apache/nutch/plugin/PluginRepository.java b/src/java/org/apache/nutch/plugin/PluginRepository.java
index fef984bf3..dbe8fb68d 100644
--- a/src/java/org/apache/nutch/plugin/PluginRepository.java
+++ b/src/java/org/apache/nutch/plugin/PluginRepository.java
@@ -478,10 +478,8 @@ public class PluginRepository implements URLStreamHandlerFactory {
Object[] filter = (Object[]) Array.newInstance(clazz, sorted.size());
for (int i = 0; i < sorted.size(); i++) {
filter[i] = sorted.get(i);
- if (LOG.isTraceEnabled()) {
- LOG.trace("{} : filters[{}] = {}", clazz.getSimpleName() , i,
- filter[i].getClass());
- }
+ LOG.trace("{} : filters[{}] = {}", clazz.getSimpleName(), i,
+ filter[i].getClass());
}
objectCache.setObject(clazz.getName(), filter);
} catch (PluginRuntimeException e) {
diff --git a/src/java/org/apache/nutch/protocol/RobotRulesParser.java b/src/java/org/apache/nutch/protocol/RobotRulesParser.java
index d73c07506..c5e267ef6 100644
--- a/src/java/org/apache/nutch/protocol/RobotRulesParser.java
+++ b/src/java/org/apache/nutch/protocol/RobotRulesParser.java
@@ -169,7 +169,7 @@ public abstract class RobotRulesParser implements Tool {
if (allowList.size() > 0) {
matcher = new SuffixStringMatcher(allowList);
- LOG.info("Allowlisted hosts: " + allowList);
+ LOG.info("Allowlisted hosts: {}", allowList);
}
}
}
@@ -421,7 +421,7 @@ public abstract class RobotRulesParser implements Tool {
}
testsIn.close();
} catch (IOException e) {
- LOG.error("Failed to run: " + StringUtils.stringifyException(e));
+ LOG.error("Failed to run:", e);
return -1;
}
@@ -480,8 +480,7 @@ public abstract class RobotRulesParser implements Tool {
rules = robotParser.parseContent(url.toString(), robotsBytes,
"text/plain", agentNames);
} catch (IOException e) {
- LOG.error("Failed to open robots.txt file " + url
- + StringUtils.stringifyException(e));
+ LOG.error("Failed to open robots.txt file {}:", url, e);
rules = EMPTY_RULES;
}
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java b/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
index 439d7438c..52211dcde 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
@@ -53,7 +53,6 @@ import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.util.FSUtils;
@@ -74,7 +73,7 @@ public class LinkDumper extends Configured implements Tool {
/**
* Reader class which will print out the url and all of its inlinks to system
- * out. Each inlinkwill be displayed with its node information including score
+ * out. Each inlink will be displayed with its node information including score
* and number of in and outlinks.
*/
public static class Reader {
@@ -443,7 +442,7 @@ public class LinkDumper extends Configured implements Tool {
dumpLinks(new Path(webGraphDb));
return 0;
} catch (Exception e) {
- LOG.error("LinkDumper: " + StringUtils.stringifyException(e));
+ LOG.error("LinkDumper:", e);
return -2;
}
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
index e48f04acd..3cafb6674 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
@@ -60,7 +60,6 @@ import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.util.FSUtils;
@@ -471,7 +470,7 @@ public class LinkRank extends Configured implements Tool {
int numOutlinks = node.getNumOutlinks();
float inlinkScore = node.getInlinkScore();
float outlinkScore = node.getOutlinkScore();
- LOG.debug(fromUrl + ": num outlinks " + numOutlinks);
+ LOG.debug("{}: num outlinks {}", fromUrl, numOutlinks);
// can't invert if no outlinks
if (numOutlinks > 0) {
@@ -484,9 +483,9 @@ public class LinkRank extends Configured implements Tool {
// collect the inverted outlink
context.write(new Text(toUrl), outlink);
- LOG.debug(toUrl + ": inverting inlink from " + fromUrl
- + " origscore: " + inlinkScore + " numOutlinks: " + numOutlinks
- + " inlinkscore: " + outlinkScore);
+ LOG.debug(
+ "{}: inverting inlink from {} origscore: {} numOutlinks: {} inlinkscore: {}",
+ toUrl, fromUrl, inlinkScore, numOutlinks, outlinkScore);
}
}
}
@@ -585,8 +584,8 @@ public class LinkRank extends Configured implements Tool {
// limit counting duplicate inlinks by pages or domains
if ((limitPages && pages.contains(inLinkPage))
|| (limitDomains && domains.contains(inLinkDomain))) {
- LOG.debug(url + ": ignoring " + scoreFromInlink + " from "
- + inlinkUrl + ", duplicate page or domain");
+ LOG.debug("{}: ignoring {} from {}, duplicate page or domain",
+ url, scoreFromInlink, inlinkUrl);
continue;
}
@@ -595,8 +594,8 @@ public class LinkRank extends Configured implements Tool {
totalInlinkScore += scoreFromInlink;
domains.add(inLinkDomain);
pages.add(inLinkPage);
- LOG.debug(url + ": adding " + scoreFromInlink + " from " + inlinkUrl
- + ", total: " + totalInlinkScore);
+ LOG.debug("{}: adding {} from {}, total: {}", url, scoreFromInlink,
+ inlinkUrl, totalInlinkScore);
}
}
@@ -604,8 +603,8 @@ public class LinkRank extends Configured implements Tool {
float linkRankScore = (1 - dampingFactor)
+ (dampingFactor * totalInlinkScore);
- LOG.debug(url + ": score: " + linkRankScore + " num inlinks: "
- + numInlinks + " iteration: " + itNum);
+ LOG.debug("{}: score: {} num inlinks: {} iteration: {}", url,
+ linkRankScore, numInlinks, itNum);
// store the score in a temporary NodeDb
Node outNode = WritableUtils.clone(node, conf);
@@ -674,10 +673,8 @@ public class LinkRank extends Configured implements Tool {
runInitializer(wgNodeDb, nodeDb);
float rankOneScore = (1f / (float) numLinks);
- if (LOG.isInfoEnabled()) {
- LOG.info("Analysis: Number of links: " + numLinks);
- LOG.info("Analysis: Rank One: " + rankOneScore);
- }
+ LOG.info("Analysis: Number of links: {}", numLinks);
+ LOG.info("Analysis: Rank One: {}", rankOneScore);
// run invert and analysis for a given number of iterations to allow the
// link rank scores to converge
@@ -685,8 +682,7 @@ public class LinkRank extends Configured implements Tool {
for (int i = 0; i < numIterations; i++) {
// the input to inverting is always the previous output from analysis
- LOG.info("Analysis: Starting iteration " + (i + 1) + " of "
- + numIterations);
+ LOG.info("Analysis: Starting iteration {} of {}", (i + 1), numIterations);
Path tempRank = new Path(linkRank + "-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
fs.mkdirs(tempRank);
@@ -701,8 +697,7 @@ public class LinkRank extends Configured implements Tool {
// replace the temporary NodeDb with the output from analysis
LOG.info("Analysis: Installing new link scores");
FSUtils.replace(fs, linkRank, tempRank, true);
- LOG.info("Analysis: finished iteration " + (i + 1) + " of "
- + numIterations);
+ LOG.info("Analysis: finished iteration {} of {}", (i + 1), numIterations);
}
// replace the NodeDb in the WebGraph with the final output of analysis
@@ -754,7 +749,7 @@ public class LinkRank extends Configured implements Tool {
analyze(new Path(webGraphDb));
return 0;
} catch (Exception e) {
- LOG.error("LinkAnalysis: " + StringUtils.stringifyException(e));
+ LOG.error("LinkAnalysis:", e);
return -2;
}
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java b/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
index 9277df8f6..a8a8e7fa1 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
@@ -44,7 +44,6 @@ import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.util.NutchConfiguration;
@@ -468,7 +467,7 @@ public class NodeDumper extends Configured implements Tool {
nameType, aggrType, asSequenceFile);
return 0;
} catch (Exception e) {
- LOG.error("NodeDumper: " + StringUtils.stringifyException(e));
+ LOG.error("NodeDumper:", e);
return -2;
}
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java b/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
index bcd534274..a595d4bf3 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
@@ -45,7 +45,6 @@ import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDatum;
@@ -123,17 +122,17 @@ public class ScoreUpdater extends Configured implements Tool{
// set the inlink score in the nodedb
float inlinkScore = node.getInlinkScore();
datum.setScore(inlinkScore);
- LOG.debug(url + ": setting to score " + inlinkScore);
+ LOG.debug("{}: setting to score {}", url, inlinkScore);
} else {
// clear out the score in the crawldb
datum.setScore(clearScore);
- LOG.debug(url + ": setting to clear score of " + clearScore);
+ LOG.debug("{}: setting to clear score of {}", url, clearScore);
}
context.write(key, datum);
} else {
- LOG.debug(url + ": no datum");
+ LOG.debug("{}: no datum", url);
}
}
}
@@ -163,7 +162,7 @@ public class ScoreUpdater extends Configured implements Tool{
Configuration conf = getConf();
// create a temporary crawldb with the new scores
- LOG.info("Running crawldb update " + crawlDb);
+ LOG.info("Running crawldb update {}", crawlDb);
Path nodeDb = new Path(webGraphDb, WebGraph.NODE_DIR);
Path crawlDbCurrent = new Path(crawlDb, CrawlDb.CURRENT_NAME);
Path newCrawlDb = new Path(crawlDb, Integer.toString(new Random()
@@ -209,7 +208,7 @@ public class ScoreUpdater extends Configured implements Tool{
}
// install the temp crawl database
- LOG.info("ScoreUpdater: installing new crawldb " + crawlDb);
+ LOG.info("ScoreUpdater: installing new crawldb {}", crawlDb);
CrawlDb.install(updater, crawlDb);
stopWatch.stop();
@@ -263,7 +262,7 @@ public class ScoreUpdater extends Configured implements Tool{
update(new Path(crawlDb), new Path(webGraphDb));
return 0;
} catch (Exception e) {
- LOG.error("ScoreUpdater: " + StringUtils.stringifyException(e));
+ LOG.error("ScoreUpdater:", e);
return -1;
}
}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java b/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
index 25e3cf230..4daefcd8f 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
@@ -53,7 +53,6 @@ import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.NutchWritable;
@@ -186,7 +185,7 @@ public class WebGraph extends Configured implements Tool {
URLNormalizers.SCOPE_DEFAULT);
normalized = normalized.trim();
} catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
+ LOG.warn("Skipping {}:{}", url, e);
normalized = null;
}
}
@@ -521,9 +520,9 @@ public class WebGraph extends Configured implements Tool {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
LOG.info("WebGraphDb: starting");
- LOG.info("WebGraphDb: webgraphdb: " + webGraphDb);
- LOG.info("WebGraphDb: URL normalize: " + normalize);
- LOG.info("WebGraphDb: URL filter: " + filter);
+ LOG.info("WebGraphDb: webgraphdb: {}", webGraphDb);
+ LOG.info("WebGraphDb: URL normalize: {}", normalize);
+ LOG.info("WebGraphDb: URL filter: {}", filter);
FileSystem fs = webGraphDb.getFileSystem(getConf());
@@ -561,14 +560,14 @@ public class WebGraph extends Configured implements Tool {
FileSystem sfs = segments[i].getFileSystem(outlinkJobConf);
Path parseData = new Path(segments[i], ParseData.DIR_NAME);
if (sfs.exists(parseData)) {
- LOG.info("OutlinkDb: adding input: " + parseData);
+ LOG.info("OutlinkDb: adding input: {}", parseData);
FileInputFormat.addInputPath(outlinkJob, parseData);
}
if (deleteGone) {
Path crawlFetch = new Path(segments[i], CrawlDatum.FETCH_DIR_NAME);
if (sfs.exists(crawlFetch)) {
- LOG.info("OutlinkDb: adding input: " + crawlFetch);
+ LOG.info("OutlinkDb: adding input: {}", crawlFetch);
FileInputFormat.addInputPath(outlinkJob, crawlFetch);
}
}
@@ -576,7 +575,7 @@ public class WebGraph extends Configured implements Tool {
}
// add the existing webgraph
- LOG.info("OutlinkDb: adding input: " + outlinkDb);
+ LOG.info("OutlinkDb: adding input: {}", outlinkDb);
FileInputFormat.addInputPath(outlinkJob, outlinkDb);
outlinkJobConf.setBoolean(OutlinkDb.URL_NORMALIZING, normalize);
@@ -606,7 +605,7 @@ public class WebGraph extends Configured implements Tool {
NutchJob.cleanupAfterFailure(tempOutlinkDb, lock, fs);
throw new RuntimeException(message);
}
- LOG.info("OutlinkDb: installing " + outlinkDb);
+ LOG.info("OutlinkDb: installing {}", outlinkDb);
FSUtils.replace(fs, oldOutlinkDb, outlinkDb, true);
FSUtils.replace(fs, outlinkDb, tempOutlinkDb, true);
if (!preserveBackup && fs.exists(oldOutlinkDb))
@@ -626,7 +625,7 @@ public class WebGraph extends Configured implements Tool {
Job inlinkJob = Job.getInstance(getConf(), "Nutch WebGraph: inlinkdb " + inlinkDb);
Configuration inlinkJobConf = inlinkJob.getConfiguration();
- LOG.info("InlinkDb: adding input: " + outlinkDb);
+ LOG.info("InlinkDb: adding input: {}", outlinkDb);
FileInputFormat.addInputPath(inlinkJob, outlinkDb);
inlinkJob.setInputFormatClass(SequenceFileInputFormat.class);
inlinkJob.setJarByClass(InlinkDb.class);
@@ -652,7 +651,7 @@ public class WebGraph extends Configured implements Tool {
NutchJob.cleanupAfterFailure(tempInlinkDb, lock, fs);
throw new RuntimeException(message);
}
- LOG.info("InlinkDb: installing " + inlinkDb);
+ LOG.info("InlinkDb: installing {}", inlinkDb);
FSUtils.replace(fs, inlinkDb, tempInlinkDb, true);
LOG.info("InlinkDb: finished");
} catch (IOException | InterruptedException | ClassNotFoundException e) {
@@ -669,8 +668,8 @@ public class WebGraph extends Configured implements Tool {
Job nodeJob = Job.getInstance(getConf(), "Nutch WebGraph: nodedb " + nodeDb);
Configuration nodeJobConf = nodeJob.getConfiguration();
- LOG.info("NodeDb: adding input: " + outlinkDb);
- LOG.info("NodeDb: adding input: " + inlinkDb);
+ LOG.info("NodeDb: adding input: {}", outlinkDb);
+ LOG.info("NodeDb: adding input: {}", inlinkDb);
FileInputFormat.addInputPath(nodeJob, outlinkDb);
FileInputFormat.addInputPath(nodeJob, inlinkDb);
nodeJob.setInputFormatClass(SequenceFileInputFormat.class);
@@ -697,7 +696,7 @@ public class WebGraph extends Configured implements Tool {
NutchJob.cleanupAfterFailure(tempNodeDb, lock, fs);
throw new RuntimeException(message);
}
- LOG.info("NodeDb: installing " + nodeDb);
+ LOG.info("NodeDb: installing {}", nodeDb);
FSUtils.replace(fs, nodeDb, tempNodeDb, true);
LOG.info("NodeDb: finished");
} catch (IOException | InterruptedException | ClassNotFoundException e) {
@@ -804,7 +803,7 @@ public class WebGraph extends Configured implements Tool {
createWebGraph(new Path(webGraphDb), segPaths, normalize, filter);
return 0;
} catch (Exception e) {
- LOG.error("WebGraph: " + StringUtils.stringifyException(e));
+ LOG.error("WebGraph:", e);
return -2;
}
}
diff --git a/src/java/org/apache/nutch/segment/SegmentChecker.java b/src/java/org/apache/nutch/segment/SegmentChecker.java
index cf230c2b6..7b02197cf 100644
--- a/src/java/org/apache/nutch/segment/SegmentChecker.java
+++ b/src/java/org/apache/nutch/segment/SegmentChecker.java
@@ -107,7 +107,7 @@ public class SegmentChecker {
&& parseDataExists) {
// No segment dir missing
- LOG.info("Segment dir is complete: " + segmentPath.toString() + ".");
+ LOG.info("Segment dir is complete: {}.", segmentPath);
return true;
} else {
@@ -128,9 +128,8 @@ public class SegmentChecker {
}
String missingDirString = missingDir.toString();
- LOG.warn("Skipping segment: " + segmentPath.toString()
- + ". Missing sub directories: "
- + missingDirString.substring(0, missingDirString.length() - 2));
+ LOG.warn("Skipping segment: {}. Missing sub directories: {}", segmentPath,
+ missingDirString.substring(0, missingDirString.length() - 2));
return false;
}
diff --git a/src/java/org/apache/nutch/segment/SegmentMergeFilters.java b/src/java/org/apache/nutch/segment/SegmentMergeFilters.java
index 812622174..a75966e61 100644
--- a/src/java/org/apache/nutch/segment/SegmentMergeFilters.java
+++ b/src/java/org/apache/nutch/segment/SegmentMergeFilters.java
@@ -80,13 +80,11 @@ public class SegmentMergeFilters {
for (SegmentMergeFilter filter : filters) {
if (!filter.filter(key, generateData, fetchData, sigData, content,
parseData, parseText, linked)) {
- if (LOG.isTraceEnabled())
- LOG.trace("Key " + key + " dropped by " + filter.getClass().getName());
+ LOG.trace("Key {} dropped by {}", key, filter.getClass().getName());
return false;
}
}
- if (LOG.isTraceEnabled())
- LOG.trace("Key " + key + " accepted for merge.");
+ LOG.trace("Key {} accepted for merge.", key);
return true;
}
}
diff --git a/src/java/org/apache/nutch/segment/SegmentMerger.java b/src/java/org/apache/nutch/segment/SegmentMerger.java
index 53bdee22e..c14fcaf68 100644
--- a/src/java/org/apache/nutch/segment/SegmentMerger.java
+++ b/src/java/org/apache/nutch/segment/SegmentMerger.java
@@ -649,9 +649,7 @@ public class SegmentMerger extends Configured implements Tool{
for (int i = 0; i < segs.length; i++) {
FileSystem fs = segs[i].getFileSystem(conf);
if (!fs.exists(segs[i])) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Input dir {} doesn't exist, skipping.", segs[i]);
- }
+ LOG.warn("Input dir {} doesn't exist, skipping.", segs[i]);
segs[i] = null;
continue;
}
diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.java
index b2073f6fc..dc18d4adb 100644
--- a/src/java/org/apache/nutch/segment/SegmentReader.java
+++ b/src/java/org/apache/nutch/segment/SegmentReader.java
@@ -184,8 +184,8 @@ public class SegmentReader extends Configured implements Tool {
}
} else if (value instanceof ParseText) {
dump.append("\nParseText::\n").append(((ParseText) value).toString());
- } else if (LOG.isWarnEnabled()) {
- LOG.warn("Unrecognized type: " + value.getClass());
+ } else {
+ LOG.warn("Unrecognized type: {}", value.getClass());
}
}
if (recodeContent && content != null) {
@@ -305,11 +305,9 @@ public class SegmentReader extends Configured implements Tool {
currentRecordNumber = append(fs, conf, partFile, writer,
currentRecordNumber);
} catch (IOException exception) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't copy the content of " + partFile.toString()
- + " into " + dumpFile.toString());
- LOG.warn(exception.getMessage());
- }
+ LOG.warn("Couldn't copy the content of {} into {}",
+ partFile.toString(), dumpFile.toString());
+ LOG.warn(exception.getMessage());
}
}
}
@@ -443,8 +441,8 @@ public class SegmentReader extends Configured implements Tool {
if (it.next().isAlive())
cnt++;
}
- if ((cnt > 0) && (LOG.isDebugEnabled())) {
- LOG.debug("(" + cnt + " to retrieve)");
+ if (cnt > 0) {
+ LOG.debug("({} to retrieve)", cnt);
}
} while (cnt > 0);
for (int i = 0; i < keys.length; i++) {
diff --git a/src/java/org/apache/nutch/tools/AbstractCommonCrawlFormat.java b/src/java/org/apache/nutch/tools/AbstractCommonCrawlFormat.java
index db0383611..00e293900 100644
--- a/src/java/org/apache/nutch/tools/AbstractCommonCrawlFormat.java
+++ b/src/java/org/apache/nutch/tools/AbstractCommonCrawlFormat.java
@@ -174,7 +174,7 @@ public abstract class AbstractCommonCrawlFormat implements CommonCrawlFormat {
return generateJson();
} catch (IOException ioe) {
- LOG.warn("Error in processing file " + url + ": " + ioe.getMessage());
+ LOG.warn("Error in processing file {}: {}", url, ioe.getMessage());
throw new IOException("Error in generating JSON:" + ioe.getMessage());
}
}
@@ -203,7 +203,7 @@ public abstract class AbstractCommonCrawlFormat implements CommonCrawlFormat {
try {
return URIUtil.encodePath(url);
} catch (URIException e) {
- LOG.error("Can't encode URL " + url);
+ LOG.error("Can't encode URL {}", url);
}
return url;
diff --git a/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java b/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
index 9a88f76d4..d5d5035e8 100644
--- a/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
+++ b/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
@@ -390,7 +390,7 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
filter = true;
}
} catch (IOException ioe) {
- LOG.error("Fatal error in creating JSON data: " + ioe.getMessage());
+ LOG.error("Fatal error in creating JSON data: {}", ioe.getMessage());
return;
}
@@ -401,20 +401,18 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
if (!gzip) {
File outputFile = new File(outputFullPath);
if (outputFile.exists()) {
- LOG.info("Skipping writing: [" + outputFullPath
- + "]: file already exists");
+ LOG.info("Skipping writing: [{}]: file already exists", outputFullPath);
} else {
- LOG.info("Writing: [" + outputFullPath + "]");
+ LOG.info("Writing: [{}]", outputFullPath);
IOUtils.copy(new ByteArrayInputStream(byteData),
new FileOutputStream(outputFile));
}
} else {
if (fileList.contains(outputFullPath)) {
- LOG.info("Skipping compressing: [" + outputFullPath
- + "]: file already exists");
+ LOG.info("Skipping compressing: [{}]: file already exists", outputFullPath);
} else {
fileList.add(outputFullPath);
- LOG.info("Compressing: [" + outputFullPath + "]");
+ LOG.info("Compressing: [{}]", outputFullPath);
//TarArchiveEntry tarEntry = new TarArchiveEntry(firstLevelDirName + File.separator + secondLevelDirName + File.separator + filename);
TarArchiveEntry tarEntry = new TarArchiveEntry(
outputRelativePath + File.separator + filename);
@@ -440,7 +438,7 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
}
if (!typeCounts.isEmpty()) {
- LOG.info("CommonsCrawlDataDumper File Stats: " + DumpFileUtil
+ LOG.info("CommonsCrawlDataDumper File Stats: {}", DumpFileUtil
.displayFileTypes(typeCounts, filteredCounts));
}
@@ -455,14 +453,14 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
bufOutput.close();
fileOutput.close();
} catch (IOException ioe) {
- LOG.warn("Error in closing stream: " + ioe.getMessage());
+ LOG.warn("Error in closing stream: {}", ioe.getMessage());
}
}
private void constructNewStream(File outputDir) throws IOException {
String archiveName = new SimpleDateFormat("yyyyMMddhhmm'.tar.gz'")
.format(new Date());
- LOG.info("Creating a new gzip archive: " + archiveName);
+ LOG.info("Creating a new gzip archive: {}", archiveName);
fileOutput = new FileOutputStream(
new File(outputDir + File.separator + archiveName));
bufOutput = new BufferedOutputStream(fileOutput);
@@ -514,7 +512,7 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
return stream.toByteArray();
} catch (Exception e) {
- LOG.warn("CBOR encoding failed: " + e.getMessage());
+ LOG.warn("CBOR encoding failed: {}", e.getMessage());
} finally {
try {
generator.close();
@@ -695,8 +693,8 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
config.setOutputDir(line.getOptionValue("outputDir"));
if (!outputDir.exists()) {
- LOG.warn("Output directory: [" + outputDir.getAbsolutePath()
- + "]: does not exist, creating it.");
+ LOG.warn("Output directory: [{}]: does not exist, creating it.",
+ outputDir.getAbsolutePath());
if (!outputDir.mkdirs())
throw new Exception(
"Unable to create: [" + outputDir.getAbsolutePath() + "]");
@@ -708,7 +706,7 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
extension, warc);
} catch (Exception e) {
- LOG.error(CommonCrawlDataDumper.class.getName() + ": " + StringUtils
+ LOG.error("{}: {}", CommonCrawlDataDumper.class.getName(), StringUtils
.stringifyException(e));
e.printStackTrace();
return -1;
diff --git a/src/java/org/apache/nutch/tools/DmozParser.java b/src/java/org/apache/nutch/tools/DmozParser.java
index ac548471a..476dc20d2 100644
--- a/src/java/org/apache/nutch/tools/DmozParser.java
+++ b/src/java/org/apache/nutch/tools/DmozParser.java
@@ -238,7 +238,7 @@ public class DmozParser {
* When parsing ends
*/
public void endDocument() {
- LOG.info("Completed parse. Found " + pages + " pages.");
+ LOG.info("Completed parse. Found {} pages.", pages);
}
/**
@@ -257,18 +257,14 @@ public class DmozParser {
* Emit the exception message
*/
public void error(SAXParseException spe) {
- if (LOG.isErrorEnabled()) {
- LOG.error("Error: " + spe.toString() + ": " + spe.getMessage());
- }
+ LOG.error("Error: {}: {}", spe.toString(), spe.getMessage());
}
/**
* Emit exception warning message
*/
public void warning(SAXParseException spe) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Warning: " + spe.toString() + ": " + spe.getMessage());
- }
+ LOG.warn("Warning: {}: {}", spe.toString(), spe.getMessage());
}
}
@@ -304,7 +300,7 @@ public class DmozParser {
topicPattern);
reader.setContentHandler(rp);
reader.setErrorHandler(rp);
- LOG.info("skew = " + rp.hashSkew);
+ LOG.info("skew = {}", rp.hashSkew);
//
// Open filtered text stream. The TextFilter makes sure that
@@ -317,9 +313,7 @@ public class DmozParser {
InputSource is = new InputSource(in);
reader.parse(is);
} catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.toString());
- }
+ LOG.error(e.toString());
System.exit(0);
}
}
@@ -333,9 +327,7 @@ public class DmozParser {
topics.addElement(line);
}
} catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.toString());
- }
+ LOG.error(e.toString());
System.exit(0);
}
}
@@ -397,7 +389,7 @@ public class DmozParser {
}
regExp = regExp.concat(topics.get(j));
regExp = regExp.concat(").*");
- LOG.info("Topic selection pattern = " + regExp);
+ LOG.info("Topic selection pattern = {}", regExp);
topicPattern = Pattern.compile(regExp);
}
diff --git a/src/java/org/apache/nutch/tools/FileDumper.java b/src/java/org/apache/nutch/tools/FileDumper.java
index 65c7dca38..efc7e29c2 100644
--- a/src/java/org/apache/nutch/tools/FileDumper.java
+++ b/src/java/org/apache/nutch/tools/FileDumper.java
@@ -132,8 +132,9 @@ public class FileDumper {
*/
public void dump(File outputDir, File segmentRootDir, String[] mimeTypes, boolean
flatDir, boolean mimeTypeStats, boolean reverseURLDump) throws Exception {
- if (mimeTypes == null)
+ if (mimeTypes == null) {
LOG.info("Accepting all mimetypes.");
+ }
// total file counts
Map<String, Integer> typeCounts = new HashMap<>();
// filtered file counts
@@ -142,13 +143,12 @@ public class FileDumper {
int fileCount = 0;
File[] segmentDirs = segmentRootDir.listFiles(file -> file.canRead() && file.isDirectory());
if (segmentDirs == null) {
- LOG.error("No segment directories found in ["
- + segmentRootDir.getAbsolutePath() + "]");
+ LOG.error("No segment directories found in [{}]", segmentRootDir.getAbsolutePath());
return;
}
for (File segment : segmentDirs) {
- LOG.info("Processing segment: [" + segment.getAbsolutePath() + "]");
+ LOG.info("Processing segment: [{}]", segment.getAbsolutePath());
DataOutputStream doutputStream = null;
Map<String, String> filenameToUrl = new HashMap<String, String>();
@@ -165,8 +165,7 @@ public class FileDumper {
String segmentPath = partDir + "/data";
Path file = new Path(segmentPath);
if (!new File(file.toString()).exists()) {
- LOG.warn("Skipping segment: [" + segmentPath
- + "]: no data directory present");
+ LOG.warn("Skipping segment: [{}]: no data directory present", segmentPath);
continue;
}
@@ -200,7 +199,7 @@ public class FileDumper {
}
} catch (Exception e) {
e.printStackTrace();
- LOG.warn("Tika is unable to detect type for: [" + url + "]");
+ LOG.warn("Tika is unable to detect type for: [{}]", url);
} finally {
if (bas != null) {
try {
@@ -245,7 +244,7 @@ public class FileDumper {
File outputFile = new File(outputFullPath);
if (!outputFile.exists()) {
- LOG.info("Writing: [" + outputFullPath + "]");
+ LOG.info("Writing: [{}]", outputFullPath);
// Modified to prevent FileNotFoundException (Invalid Argument)
FileOutputStream output = null;
@@ -253,7 +252,7 @@ public class FileDumper {
output = new FileOutputStream(outputFile);
IOUtils.write(content.getContent(), output);
} catch (Exception e) {
- LOG.warn("Write Error: [" + outputFullPath + "]");
+ LOG.warn("Write Error: [{}]", outputFullPath);
e.printStackTrace();
} finally {
if (output != null) {
@@ -266,8 +265,8 @@ public class FileDumper {
}
fileCount++;
} else {
- LOG.info("Skipping writing: [" + outputFullPath
- + "]: file already exists");
+ LOG.info("Skipping writing: [{}]: file already exists",
+ outputFullPath);
}
}
}
@@ -288,8 +287,8 @@ public class FileDumper {
new ObjectMapper().writeValue(new File(filenameToUrlFilePath), filenameToUrl);
}
- LOG.info("Dumper File Stats: "
- + DumpFileUtil.displayFileTypes(typeCounts, filteredCounts));
+ LOG.info("Dumper File Stats: {}",
+ DumpFileUtil.displayFileTypes(typeCounts, filteredCounts));
if (mimeTypeStats) {
System.out.println("Dumper File Stats: "
@@ -377,8 +376,8 @@ public class FileDumper {
reverseURLDump = true;
if (!outputDir.exists()) {
- LOG.warn("Output directory: [" + outputDir.getAbsolutePath()
- + "]: does not exist, creating it.");
+ LOG.warn("Output directory: [{}]: does not exist, creating it.",
+ outputDir.getAbsolutePath());
if (!shouldDisplayStats) {
if (!outputDir.mkdirs())
throw new Exception("Unable to create: ["
@@ -389,7 +388,7 @@ public class FileDumper {
FileDumper dumper = new FileDumper();
dumper.dump(outputDir, segmentRootDir, mimeTypes, flatDir, shouldDisplayStats, reverseURLDump);
} catch (Exception e) {
- LOG.error("FileDumper: " + StringUtils.stringifyException(e));
+ LOG.error("FileDumper: {}", StringUtils.stringifyException(e));
e.printStackTrace();
return;
}
diff --git a/src/java/org/apache/nutch/tools/FreeGenerator.java b/src/java/org/apache/nutch/tools/FreeGenerator.java
index 9ace8f192..93eec6e53 100644
--- a/src/java/org/apache/nutch/tools/FreeGenerator.java
+++ b/src/java/org/apache/nutch/tools/FreeGenerator.java
@@ -174,7 +174,7 @@ public class FreeGenerator extends Configured implements Tool {
numFetchers = Integer.parseInt(args[i + 1]);
i++;
} else {
- LOG.error("Unknown argument: " + args[i] + ", exiting ...");
+ LOG.error("Unknown argument: {}, exiting ...", args[i]);
return -1;
}
}
@@ -223,7 +223,7 @@ public class FreeGenerator extends Configured implements Tool {
throw new RuntimeException(message);
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
- LOG.error("FAILED: " + StringUtils.stringifyException(e));
+ LOG.error("FAILED: {}", StringUtils.stringifyException(e));
return -1;
}
stopWatch.stop();
diff --git a/src/java/org/apache/nutch/tools/ResolveUrls.java b/src/java/org/apache/nutch/tools/ResolveUrls.java
index 5d84394da..5bf95b9f3 100644
--- a/src/java/org/apache/nutch/tools/ResolveUrls.java
+++ b/src/java/org/apache/nutch/tools/ResolveUrls.java
@@ -80,16 +80,16 @@ public class ResolveUrls {
// get the address by name and if no error is thrown then it
// is resolved successfully
InetAddress.getByName(host);
- LOG.info("Resolved: " + host);
+ LOG.info("Resolved: {}", host);
numResolved.incrementAndGet();
} catch (Exception uhe) {
- LOG.info("Error Resolving: " + host);
+ LOG.info("Error Resolving: {}", host);
numErrored.incrementAndGet();
}
long end = System.currentTimeMillis();
long total = (end - start);
totalTime.addAndGet(total);
- LOG.info(", " + total + " millis");
+ LOG.info(", {} millis", total);
}
}
@@ -112,7 +112,7 @@ public class ResolveUrls {
while ((urlStr = buffRead.readLine()) != null) {
// spin up a resolver thread per url
- LOG.info("Starting: " + urlStr);
+ LOG.info("Starting: {}", urlStr);
pool.execute(new ResolverThread(urlStr));
}
@@ -129,9 +129,9 @@ public class ResolveUrls {
// shutdown the thread pool and log totals
pool.shutdown();
- LOG.info("Total: " + numTotal.get() + ", Resovled: " + numResolved.get()
- + ", Errored: " + numErrored.get() + ", Average Time: "
- + totalTime.get() / numTotal.get());
+ LOG.info("Total: {}, Resovled: {}, Errored: {}, Average Time: {}",
+ numTotal.get(), numResolved.get(), numErrored.get(),
+ totalTime.get() / numTotal.get());
}
/**
@@ -203,7 +203,7 @@ public class ResolveUrls {
ResolveUrls resolve = new ResolveUrls(urls, numThreads);
resolve.resolveUrls();
} catch (Exception e) {
- LOG.error("ResolveUrls: " + StringUtils.stringifyException(e));
+ LOG.error("ResolveUrls: {}", StringUtils.stringifyException(e));
}
}
}
diff --git a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
index 311675310..27321573d 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
@@ -117,10 +117,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
* The error that occured.
*/
private static void logError(Text url, Throwable t) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Conversion of " + url + " failed with: "
- + StringUtils.stringifyException(t));
- }
+ LOG.info("Conversion of {} failed with: {}", url, StringUtils.stringifyException(t));
}
public static class ArcSegmentCreatorMapper extends
@@ -175,9 +172,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
try {
scfilters.passScoreBeforeParsing(key, datum, content);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
- }
+ LOG.warn("Couldn't pass score, url {} ({})", key, e);
}
try {
@@ -185,8 +180,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
// parse the content
parseResult = parseUtil.parse(content);
} catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": "
- + StringUtils.stringifyException(e));
+ LOG.warn("Error parsing: {}: {}", key, StringUtils.stringifyException(e));
}
// set the content signature
@@ -213,7 +207,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
ParseStatus parseStatus = parse.getData().getStatus();
if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
+ LOG.warn("Error parsing: {}: {}", key, parseStatus);
parse = parseStatus.getEmptyParse(conf);
}
@@ -233,19 +227,14 @@ public class ArcSegmentCreator extends Configured implements Tool {
try {
scfilters.passScoreAfterParsing(url, content, parse);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
- }
+ LOG.warn("Couldn't pass score, url {} ({})", key, e);
}
context.write(url, new NutchWritable(new ParseImpl(new ParseText(
parse.getText()), parse.getData(), parse.isCanonical())));
}
}
} catch (IOException e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("ArcSegmentCreator caught:"
- + StringUtils.stringifyException(e));
- }
+ LOG.error("ArcSegmentCreator caught:{}", StringUtils.stringifyException(e));
}
if (parseResult != null && !parseResult.isEmpty()) {
@@ -300,10 +289,10 @@ public class ArcSegmentCreator extends Configured implements Tool {
// arcs start with a file description. for now we ignore this as it is not
// a content record
if (urlStr.startsWith("filedesc://")) {
- LOG.info("Ignoring file header: " + urlStr);
+ LOG.info("Ignoring file header: {}", urlStr);
return;
}
- LOG.info("Processing: " + urlStr);
+ LOG.info("Processing: {}", urlStr);
// get the raw bytes from the arc file, create a new crawldatum
Text url = new Text();
@@ -316,9 +305,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
urlStr = normalizers.normalize(urlStr, URLNormalizers.SCOPE_FETCHER);
urlStr = urlFilters.filter(urlStr); // filter the url
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Skipping " + url + ":" + e);
- }
+ LOG.warn("Skipping {}: {}", url, e);
urlStr = null;
}
@@ -372,7 +359,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
LOG.info("ArcSegmentCreator: starting");
- LOG.info("ArcSegmentCreator: arc files dir: " + arcFiles);
+ LOG.info("ArcSegmentCreator: arc files dir: {}", arcFiles);
Job job = Job.getInstance(getConf(), "Nutch ArcSegmentCreator: " + arcFiles);
Configuration conf = job.getConfiguration();
@@ -401,7 +388,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
}
stopWatch.stop();
- LOG.info("ArcSegmentCreator: finished, elapsed: {} ms" + stopWatch.getTime(
+ LOG.info("ArcSegmentCreator: finished, elapsed: {} ms{}", stopWatch.getTime(
TimeUnit.MILLISECONDS));
}
@@ -430,7 +417,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
createSegments(arcFiles, segmentsOutDir);
return 0;
} catch (Exception e) {
- LOG.error("ArcSegmentCreator: " + StringUtils.stringifyException(e));
+ LOG.error("ArcSegmentCreator: {}", StringUtils.stringifyException(e));
return -1;
}
}
diff --git a/src/java/org/apache/nutch/util/AbstractChecker.java b/src/java/org/apache/nutch/util/AbstractChecker.java
index 137481225..039d6a610 100644
--- a/src/java/org/apache/nutch/util/AbstractChecker.java
+++ b/src/java/org/apache/nutch/util/AbstractChecker.java
@@ -111,7 +111,7 @@ public abstract class AbstractChecker extends Configured implements Tool {
server.bind(new InetSocketAddress(tcpPort));
LOG.info(server.toString());
} catch (Exception e) {
- LOG.error("Could not listen on port " + tcpPort, e);
+ LOG.error("Could not listen on port {}", tcpPort, e);
return -1;
}
@@ -122,7 +122,7 @@ public abstract class AbstractChecker extends Configured implements Tool {
Thread thread = new Thread(worker);
thread.start();
} catch (Exception e) {
- LOG.error("Accept failed: " + tcpPort, e);
+ LOG.error("Accept failed: {}", tcpPort, e);
return -1;
}
}
diff --git a/src/java/org/apache/nutch/util/CrawlCompletionStats.java b/src/java/org/apache/nutch/util/CrawlCompletionStats.java
index e5ee5f643..d806b9295 100644
--- a/src/java/org/apache/nutch/util/CrawlCompletionStats.java
+++ b/src/java/org/apache/nutch/util/CrawlCompletionStats.java
@@ -177,7 +177,7 @@ public class CrawlCompletionStats extends Configured implements Tool {
throw new RuntimeException(message);
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
- LOG.error(jobName + " job failed");
+ LOG.error("{} job failed", jobName);
throw e;
}
diff --git a/src/java/org/apache/nutch/util/DomainStatistics.java b/src/java/org/apache/nutch/util/DomainStatistics.java
index 0a74f0231..5ee09c846 100644
--- a/src/java/org/apache/nutch/util/DomainStatistics.java
+++ b/src/java/org/apache/nutch/util/DomainStatistics.java
@@ -144,7 +144,7 @@ public class DomainStatistics extends Configured implements Tool {
throw new RuntimeException(message);
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
- LOG.error(jobName + " job failed", e);
+ LOG.error("{} job failed", jobName, e);
throw e;
}
@@ -196,7 +196,7 @@ public class DomainStatistics extends Configured implements Tool {
break;
}
if (out.trim().equals("")) {
- LOG.info("url : " + url);
+ LOG.info("url : {}", url);
context.getCounter(MyCounter.EMPTY_RESULT).increment(1);
}
diff --git a/src/java/org/apache/nutch/util/EncodingDetector.java b/src/java/org/apache/nutch/util/EncodingDetector.java
index d474b11b1..000cc37c3 100644
--- a/src/java/org/apache/nutch/util/EncodingDetector.java
+++ b/src/java/org/apache/nutch/util/EncodingDetector.java
@@ -239,24 +239,19 @@ public class EncodingDetector {
EncodingClue bestClue = defaultClue;
for (EncodingClue clue : clues) {
- if (LOG.isTraceEnabled()) {
- LOG.trace(base + ": charset " + clue);
- }
+ LOG.trace("{}: charset {}", base, clue);
String charset = clue.value;
if (minConfidence >= 0 && clue.confidence >= minConfidence) {
- if (LOG.isTraceEnabled()) {
- LOG.trace(base + ": Choosing encoding: " + charset
- + " with confidence " + clue.confidence);
- }
+ LOG.trace("{}: Choosing encoding: {} with confidence {}", base, charset,
+ clue.confidence);
return resolveEncodingAlias(charset).toLowerCase();
} else if (clue.confidence == NO_THRESHOLD && bestClue == defaultClue) {
bestClue = clue;
}
}
- if (LOG.isTraceEnabled()) {
- LOG.trace(base + ": Choosing encoding: " + bestClue);
- }
+ LOG.trace("{}: Choosing encoding: {}", base, bestClue);
+
return bestClue.value.toLowerCase();
}
@@ -310,7 +305,7 @@ public class EncodingDetector {
return ALIASES.containsKey(canonicalName) ? ALIASES.get(canonicalName)
: canonicalName;
} catch (Exception e) {
- LOG.warn("Invalid encoding " + encoding + " detected, using default.");
+ LOG.warn("Invalid encoding {} detected, using default.", encoding);
return null;
}
}
diff --git a/src/java/org/apache/nutch/util/MimeUtil.java b/src/java/org/apache/nutch/util/MimeUtil.java
index 656331646..eacd69a16 100644
--- a/src/java/org/apache/nutch/util/MimeUtil.java
+++ b/src/java/org/apache/nutch/util/MimeUtil.java
@@ -86,14 +86,13 @@ public final class MimeUtil {
mimeTypez = MimeTypesFactory.create(conf
.getConfResourceAsInputStream(customMimeTypeFile));
} catch (Exception e) {
- LOG.error("Can't load mime.types.file : " + customMimeTypeFile
- + " using Tika's default");
+ LOG.error("Can't load mime.types.file : {} using Tika's default", customMimeTypeFile);
}
}
if (mimeTypez == null)
mimeTypez = MimeTypes.getDefaultMimeTypes();
} catch (Exception e) {
- LOG.error("Exception in MimeUtil " + e.getMessage());
+ LOG.error("Exception in MimeUtil {}", e.getMessage());
throw new RuntimeException(e);
}
objectCache.setObject(MimeTypes.class.getName(), mimeTypez);
@@ -248,8 +247,7 @@ public final class MimeUtil {
try {
return this.mimeTypes.forName(name).toString();
} catch (MimeTypeException e) {
- LOG.error("Exception getting mime type by name: [" + name
- + "]: Message: " + e.getMessage());
+ LOG.error("Exception getting mime type by name: [{}]: Message: {}", name, e.getMessage());
return null;
}
}
@@ -267,8 +265,7 @@ public final class MimeUtil {
try {
return tika.detect(f);
} catch (Exception e) {
- LOG.error("Exception getting mime type for file: [" + f.getPath()
- + "]: Message: " + e.getMessage());
+ LOG.error("Exception getting mime type for file: [{}]: Message: {}", f.getPath(), e.getMessage());
return null;
}
}
diff --git a/src/java/org/apache/nutch/util/ObjectCache.java b/src/java/org/apache/nutch/util/ObjectCache.java
index e313a6eca..816f9eebb 100644
--- a/src/java/org/apache/nutch/util/ObjectCache.java
+++ b/src/java/org/apache/nutch/util/ObjectCache.java
@@ -40,8 +40,9 @@ public class ObjectCache {
public synchronized static ObjectCache get(Configuration conf) {
ObjectCache objectCache = CACHE.get(conf);
if (objectCache == null) {
- LOG.debug("No object cache found for conf=" + conf
- + ", instantiating a new object cache");
+ LOG.debug(
+ "No object cache found for conf={}, instantiating a new object cache",
+ conf);
objectCache = new ObjectCache();
CACHE.put(conf, objectCache);
}
diff --git a/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java b/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java
index f4e8a1b91..3c37887cc 100644
--- a/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java
+++ b/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java
@@ -125,7 +125,7 @@ public class ProtocolStatusStatistics extends Configured implements Tool {
throw new RuntimeException(message);
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
- LOG.error(jobName + " job failed", e);
+ LOG.error("{} job failed", jobName, e);
throw e;
}
diff --git a/src/java/org/apache/nutch/util/SitemapProcessor.java b/src/java/org/apache/nutch/util/SitemapProcessor.java
index 043e77f69..75967815b 100644
--- a/src/java/org/apache/nutch/util/SitemapProcessor.java
+++ b/src/java/org/apache/nutch/util/SitemapProcessor.java
@@ -161,12 +161,13 @@ public class SitemapProcessor extends Configured implements Tool {
context.getCounter("Sitemap", "sitemap_seeds").increment(1);
generateSitemapUrlDatum(protocolFactory.getProtocol(url), url, context);
} else {
- LOG.info("generateSitemapsFromHostname: " + key.toString());
+ LOG.info("generateSitemapsFromHostname: {}", key.toString());
generateSitemapsFromHostname(key.toString(), context);
}
}
} catch (Exception e) {
- LOG.warn("Exception for record {} : {}", key.toString(), StringUtils.stringifyException(e));
+ LOG.warn("Exception for record {} : {}", key.toString(),
+ StringUtils.stringifyException(e));
}
}
@@ -447,7 +448,7 @@ public class SitemapProcessor extends Configured implements Tool {
LOG.info("SitemapProcessor: finished, elapsed: {} ms", stopWatch.getTime(
TimeUnit.MILLISECONDS));
} catch (IOException | InterruptedException | ClassNotFoundException e) {
- LOG.error("SitemapProcessor_" + crawldb.toString(), e);
+ LOG.error("SitemapProcessor_{}", crawldb.toString(), e);
NutchJob.cleanupAfterFailure(tempCrawlDb, lock, fs);
throw e;
}
diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
index bb3560d53..5640171d3 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java
@@ -57,9 +57,7 @@ public class CCIndexingFilter implements IndexingFilter {
// index the license
String licenseUrl = metadata.get(CreativeCommons.LICENSE_URL);
if (licenseUrl != null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("CC: indexing " + licenseUrl + " for: " + url.toString());
- }
+ LOG.info("CC: indexing {} for: {}", licenseUrl, url.toString());
// add the entire license as cc:license=xxx
addFeature(doc, "license=" + licenseUrl);
@@ -106,9 +104,7 @@ public class CCIndexingFilter implements IndexingFilter {
addFeature(doc, feature);
}
} catch (MalformedURLException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("CC: failed to parse url: " + urlString + " : " + e);
- }
+ LOG.warn("CC: failed to parse url: {} :", urlString, e);
}
}
diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
index 9e7676d70..030c6bf66 100644
--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java
@@ -99,18 +99,13 @@ public class CCParseFilter implements HtmlParseFilter {
// add license to metadata
if (licenseUrl != null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("CC: found " + licenseUrl + " in " + licenseLocation
- + " of " + base);
- }
+ LOG.info("CC: found {} in {} of {}", licenseUrl, licenseLocation, base);
metadata.add(CreativeCommons.LICENSE_URL, licenseUrl);
metadata.add(CreativeCommons.LICENSE_LOCATION, licenseLocation);
}
if (walker.workType != null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("CC: found " + walker.workType + " in " + base);
- }
+ LOG.info("CC: found {} in {}", walker.workType, base);
metadata.add(CreativeCommons.WORK_TYPE, walker.workType);
}
@@ -203,18 +198,14 @@ public class CCParseFilter implements HtmlParseFilter {
DocumentBuilder parser = FACTORY.newDocumentBuilder();
doc = parser.parse(new InputSource(new StringReader(comment)));
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("CC: Failed to parse RDF in " + base + ": " + e);
- }
+ LOG.warn("CC: Failed to parse RDF in {}: ", base, e);
return;
}
// check that root is rdf:RDF
NodeList roots = doc.getElementsByTagNameNS(RDF_NS, "RDF");
if (roots.getLength() != 1) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("CC: No RDF root in " + base);
- }
+ LOG.warn("CC: No RDF root in {}", base);
return;
}
Element rdf = (Element) roots.item(0);
diff --git a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
index cecd36630..53d932911 100644
--- a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
+++ b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
@@ -29,7 +29,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.metadata.Feed;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.net.URLFilters;
@@ -116,8 +115,7 @@ public class FeedParser implements Parser {
feed = feedInput.build(input);
} catch (Exception e) {
// return empty parse
- LOG.warn("Parse failed: url: " + content.getUrl() + ", exception: "
- + StringUtils.stringifyException(e));
+ LOG.warn("Parse failed: url: {}, exception: ", content.getUrl(), e);
return new ParseStatus(e)
.getEmptyParseResult(content.getUrl(), getConf());
}
diff --git a/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java b/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
index 7493c3187..d5bb01c3d 100644
--- a/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
+++ b/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
@@ -51,7 +51,7 @@ public class AnchorIndexingFilter implements IndexingFilter {
this.conf = conf;
deduplicate = conf.getBoolean("anchorIndexingFilter.deduplicate", false);
- LOG.info("Anchor deduplication is: " + (deduplicate ? "on" : "off"));
+ LOG.info("Anchor deduplication is: {}", (deduplicate ? "on" : "off"));
}
/**
diff --git a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java
index 5cc9fcfb8..31b6398fd 100644
--- a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java
+++ b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java
@@ -157,11 +157,9 @@ public class MoreIndexingFilter implements IndexingFilter {
try {
Date parsedDate = DateUtils.parseDate(date, dateStyles);
time = parsedDate.getTime();
- LOG.info(url + ": parsed date: " + date +" to: " + time);
+ LOG.info("{}: parsed date: {} to: {}", url, date, time);
} catch (Exception e2) {
- if (LOG.isWarnEnabled()) {
- LOG.warn(url + ": can't parse erroneous date: " + date);
- }
+ LOG.warn("{}: can't parse erroneous date: {}", url, date);
}
}
diff --git a/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/FieldReplacer.java b/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/FieldReplacer.java
index ecea343df..c2047d459 100644
--- a/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/FieldReplacer.java
+++ b/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/FieldReplacer.java
@@ -70,8 +70,9 @@ public class FieldReplacer {
this.isValid = false;
}
if (pattern == null || pattern.trim().length() == 0) {
- LOG.error("Empty pattern for field " + fieldName
- + "provided, FieldReplacer marked invalid.");
+ LOG.error(
+ "Empty pattern for field {} provided, FieldReplacer marked invalid.",
+ fieldName);
this.isValid = false;
}
@@ -85,7 +86,7 @@ public class FieldReplacer {
this.toFieldName = toFieldName.trim();
if (this.isValid) {
- LOG.info("Compiling pattern " + pattern + " for field " + fieldName);
+ LOG.info("Compiling pattern {} for field {}", pattern, fieldName);
Pattern myPattern = null;
try {
if (flags != null) {
@@ -94,8 +95,8 @@ public class FieldReplacer {
myPattern = Pattern.compile(pattern);
}
} catch (PatternSyntaxException e) {
- LOG.error("Pattern " + pattern + " for field " + fieldName
- + " failed to compile: " + e.toString());
+ LOG.error("Pattern {} for field {} failed to compile: ", pattern,
+ fieldName, e);
this.isValid = false;
}
this.pattern = myPattern;
diff --git a/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/ReplaceIndexer.java b/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/ReplaceIndexer.java
index 8dde66fcb..bf1e44d4b 100644
--- a/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/ReplaceIndexer.java
+++ b/src/plugin/index-replace/src/java/org/apache/nutch/indexer/replace/ReplaceIndexer.java
@@ -152,8 +152,8 @@ public class ReplaceIndexer implements IndexingFilter {
try {
hostPattern = Pattern.compile(value);
} catch (PatternSyntaxException pse) {
- LOG.error("hostmatch pattern " + value + " does not compile: "
- + pse.getMessage());
+ LOG.error("hostmatch pattern {} does not compile: {}", value,
+ pse.getMessage());
// Deactivate this invalid match set by making it match no host.
hostPattern = Pattern.compile("willnotmatchanyhost");
}
@@ -161,8 +161,8 @@ public class ReplaceIndexer implements IndexingFilter {
try {
urlPattern = Pattern.compile(value);
} catch (PatternSyntaxException pse) {
- LOG.error("urlmatch pattern " + value + " does not compile: "
- + pse.getMessage());
+ LOG.error("urlmatch pattern {} does not compile: {}", value,
+ pse.getMessage());
// Deactivate this invalid match set by making it match no url.
urlPattern = Pattern.compile("willnotmatchanyurl");
}
@@ -179,8 +179,8 @@ public class ReplaceIndexer implements IndexingFilter {
// Divide the value into pattern / replacement / flags.
value = value.substring(1);
if (!value.contains(sep)) {
- LOG.error("Pattern '" + line
- + "', not parseable. Missing separator " + sep);
+ LOG.error("Pattern '{}', not parseable. Missing separator {}",
+ line, sep);
continue;
}
String pattern = value.substring(0, value.indexOf(sep));
@@ -195,7 +195,7 @@ public class ReplaceIndexer implements IndexingFilter {
try {
flags = Integer.parseInt(value);
} catch (NumberFormatException e) {
- LOG.error("Pattern " + line + ", has invalid flags component");
+ LOG.error("Pattern {} has invalid flags component", line);
continue;
}
}
diff --git a/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.java b/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.java
index 51cd41d7a..a0ea4a738 100644
--- a/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.java
+++ b/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.java
@@ -117,13 +117,13 @@ public class CSVIndexWriter implements IndexWriter {
boolean isChar) {
String str = parameters.get(property);
if (isChar && str != null && !str.isEmpty()) {
- LOG.warn("Separator " + property
- + " must be a char, only the first character '" + str.charAt(0)
- + "' of \"" + str + "\" is used");
+ LOG.warn(
+ "Separator {} must be a char, only the first character '{}' of \"{}\" is used",
+ property, str.charAt(0), str);
str = str.substring(0, 1);
}
set(str);
- LOG.info(property + " = " + toString());
+ LOG.info("{} = {}", property, toString());
}
/**
@@ -215,13 +215,13 @@ public class CSVIndexWriter implements IndexWriter {
valueSeparator.setFromConf(parameters, CSVConstants.CSV_VALUESEPARATOR);
withHeader = parameters.getBoolean(CSVConstants.CSV_WITHHEADER, true);
maxFieldLength = parameters.getInt(CSVConstants.CSV_MAXFIELDLENGTH, maxFieldLength);
- LOG.info(CSVConstants.CSV_MAXFIELDLENGTH + " = " + maxFieldLength);
+ LOG.info("{} = {}", CSVConstants.CSV_MAXFIELDLENGTH, maxFieldLength);
maxFieldValues = parameters.getInt(CSVConstants.CSV_MAXFIELDVALUES, maxFieldValues);
- LOG.info(CSVConstants.CSV_MAXFIELDVALUES + " = " + maxFieldValues);
+ LOG.info("{} = {}", CSVConstants.CSV_MAXFIELDVALUES, maxFieldValues);
fields = parameters.getStrings(CSVConstants.CSV_FIELDS, "id", "title", "content");
LOG.info("fields =");
for (String f : fields) {
- LOG.info("\t" + f);
+ LOG.info("\t{}", f);
}
fs = FileSystem.get(config);
diff --git a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
index dc024d50b..84978dbc2 100644
--- a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
+++ b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
@@ -219,7 +219,7 @@ public class ElasticIndexWriter implements IndexWriter {
}
});
} catch (Exception e) {
- LOG.error("Error setting up SSLContext because: " + e.getMessage(), e);
+ LOG.error("Error setting up SSLContext because: {}", e.getMessage(), e);
}
}
diff --git a/src/plugin/indexer-opensearch-1x/src/java/org/apache/nutch/indexwriter/opensearch1x/OpenSearch1xIndexWriter.java b/src/plugin/indexer-opensearch-1x/src/java/org/apache/nutch/indexwriter/opensearch1x/OpenSearch1xIndexWriter.java
index 878c55a09..a51004ebc 100644
--- a/src/plugin/indexer-opensearch-1x/src/java/org/apache/nutch/indexwriter/opensearch1x/OpenSearch1xIndexWriter.java
+++ b/src/plugin/indexer-opensearch-1x/src/java/org/apache/nutch/indexwriter/opensearch1x/OpenSearch1xIndexWriter.java
@@ -242,7 +242,7 @@ public class OpenSearch1xIndexWriter implements IndexWriter {
}
});
} catch (Exception e) {
- LOG.error("Error setting up SSLContext because: " + e.getMessage(),
+ LOG.error("Error setting up SSLContext because: {}", e.getMessage(),
e);
}
}
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
index ec2ab46d2..bd2a51824 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
@@ -252,7 +252,7 @@ public class SolrIndexWriter implements IndexWriter {
}
}
} catch (final SolrServerException e) {
- LOG.error("Failed to commit solr connection: " + e.getMessage());
+ LOG.error("Failed to commit solr connection: {}", e.getMessage());
}
}
@@ -298,7 +298,7 @@ public class SolrIndexWriter implements IndexWriter {
}
} catch (final SolrServerException e) {
- LOG.error("Error deleting: " + deleteIds);
+ LOG.error("Error deleting: {}", deleteIds);
throw makeIOException(e);
}
deleteIds.clear();
diff --git a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
index 783c3bf3f..2e47b2073 100644
--- a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
+++ b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
@@ -70,9 +70,7 @@ public class HTMLLanguageParser implements HtmlParseFilter {
}
}
} catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.toString());
- }
+ LOG.error(e.toString());
}
}
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
index 7e337f844..e24488234 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
@@ -408,16 +408,12 @@ public abstract class HttpBase implements Protocol {
// handle this in the higher layer.
return new ProtocolOutput(c, new ProtocolStatus(protocolStatusCode, u));
} else if (code == 400) { // bad request, mark as GONE
- if (this.logger.isTraceEnabled()) {
- this.logger.trace("400 Bad request: {}", u);
- }
+ this.logger.trace("400 Bad request: {}", u);
return new ProtocolOutput(c,
new ProtocolStatus(ProtocolStatus.GONE, u));
} else if (code == 401) { // requires authorization, but no valid auth
// provided.
- if (this.logger.isTraceEnabled()) {
- this.logger.trace("401 Authentication Required");
- }
+ this.logger.trace("401 Authentication Required");
return new ProtocolOutput(c,
new ProtocolStatus(ProtocolStatus.ACCESS_DENIED,
"Authentication required: " + urlString));
@@ -571,8 +567,8 @@ public abstract class HttpBase implements Protocol {
private static String getAgentString(String agentName, String agentVersion,
String agentDesc, String agentURL, String agentEmail) {
- if (((agentName == null) || (agentName.trim().isEmpty())) && LOG.isErrorEnabled()) {
- LOG.error("No User-Agent string set (http.agent.name)!");
+ if ((agentName == null) || (agentName.trim().isEmpty())) {
+ LOG.error("No User-Agent string set (http.agent.name)!");
}
StringBuilder buf = new StringBuilder();
@@ -624,9 +620,7 @@ public abstract class HttpBase implements Protocol {
public byte[] processGzipEncoded(byte[] compressed, URL url)
throws IOException {
- if (LOG.isTraceEnabled()) {
- LOG.trace("uncompressing....");
- }
+ LOG.trace("uncompressing....");
// content can be empty (i.e. redirection) in which case
// there is nothing to unzip
@@ -643,10 +637,9 @@ public abstract class HttpBase implements Protocol {
if (content == null)
throw new IOException("unzipBestEffort returned null");
- if (LOG.isTraceEnabled()) {
- LOG.trace("fetched {} bytes of compressed content (expanded to {} " +
- "bytes) from {}", compressed.length, content.length, url);
- }
+ LOG.trace(
+ "fetched {} bytes of compressed content (expanded to {} bytes) from {}",
+ compressed.length, content.length, url);
return content;
}
@@ -658,9 +651,7 @@ public abstract class HttpBase implements Protocol {
if (compressed.length == 0)
return compressed;
- if (LOG.isTraceEnabled()) {
- LOG.trace("inflating....");
- }
+ LOG.trace("inflating....");
byte[] content;
if (getMaxContent() >= 0) {
@@ -672,10 +663,9 @@ public abstract class HttpBase implements Protocol {
if (content == null)
throw new IOException("inflateBestEffort returned null");
- if (LOG.isTraceEnabled()) {
- LOG.trace("fetched {} bytes of compressed content (expanded to {} " +
- "bytes) from {}", compressed.length, content.length, url);
- }
+ LOG.trace(
+ "fetched {} bytes of compressed content (expanded to {} bytes) from {}",
+ compressed.length, content.length, url);
return content;
}
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
index 9818c9a4a..9da92698f 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
@@ -243,14 +243,14 @@ public class HttpRobotRulesParser extends RobotRulesParser {
}
} catch (Throwable t) {
if (robotsUrl == null || robotsUrlRedir == null) {
- LOG.info("Couldn't get robots.txt for {}", url, t);
+ LOG.info("Couldn't get robots.txt for {}", url, t.getMessage());
} else if (robotsUrl.equals(robotsUrlRedir)) {
LOG.info("Couldn't get robots.txt for {} ({}): {}", url, robotsUrl,
- t);
+ t.getMessage());
} else {
LOG.info(
"Couldn't get redirected robots.txt for {} (redirected to {}): {}",
- url, robotsUrlRedir, t);
+ url, robotsUrlRedir, t.getMessage());
}
cacheRule = false; // try again later to fetch robots.txt
robotRules = EMPTY_RULES;
diff --git a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
index fd59fb9cc..ee243989e 100644
--- a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
+++ b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
@@ -211,17 +211,13 @@ public abstract class RegexURLFilterBase implements URLFilter {
try {
reader = getRulesReader(conf);
} catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.getMessage());
- }
+ LOG.error(e.getMessage());
throw new RuntimeException(e.getMessage(), e);
}
try {
rules = readRules(reader);
} catch (IOException e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.getMessage());
- }
+ LOG.error(e.getMessage());
throw new RuntimeException(e.getMessage(), e);
}
}
@@ -275,9 +271,7 @@ public abstract class RegexURLFilterBase implements URLFilter {
}
String regex = line.substring(1);
- if (LOG.isTraceEnabled()) {
- LOG.trace("Adding rule [" + regex + "] for " + hostOrDomain);
- }
+ LOG.trace("Adding rule [" + regex + "] for " + hostOrDomain);
RegexRule rule = createRule(sign, regex, hostOrDomain);
rules.add(rule);
}
diff --git a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
index 3d96a7b04..2f35ed017 100644
--- a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
+++ b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
@@ -106,7 +106,7 @@ public class RelTagParser implements HtmlParseFilter {
if (!StringUtil.isEmpty(tag)) {
if (!tags.contains(tag)) {
tags.add(tag);
- LOG.debug("Adding tag: " + tag + " to tag set.");
+ LOG.debug("Adding tag {} to tag set.", tag);
}
}
}
diff --git a/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java b/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
index e98f1b516..9fb0b43fd 100644
--- a/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
+++ b/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
@@ -109,9 +109,7 @@ public class MimeTypeIndexingFilter implements IndexingFilter {
contentType = mimeType;
- if (LOG.isInfoEnabled()) {
- LOG.info(String.format("[%s] %s", contentType, url));
- }
+ LOG.info("[{}] {}", contentType, url);
if (trie != null) {
if (trie.shortestMatch(contentType) == null) {
@@ -150,9 +148,7 @@ public class MimeTypeIndexingFilter implements IndexingFilter {
try {
readConfiguration(reader);
} catch (IOException e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.getMessage());
- }
+ LOG.error(e.getMessage());
throw new RuntimeException(e.getMessage(), e);
}
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
index 6a6d49d49..73d42d0dc 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java
@@ -176,9 +176,7 @@ public class HtmlParser implements Parser {
metadata.set(Metadata.CHAR_ENCODING_FOR_CONVERSION, encoding);
input.setEncoding(encoding);
- if (LOG.isTraceEnabled()) {
- LOG.trace("Parsing...");
- }
+ LOG.trace("Parsing...");
root = parse(input);
} catch (IOException e) {
return new ParseStatus(e)
@@ -201,21 +199,16 @@ public class HtmlParser implements Parser {
// populate Nutch metadata with HTML meta directives
metadata.addAll(metaTags.getGeneralTags());
- if (LOG.isTraceEnabled()) {
- LOG.trace("Meta tags for " + base + ": " + metaTags.toString());
- }
+ LOG.trace("Meta tags for " + base + ": " + metaTags.toString());
+
// check meta directives
if (!metaTags.getNoIndex()) { // okay to index
StringBuffer sb = new StringBuffer();
- if (LOG.isTraceEnabled()) {
- LOG.trace("Getting text...");
- }
+ LOG.trace("Getting text...");
utils.getText(sb, root); // extract text
text = sb.toString();
sb.setLength(0);
- if (LOG.isTraceEnabled()) {
- LOG.trace("Getting title...");
- }
+ LOG.trace("Getting title...");
utils.getTitle(sb, root); // extract title
title = sb.toString().trim();
}
@@ -231,15 +224,10 @@ public class HtmlParser implements Parser {
baseTag = base;
}
}
- if (LOG.isTraceEnabled()) {
- LOG.trace("Getting links...");
- }
+ LOG.trace("Getting links...");
utils.getOutlinks(baseTag, l, root);
outlinks = l.toArray(new Outlink[l.size()]);
- if (LOG.isTraceEnabled()) {
- LOG.trace("found " + outlinks.length + " outlinks in "
- + content.getUrl());
- }
+ LOG.trace("found {} outlinks in {}", outlinks.length, content.getUrl());
}
ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);
@@ -326,10 +314,7 @@ public class HtmlParser implements Parser {
parser.parse(input, frag);
if (!frag.hasChildNodes())
break;
- if (LOG.isInfoEnabled()) {
- LOG.info(" - new frag, " + frag.getChildNodes().getLength()
- + " nodes.");
- }
+ LOG.info(" - new frag, {} nodes.", frag.getChildNodes().getLength());
res.appendChild(frag);
}
} catch (Exception e) {
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
index 80d09e7d8..6e13a69ea 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
@@ -114,9 +114,9 @@ public class TestHtmlParser {
String title = parse.getData().getTitle();
String keywords = parse.getData().getMeta("keywords");
LOG.info(name);
- LOG.info("title:\t" + title);
- LOG.info("keywords:\t" + keywords);
- LOG.info("text:\t" + text);
+ LOG.info("title:\t{}", title);
+ LOG.info("keywords:\t{}", keywords);
+ LOG.info("text:\t{}", text);
Assert.assertEquals("Title not extracted properly (" + name + ")",
encodingTestKeywords, title);
for (String keyword : encodingTestKeywords.split(",\\s*")) {
diff --git a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
index c27ef4a51..194ef915e 100644
--- a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
+++ b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
@@ -122,10 +122,6 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
script.append('\n');
script.append(nn.item(i).getNodeValue());
}
- // if (LOG.isInfoEnabled()) {
- // LOG.info("script: language=" + lang + ", text: " +
- // script.toString());
- // }
Outlink[] links = getJSLinks(script.toString(), "", base);
if (links != null && links.length > 0)
outlinks.addAll(Arrays.asList(links));
@@ -215,9 +211,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
try {
baseURL = new URL(base);
} catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("error assigning base URL", e);
- }
+ LOG.error("error assigning base URL", e);
}
try {
@@ -240,10 +234,8 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
try {
url = new URL(baseURL, url).toString();
} catch (MalformedURLException ex) {
- if (LOG.isTraceEnabled()) {
- LOG.trace(" - failed URL parse '" + url + "' and baseURL '"
- + baseURL + "'", ex);
- }
+ LOG.trace(" - failed URL parse '{}' and baseURL '{}'", url, baseURL,
+ ex);
continue;
}
}
@@ -256,9 +248,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
} catch (Exception ex) {
// if it is a malformed URL we just throw it away and continue with
// extraction.
- if (LOG.isErrorEnabled()) {
- LOG.error(" - invalid or malformed URL", ex);
- }
+ LOG.error(" - invalid or malformed URL", ex);
}
final Outlink[] retval;
diff --git a/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/MetaTagsParser.java b/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/MetaTagsParser.java
index 6cef43870..1ede6cd2b 100644
--- a/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/MetaTagsParser.java
+++ b/src/plugin/parse-metatags/src/java/org/apache/nutch/parse/metatags/MetaTagsParser.java
@@ -72,9 +72,7 @@ public class MetaTagsParser implements HtmlParseFilter {
String value) {
String lcMetatag = metatag.toLowerCase(Locale.ROOT);
if (metatagset.contains("*") || metatagset.contains(lcMetatag)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Found meta tag: {}\t{}", lcMetatag, value);
- }
+ LOG.debug("Found meta tag: {}\t{}", lcMetatag, value);
metadata.add("metatag." + lcMetatag, value);
}
}
@@ -89,9 +87,7 @@ public class MetaTagsParser implements HtmlParseFilter {
if (metatagset.contains("*") || metatagset.contains(lcMetatag)) {
String key = "metatag." + lcMetatag;
for (String value : values) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Found meta tag: {}\t{}", lcMetatag, value);
- }
+ LOG.debug("Found meta tag: {}\t{}", lcMetatag, value);
metadata.add(key, value);
}
}
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/BoilerpipeExtractorRepository.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/BoilerpipeExtractorRepository.java
index 03c493287..483009a87 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/BoilerpipeExtractorRepository.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/BoilerpipeExtractorRepository.java
@@ -43,15 +43,17 @@ class BoilerpipeExtractorRepository {
ClassLoader loader = BoilerpipeExtractor.class.getClassLoader();
Class<?> extractorClass = loader.loadClass(boilerpipeExtractorName);
- // Add an instance to the repository
- extractorRepository.put(boilerpipeExtractorName, (BoilerpipeExtractor)extractorClass.getConstructor().newInstance());
+ // Add an instance to the repository
+ extractorRepository.put(boilerpipeExtractorName,
+ (BoilerpipeExtractor) extractorClass.getConstructor()
+ .newInstance());
} catch (ClassNotFoundException e) {
- LOG.error("BoilerpipeExtractor " + boilerpipeExtractorName + " not found!");
+ LOG.error("BoilerpipeExtractor {} not found!", boilerpipeExtractorName);
} catch (InstantiationException e) {
- LOG.error("Could not instantiate " + boilerpipeExtractorName);
+ LOG.error("Could not instantiate {}", boilerpipeExtractorName);
} catch (Exception e) {
- LOG.error(e.getLocalizedMessage());
+ LOG.error(e.getMessage());
}
}
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
index 85cd1fae0..e75f70aef 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
@@ -151,7 +151,7 @@ public class TikaParser implements org.apache.nutch.parse.Parser {
parser.parse(new ByteArrayInputStream(raw),
(ContentHandler) teeContentHandler, tikamd, context);
} catch (Exception e) {
- LOG.error("Error parsing " + content.getUrl(), e);
+ LOG.error("Error parsing {}", content.getUrl(), e);
return new ParseStatus(ParseStatus.FAILED, e.getMessage())
.getEmptyParseResult(content.getUrl(), getConf());
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestHtmlParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestHtmlParser.java
index 781e8910a..e03622246 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestHtmlParser.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestHtmlParser.java
@@ -114,9 +114,9 @@ public class TestHtmlParser {
String title = parse.getData().getTitle();
String keywords = parse.getData().getMeta("keywords");
LOG.info(name);
- LOG.info("title:\t" + title);
- LOG.info("keywords:\t" + keywords);
- LOG.info("text:\t" + text);
+ LOG.info("title:\t{}", title);
+ LOG.info("keywords:\t{}", keywords);
+ LOG.info("text:\t{}", text);
Assert.assertEquals("Title not extracted properly (" + name + ")",
encodingTestKeywords, title);
for (String keyword : encodingTestKeywords.split(",\\s*")) {
diff --git a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java
index a605f3b0b..315f7e79b 100644
--- a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java
+++ b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java
@@ -66,9 +66,7 @@ public class ZipParser implements Parser {
final String contentLen = content.getMetadata().get(
Response.CONTENT_LENGTH);
final int len = Integer.parseInt(contentLen);
- if (LOG.isDebugEnabled()) {
- LOG.debug("ziplen: " + len);
- }
+ LOG.debug("ziplen: {}", len);
final byte[] contentInBytes = content.getContent();
if (contentLen != null && contentInBytes.length != len) {
@@ -103,9 +101,8 @@ public class ZipParser implements Parser {
final ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS,
resultTitle, outlinks, content.getMetadata());
- if (LOG.isTraceEnabled()) {
- LOG.trace("Zip file parsed sucessfully !!");
- }
+ LOG.trace("Zip file parsed sucessfully.");
+
return ParseResult.createParseResult(content.getUrl(), new ParseImpl(
resultText, parseData));
}
diff --git a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java
index 1e4e4f3ee..6265530b1 100644
--- a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java
+++ b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java
@@ -104,10 +104,7 @@ public class ZipTextExtractor {
resultText += entry.getName() + " " + parse.getText() + " ";
} catch (ParseException e) {
- if (LOG.isInfoEnabled()) {
- LOG.info("fetch okay, but can't parse " + fname + ", reason: "
- + e.getMessage());
- }
+ LOG.info("fetch okay, but can't parse {}, reason: {}", fname,e.getMessage());
}
}
}
diff --git a/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/NaiveBayesParseFilter.java b/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/NaiveBayesParseFilter.java
index 76821a280..2d222a7dc 100644
--- a/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/NaiveBayesParseFilter.java
+++ b/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/NaiveBayesParseFilter.java
@@ -63,8 +63,7 @@ public class NaiveBayesParseFilter implements HtmlParseFilter {
try {
return classify(text);
} catch (IOException e) {
- LOG.error("Error occured while classifying:: " + text + " ::"
- + StringUtils.stringifyException(e));
+ LOG.error("Error occured while classifying:: {} ::", text, e);
}
return false;
@@ -112,9 +111,7 @@ public class NaiveBayesParseFilter implements HtmlParseFilter {
if (inputFilePath == null || inputFilePath.trim().length() == 0
|| dictionaryFile == null || dictionaryFile.trim().length() == 0) {
String message = "ParseFilter: NaiveBayes: trainfile or wordlist not set in the parsefilte.naivebayes.trainfile or parsefilte.naivebayes.wordlist";
- if (LOG.isErrorEnabled()) {
- LOG.error(message);
- }
+ LOG.error(message);
throw new IllegalArgumentException(message);
}
try {
@@ -122,9 +119,7 @@ public class NaiveBayesParseFilter implements HtmlParseFilter {
|| (FileSystem.get(conf).exists(new Path(dictionaryFile)))) {
String message = "ParseFilter: NaiveBayes: " + inputFilePath + " or "
+ dictionaryFile + " not found!";
- if (LOG.isErrorEnabled()) {
- LOG.error(message);
- }
+ LOG.error(message);
throw new IllegalArgumentException(message);
}
@@ -144,8 +139,7 @@ public class NaiveBayesParseFilter implements HtmlParseFilter {
train();
} catch (Exception e) {
- LOG.error("Error occured while training:: "
- + StringUtils.stringifyException(e));
+ LOG.error("Error occured while training::", e);
}
@@ -169,13 +163,13 @@ public class NaiveBayesParseFilter implements HtmlParseFilter {
if (!filterParse(text)) { // kick in the second tier
// if parent page found
// irrelevant
- LOG.info("ParseFilter: NaiveBayes: Page found irrelevant:: " + url);
+ LOG.info("ParseFilter: NaiveBayes: Page found irrelevant:: {}", url);
LOG.info("Checking outlinks");
Outlink[] out = null;
for (int i = 0; i < parse.getData().getOutlinks().length; i++) {
- LOG.info("ParseFilter: NaiveBayes: Outlink to check:: "
- + parse.getData().getOutlinks()[i].getToUrl());
+ LOG.info("ParseFilter: NaiveBayes: Outlink to check:: {}",
+ parse.getData().getOutlinks()[i].getToUrl());
if (filterUrl(parse.getData().getOutlinks()[i].getToUrl())) {
tempOutlinks.add(parse.getData().getOutlinks()[i]);
LOG.info("ParseFilter: NaiveBayes: found relevant");
@@ -191,7 +185,7 @@ public class NaiveBayesParseFilter implements HtmlParseFilter {
parse.getData().setOutlinks(out);
} else {
- LOG.info("ParseFilter: NaiveBayes: Page found relevant:: " + url);
+ LOG.info("ParseFilter: NaiveBayes: Page found relevant:: {}", url);
}
return parseResult;
diff --git a/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java b/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
index cc3d12561..5eaf61b13 100644
--- a/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
+++ b/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
@@ -75,7 +75,7 @@ public class RegexParseFilter implements HtmlParseFilter {
}
if (source == null) {
- LOG.error("source for regex rule: " + field + " misconfigured");
+ LOG.error("source for regex rule {} misconfigured", field);
}
if (matches(source, regexRule.regex)) {
@@ -110,16 +110,11 @@ public class RegexParseFilter implements HtmlParseFilter {
}
if (attributeFile != null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Attribute \"file\" is defined for plugin " + pluginName
- + " as " + attributeFile);
- }
- }
- else {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin "
- + pluginName);
- }
+ LOG.info("Attribute \"file\" is defined for plugin {} as {}", pluginName,
+ attributeFile);
+ } else {
+ LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin {}",
+ pluginName);
}
String file = conf.get("parsefilter.regex.file", attributeFile);
@@ -174,7 +169,7 @@ public class RegexParseFilter implements HtmlParseFilter {
rules.put(field, new RegexRule(source, regex));
} else {
- LOG.info("RegexParseFilter rule is invalid. " + line);
+ LOG.info("RegexParseFilter rule is invalid: {}", line);
}
}
}
diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
index d55e42e44..e4d201069 100644
--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
@@ -139,9 +139,7 @@ public class File implements Protocol {
} else if (code >= 300 && code < 400) { // handle redirect
u = new URL(response.getHeader("Location"));
- if (LOG.isTraceEnabled()) {
- LOG.trace("redirect to " + u);
- }
+ LOG.trace("redirect to {}", u);
if (symlinksAsRedirects) {
return new ProtocolOutput(response.toContent(), new ProtocolStatus(
ProtocolStatus.MOVED, u));
diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java
index 803557fac..c50988c2d 100644
--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java
+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java
@@ -116,9 +116,7 @@ public class FileResponse {
if (!"file".equals(url.getProtocol()))
throw new FileException("Not a file url:" + url);
- if (File.LOG.isTraceEnabled()) {
- File.LOG.trace("fetching {}", url);
- }
+ File.LOG.trace("fetching {}", url);
if (url.getQuery() != null) {
File.LOG.warn(
@@ -221,9 +219,7 @@ public class FileResponse {
offset += n;
}
if (offset < len) { // keep whatever already have, but issue a warning
- if (File.LOG.isWarnEnabled()) {
- File.LOG.warn("not enough bytes read from file: " + f.getPath());
- }
+ File.LOG.warn("not enough bytes read from file: {}", f.getPath());
}
is.close();
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java
index 20289e70e..d6f7fd64a 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java
@@ -90,7 +90,7 @@ public class FtpResponse {
this.conf = conf;
if (!"ftp".equals(url.getProtocol()))
- throw new FtpException("Not a ftp url:" + url);
+ throw new FtpException("Not a ftp url: " + url);
if (url.getQuery() != null) {
Ftp.LOG.warn(
@@ -102,13 +102,9 @@ public class FtpResponse {
try {
if (ftp.followTalk) {
- if (Ftp.LOG.isInfoEnabled()) {
- Ftp.LOG.info("fetching " + url);
- }
+ Ftp.LOG.info("fetching {}", url);
} else {
- if (Ftp.LOG.isTraceEnabled()) {
- Ftp.LOG.trace("fetching " + url);
- }
+ Ftp.LOG.trace("fetching {}", url);
}
InetAddress addr = InetAddress.getByName(url.getHost());
@@ -120,15 +116,13 @@ public class FtpResponse {
// should start anew.
if (ftp.client != null && ftp.keepConnection
&& ftp.renewalTime < System.currentTimeMillis()) {
- if (Ftp.LOG.isInfoEnabled()) {
- Ftp.LOG.info("delete client because idled too long");
- }
+ Ftp.LOG.info("delete client because idled too long");
ftp.client = null;
}
// start anew if needed
if (ftp.client == null) {
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
+ if (ftp.followTalk) {
Ftp.LOG.info("start client");
}
// the real client
@@ -153,9 +147,9 @@ public class FtpResponse {
if (ftp.client.isConnected()) {
InetAddress remoteAddress = ftp.client.getRemoteAddress();
if (!addr.equals(remoteAddress)) {
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("disconnect from " + remoteAddress
- + " before connect to " + addr);
+ if (ftp.followTalk) {
+ Ftp.LOG.info("disconnect from {} before connect to {}",
+ remoteAddress, addr);
}
// quit from current site
ftp.client.logout();
@@ -166,23 +160,21 @@ public class FtpResponse {
// connect to current site if needed
if (!ftp.client.isConnected()) {
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("connect to " + addr);
+ if (ftp.followTalk) {
+ Ftp.LOG.info("connect to {}", addr);
}
ftp.client.connect(addr);
if (!FTPReply.isPositiveCompletion(ftp.client.getReplyCode())) {
ftp.client.disconnect();
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.client.connect() failed: " + addr + " "
- + ftp.client.getReplyString());
- }
+ Ftp.LOG.warn("ftp.client.connect() failed: {} {}", addr,
+ ftp.client.getReplyString());
this.code = 500; // http Internal Server Error
return;
}
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("log into " + addr);
+ if (ftp.followTalk) {
+ Ftp.LOG.info("log into {}", addr);
}
if (!ftp.client.login(ftp.userName, ftp.passWord)) {
@@ -192,9 +184,7 @@ public class FtpResponse {
// but throw exception, which then will be handled by caller
// (not dealt with here at all) .
ftp.client.disconnect();
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.client.login() failed: " + addr);
- }
+ Ftp.LOG.warn("ftp.client.login() failed: {}", addr);
this.code = 401; // http Unauthorized
return;
}
@@ -203,15 +193,13 @@ public class FtpResponse {
if (!ftp.client.setFileType(FTP.BINARY_FILE_TYPE)) {
ftp.client.logout();
ftp.client.disconnect();
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.client.setFileType() failed: " + addr);
- }
+ Ftp.LOG.warn("ftp.client.setFileType() failed: {}", addr);
this.code = 500; // http Internal Server Error
return;
}
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("set parser for " + addr);
+ if (ftp.followTalk) {
+ Ftp.LOG.info("set parser for {}", addr);
}
// SYST is valid only after login
@@ -224,25 +212,18 @@ public class FtpResponse {
ftp.parser = (new DefaultFTPFileEntryParserFactory())
.createFileEntryParser(parserKey);
} catch (FtpExceptionBadSystResponse e) {
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG
- .warn("ftp.client.getSystemName() failed: " + addr + " " + e);
- }
+ Ftp.LOG.warn("ftp.client.getSystemName() failed: {} ", addr, e);
ftp.parser = null;
} catch (ParserInitializationException e) {
// ParserInitializationException is RuntimeException defined in
// org.apache.commons.net.ftp.parser.ParserInitializationException
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("createFileEntryParser() failed. " + addr + " " + e);
- }
+ Ftp.LOG.warn("createFileEntryParser() failed: {} ", addr, e);
ftp.parser = null;
} finally {
if (ftp.parser == null) {
// do not log as severe, otherwise
// FetcherThread/RequestScheduler will abort
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("ftp.parser is null: " + addr);
- }
+ Ftp.LOG.warn("ftp.parser is null: {}", addr);
ftp.client.logout();
ftp.client.disconnect();
this.code = 500; // http Internal Server Error
@@ -251,7 +232,7 @@ public class FtpResponse {
}
} else {
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
+ if (ftp.followTalk) {
Ftp.LOG.info("use existing connection");
}
}
@@ -271,29 +252,27 @@ public class FtpResponse {
ftp.renewalTime = System.currentTimeMillis()
+ ((ftp.timeout < ftp.serverTimeout) ? ftp.timeout
: ftp.serverTimeout);
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("reset renewalTime to "
- + HttpDateFormat.toString(ftp.renewalTime));
+ if (ftp.followTalk) {
+ Ftp.LOG.info("reset renewalTime to {}",
+ HttpDateFormat.toString(ftp.renewalTime));
}
}
// getDirAsHttpResponse() or getFileAsHttpResponse() above
// may have deleted ftp.client
if (ftp.client != null && !ftp.keepConnection) {
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("disconnect from " + addr);
+ if (ftp.followTalk) {
+ Ftp.LOG.info("disconnect from {}", addr);
}
ftp.client.logout();
ftp.client.disconnect();
}
} catch (Exception e) {
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("Error: ", e);
- }
+ Ftp.LOG.warn("Error: ", e);
// for any un-foreseen exception (run time exception or not),
// do ultimate clean and leave ftp.client for garbage collection
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
+ if (ftp.followTalk) {
Ftp.LOG.info("delete client due to exception");
}
ftp.client = null;
@@ -350,9 +329,9 @@ public class FtpResponse {
// control connection is off, clean up
// ftp.client.disconnect();
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("delete client because server cut off control channel: "
- + e);
+ if (ftp.followTalk) {
+ Ftp.LOG.info("delete client because server cut off control channel: ",
+ e);
}
ftp.client = null;
@@ -360,11 +339,9 @@ public class FtpResponse {
// thrown by retrieveList() (not retrieveFile()) above,
if (os == null) { // indicating throwing by retrieveList()
// throw new FtpException("fail to get attibutes: "+path);
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG
- .warn("Please try larger maxContentLength for ftp.client.retrieveList(). "
- + e);
- }
+ Ftp.LOG.warn(
+ "Please try larger maxContentLength for ftp.client.retrieveList(). ",
+ e);
// in a way, this is our request fault
this.code = 400; // http Bad request
return;
@@ -405,11 +382,9 @@ public class FtpResponse {
} catch (FtpExceptionUnknownForcedDataClose e) {
// Please note control channel is still live.
// in a way, this is our request fault
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
- + "If this is acceptable, please modify Client.java accordingly. "
- + e);
- }
+ Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
+ + "If this is acceptable, please modify Client.java accordingly. ",
+ e);
this.code = 400; // http Bad Request
}
@@ -449,9 +424,9 @@ public class FtpResponse {
// control connection is off, clean up
// ftp.client.disconnect();
- if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
- Ftp.LOG.info("delete client because server cut off control channel: "
- + e);
+ if (ftp.followTalk) {
+ Ftp.LOG.info("delete client because server cut off control channel: ",
+ e);
}
ftp.client = null;
@@ -472,16 +447,12 @@ public class FtpResponse {
} catch (FtpExceptionUnknownForcedDataClose e) {
// Please note control channel is still live.
// in a way, this is our request fault
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
- + "If this is acceptable, please modify Client.java accordingly. "
- + e);
- }
+ Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
+ + "If this is acceptable, please modify Client.java accordingly. ",
+ e);
this.code = 400; // http Bad Request
} catch (FtpExceptionCanNotHaveDataConnection e) {
- if (Ftp.LOG.isWarnEnabled()) {
- Ftp.LOG.warn("" + e);
- }
+ Ftp.LOG.warn("{}", e);
this.code = 500; // http Iternal Server Error
}
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
index 45a3da450..33d11d5e7 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
@@ -86,8 +86,8 @@ public class FtpRobotRulesParser extends RobotRulesParser {
if (robotRules != null) {
return robotRules; // cached rule
- } else if (LOG.isTraceEnabled()) {
- LOG.trace("cache miss " + url);
+ } else {
+ LOG.trace("cache miss {}", url);
}
boolean cacheRule = true;
@@ -117,9 +117,7 @@ public class FtpRobotRulesParser extends RobotRulesParser {
robotRules = EMPTY_RULES; // use default rules
}
} catch (Throwable t) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Couldn't get robots.txt for " + url + ": " + t.toString());
- }
+ LOG.info("Couldn't get robots.txt for {}: {}", url, t.toString());
cacheRule = false; // try again later to fetch robots.txt
robotRules = EMPTY_RULES;
}
diff --git a/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java b/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java
index ae876e00f..3afcbb25c 100644
--- a/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java
+++ b/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java
@@ -197,9 +197,7 @@ public class HttpResponse implements Response {
String userAgent = http.getUserAgent();
if ((userAgent == null) || (userAgent.length() == 0)) {
- if (Http.LOG.isErrorEnabled()) {
- Http.LOG.error("User-agent is not set!");
- }
+ Http.LOG.error("User-agent is not set!");
} else {
reqStr.append("User-Agent: ");
reqStr.append(userAgent);
diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
index d53ae823a..377b784c5 100644
--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
@@ -90,9 +90,7 @@ public class HttpResponse implements Response {
throw new HttpException("Unknown scheme (not http/https) for url:" + url);
}
- if (Http.LOG.isTraceEnabled()) {
- Http.LOG.trace("fetching " + url);
- }
+ Http.LOG.trace("fetching {}", url);
String path = url.getFile();
if (!path.startsWith("/")) {
@@ -195,9 +193,7 @@ public class HttpResponse implements Response {
String userAgent = http.getUserAgent();
if ((userAgent == null) || (userAgent.length() == 0)) {
- if (Http.LOG.isErrorEnabled()) {
- Http.LOG.error("User-agent is not set!");
- }
+ Http.LOG.error("User-agent is not set!");
} else {
reqStr.append("User-Agent: ");
reqStr.append(userAgent);
@@ -315,9 +311,7 @@ public class HttpResponse implements Response {
} else if ("deflate".equals(contentEncoding)) {
content = http.processDeflateEncoded(content, url);
} else {
- if (Http.LOG.isTraceEnabled()) {
- Http.LOG.trace("fetched " + content.length + " bytes from " + url);
- }
+ Http.LOG.trace("fetched {} bytes from {}", content.length, url);
}
if (httpHeaders != null) {
httpHeaders.append("\r\n");
@@ -481,9 +475,7 @@ public class HttpResponse implements Response {
ByteArrayOutputStream out = new ByteArrayOutputStream(Http.BUFFER_SIZE);
while (true) {
- if (Http.LOG.isTraceEnabled()) {
- Http.LOG.trace("Http: starting chunk");
- }
+ Http.LOG.trace("Http: starting chunk");
readLine(in, line, false);
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java
index b6e3fa9c3..de834f5f6 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/DummySSLProtocolSocketFactory.java
@@ -64,9 +64,7 @@ public class DummySSLProtocolSocketFactory implements
new TrustManager[] { new DummyX509TrustManager(null) }, null);
return context;
} catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.getMessage(), e);
- }
+ LOG.error(e.getMessage(), e);
throw new HttpClientError(e.toString());
}
}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
index 894ce6ef8..ebeb652dd 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java
@@ -142,10 +142,8 @@ public class Http extends HttpBase {
try {
setCredentials();
} catch (Exception ex) {
- if (LOG.isErrorEnabled()) {
- LOG.error("Http ", ex);
- LOG.error("Could not read " + authFile + " : " + ex.getMessage());
- }
+ LOG.error("Http ", ex);
+ LOG.error("Could not read {}: {}", authFile, ex.getMessage());
}
}
@@ -282,10 +280,9 @@ public class Http extends HttpBase {
Element rootElement = doc.getDocumentElement();
if (!"auth-configuration".equals(rootElement.getTagName())) {
- if (LOG.isWarnEnabled())
- LOG.warn("Bad auth conf file: root element <"
- + rootElement.getTagName() + "> found in " + authFile
- + " - must be <auth-configuration>");
+ LOG.warn(
+ "Bad auth conf file: root element <{}> found in {} - must be <auth-configuration>",
+ rootElement.getTagName(), authFile);
}
// For each set of credentials
@@ -297,10 +294,9 @@ public class Http extends HttpBase {
Element credElement = (Element) credNode;
if (!"credentials".equals(credElement.getTagName())) {
- if (LOG.isWarnEnabled())
- LOG.warn("Bad auth conf file: Element <" + credElement.getTagName()
- + "> not recognized in " + authFile
- + " - expected <credentials>");
+ LOG.warn(
+ "Bad auth conf file: Element <{}> not recognized in {} - expected <credentials>",
+ credElement.getTagName(), authFile);
continue;
}
@@ -335,11 +331,9 @@ public class Http extends HttpBase {
defaultRealm = realm;
defaultScheme = scheme;
- if (LOG.isTraceEnabled()) {
- LOG.trace(
- "Credentials - username: " + username + "; set as default"
- + " for realm: " + realm + "; scheme: " + scheme);
- }
+ LOG.trace(
+ "Credentials - username: {}; set as default for realm: {}; scheme: {}",
+ username, realm, scheme);
} else if ("authscope".equals(scopeElement.getTagName())) {
@@ -361,17 +355,14 @@ public class Http extends HttpBase {
client.getState().setCredentials(authScope, credentials);
- if (LOG.isTraceEnabled()) {
- LOG.trace("Credentials - username: " + username
- + "; set for AuthScope - " + "host: " + host + "; port: "
- + port + "; realm: " + realm + "; scheme: " + scheme);
- }
+ LOG.trace(
+ "Credentials - username: {}; set for AuthScope - host: {}; port: {}; realm: {}; scheme: {}",
+ username, host, port, realm, scheme);
} else {
- if (LOG.isWarnEnabled())
- LOG.warn("Bad auth conf file: Element <"
- + scopeElement.getTagName() + "> not recognized in "
- + authFile + " - expected <authscope>");
+ LOG.warn(
+ "Bad auth conf file: Element <{}> not recognized in {} - expected <authscope>",
+ scopeElement.getTagName(), authFile);
}
}
is.close();
@@ -474,7 +465,7 @@ public class Http extends HttpBase {
if ("policy".equals(fieldElement.getTagName())) {
String policy = fieldElement.getTextContent();
formConfigurer.setCookiePolicy(policy);
- LOG.debug("cookie policy is " + policy);
+ LOG.debug("cookie policy is {}", policy);
}
}
}
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpFormAuthentication.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpFormAuthentication.java
index 966ab6522..a960094ca 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpFormAuthentication.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpFormAuthentication.java
@@ -124,18 +124,18 @@ public class HttpFormAuthentication {
post.addParameters(params.toArray(new NameValuePair[0]));
int rspCode = client.executeMethod(post);
if (LOG.isDebugEnabled()) {
- LOG.debug("rspCode: " + rspCode);
- LOG.debug("\nSending 'POST' request to URL : " + url);
+ LOG.debug("rspCode: {}", rspCode);
+ LOG.debug("\nSending 'POST' request to URL : {}", url);
- LOG.debug("Post parameters : " + params);
- LOG.debug("Response Code : " + rspCode);
+ LOG.debug("Post parameters : {}", params);
+ LOG.debug("Response Code : {}", rspCode);
for (Header header : post.getRequestHeaders()) {
- LOG.debug("Response headers : " + header);
+ LOG.debug("Response headers : {}", header);
}
}
String rst = IOUtils.toString(post.getResponseBodyAsStream(),
StandardCharsets.UTF_8);
- LOG.debug("login post result: " + rst);
+ LOG.debug("login post result: {}", rst);
} finally {
if (post != null) {
post.releaseConnection();
@@ -166,7 +166,7 @@ public class HttpFormAuthentication {
String policy = formConfigurer.getCookiePolicy();
Object p = FieldUtils.readDeclaredStaticField(CookiePolicy.class, policy);
if (null != p) {
- LOG.debug("reflection of cookie value: " + p.toString());
+ LOG.debug("reflection of cookie value: {}", p);
params.setParameter(HttpMethodParams.COOKIE_POLICY, p);
}
}
diff --git a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
index 16fe29180..9081f14b8 100644
--- a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
+++ b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
@@ -92,9 +92,7 @@ public class HttpResponse implements Response {
throw new HttpException("Unknown scheme (not http/https) for url:" + url);
}
- if (Http.LOG.isTraceEnabled()) {
- Http.LOG.trace("fetching " + url);
- }
+ Http.LOG.trace("fetching {}", url);
String path = "".equals(url.getFile()) ? "/" : url.getFile();
@@ -189,9 +187,7 @@ public class HttpResponse implements Response {
String userAgent = http.getUserAgent();
if ((userAgent == null) || (userAgent.length() == 0)) {
- if (Http.LOG.isErrorEnabled()) {
- Http.LOG.error("User-agent is not set!");
- }
+ Http.LOG.error("User-agent is not set!");
} else {
reqStr.append("User-Agent: ");
reqStr.append(userAgent);
@@ -381,13 +377,13 @@ public class HttpResponse implements Response {
| NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
- Http.LOG.info("Successfully loaded " + classToLoad);
+ Http.LOG.info("Successfully loaded {}", classToLoad);
} catch (ClassNotFoundException e) {
- Http.LOG.info("Unable to load Handler class for: " + handlerNames[i]);
+ Http.LOG.info("Unable to load Handler class for: {}", handlerNames[i]);
} catch (InstantiationException e) {
- Http.LOG.info("Unable to instantiate Handler: " + handlerNames[i]);
+ Http.LOG.info("Unable to instantiate Handler: {}", handlerNames[i]);
} catch (IllegalAccessException e) {
- Http.LOG.info("Illegal access with Handler: " + handlerNames[i]);
+ Http.LOG.info("Illegal access with Handler: {}", handlerNames[i]);
}
}
}
diff --git a/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java b/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java
index 750677374..ddfcf7241 100644
--- a/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java
+++ b/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java
@@ -184,9 +184,7 @@ public class HttpResponse implements Response {
String userAgent = http.getUserAgent();
if ((userAgent == null) || (userAgent.length() == 0)) {
- if (Http.LOG.isErrorEnabled()) {
- Http.LOG.error("User-agent is not set!");
- }
+ Http.LOG.error("User-agent is not set!");
} else {
reqStr.append("User-Agent: ");
reqStr.append(userAgent);
diff --git a/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java b/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java
index 6fdf9edd6..561bdca1f 100644
--- a/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java
+++ b/src/plugin/scoring-depth/src/java/org/apache/nutch/scoring/depth/DepthScoringFilter.java
@@ -94,7 +94,7 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
}
String depthString = parseData.getMeta(DEPTH_KEY);
if (depthString == null) {
- LOG.warn("Missing depth, removing all outlinks from url " + fromUrl);
+ LOG.warn("Missing depth, removing all outlinks from url {}", fromUrl);
targets.clear();
return adjust;
}
@@ -120,8 +120,8 @@ public class DepthScoringFilter extends Configured implements ScoringFilter {
}
if (curDepth >= curMaxDepth) {
// depth exceeded - throw away
- LOG.info("Depth limit (" + curMaxDepth
- + ") reached, ignoring outlinks for " + fromUrl);
+ LOG.info("Depth limit ({}) reached, ignoring outlinks for ", curMaxDepth,
+ fromUrl);
targets.clear();
return adjust;
}
diff --git a/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java b/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java
index 00e8c644b..4be4eca61 100644
--- a/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java
+++ b/src/plugin/subcollection/src/java/org/apache/nutch/collection/CollectionManager.java
@@ -69,9 +69,7 @@ public class CollectionManager extends Configured {
protected void init() {
try {
- if (LOG.isInfoEnabled()) {
- LOG.info("initializing CollectionManager");
- }
+ LOG.info("initializing CollectionManager");
// initialize known subcollections
configfile = getConf().getResource(
getConf().get("subcollections.config", DEFAULT_FILE_NAME));
@@ -80,9 +78,7 @@ public class CollectionManager extends Configured {
getConf().get("subcollections.config", DEFAULT_FILE_NAME));
parse(input);
} catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Error occured:" + e);
- }
+ LOG.warn("Error occured:", e);
}
}
@@ -93,9 +89,7 @@ public class CollectionManager extends Configured {
NodeList nodeList = collections
.getElementsByTagName(Subcollection.TAG_COLLECTION);
- if (LOG.isInfoEnabled()) {
- LOG.info("file has " + nodeList.getLength() + " elements");
- }
+ LOG.info("file has {} elements", nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Element scElem = (Element) nodeList.item(i);
@@ -103,7 +97,7 @@ public class CollectionManager extends Configured {
subCol.initialize(scElem);
collectionMap.put(subCol.name, subCol);
}
- } else if (LOG.isInfoEnabled()) {
+ } else {
LOG.info("Cannot find collections");
}
}
@@ -114,9 +108,7 @@ public class CollectionManager extends Configured {
CollectionManager impl = (CollectionManager) objectCache.getObject(key);
if (impl == null) {
try {
- if (LOG.isInfoEnabled()) {
- LOG.info("Instantiating CollectionManager");
- }
+ LOG.info("Instantiating CollectionManager");
impl = new CollectionManager(conf);
objectCache.setObject(key, impl);
} catch (Exception e) {
diff --git a/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java b/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
index e9ba6a8c6..4605e1045 100644
--- a/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
+++ b/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
@@ -145,7 +145,7 @@ public class DomainURLFilter implements URLFilter {
}
readConfiguration(reader);
} catch (IOException e) {
- LOG.error("Error reading " + pluginName + " rule file " + file, e);
+ LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
@@ -176,8 +176,7 @@ public class DomainURLFilter implements URLFilter {
} catch (Exception e) {
// if an error happens, allow the url to pass
- LOG.error("Could not apply filter on url: " + url + "\n"
- + org.apache.hadoop.util.StringUtils.stringifyException(e));
+ LOG.error("Could not apply filter on url: {}", url, e);
return null;
}
}
diff --git a/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java b/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java
index d61d59722..c034d0ca3 100644
--- a/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java
+++ b/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java
@@ -121,8 +121,7 @@ public class DomainDenylistURLFilter implements URLFilter {
}
if (attributeFile != null) {
- LOG.info("Attribute \"file\" is defined for plugin {} as {}", pluginName,
- attributeFile);
+ LOG.info("Attribute \"file\" is defined for plugin {} as {}", pluginName, attributeFile);
}
// precedence hierarchy for definition of filter rules
@@ -146,7 +145,7 @@ public class DomainDenylistURLFilter implements URLFilter {
}
readConfiguration(reader);
} catch (IOException e) {
- LOG.error("Error reading " + pluginName + " rule file " + file, e);
+ LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
@@ -175,8 +174,7 @@ public class DomainDenylistURLFilter implements URLFilter {
} catch (Exception e) {
// if an error happens, allow the url to pass
- LOG.error("Could not apply filter on url: " + url + "\n"
- + org.apache.hadoop.util.StringUtils.stringifyException(e));
+ LOG.error("Could not apply filter on url: {}", url, e);
return null;
}
}
diff --git a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
index ccba29c36..7e6e27fd0 100644
--- a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
+++ b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
@@ -162,7 +162,7 @@ public class PrefixURLFilter implements URLFilter {
try {
trie = readConfiguration(reader);
} catch (IOException e) {
- LOG.error("Error reading " + pluginName + " rule file " + file, e);
+ LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
}
diff --git a/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java b/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
index 5edf5fc38..293d7aa41 100644
--- a/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
+++ b/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
@@ -293,7 +293,7 @@ public class SuffixURLFilter implements URLFilter {
try {
readConfiguration(reader);
} catch (IOException e) {
- LOG.error("Error reading " + pluginName + " rule file " + file, e);
+ LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
diff --git a/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java b/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
index 7c55cd723..2342ced68 100644
--- a/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
+++ b/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
@@ -62,7 +62,7 @@ public class AjaxURLNormalizer implements URLNormalizer {
*/
@Override
public String normalize(String urlString, String scope) throws MalformedURLException {
- LOG.info(scope + " // " + urlString);
+ LOG.info("{} // {}", scope, urlString);
// When indexing, transform _escaped_fragment_ URL's to their #! counterpart
if (scope.equals(URLNormalizers.SCOPE_INDEXER) && urlString.contains(ESCAPED_URL_PART)) {
@@ -71,7 +71,7 @@ public class AjaxURLNormalizer implements URLNormalizer {
// Otherwise transform #! URL's to their _escaped_fragment_ counterpart
if (urlString.contains(AJAX_URL_PART)) {
- LOG.info(scope + " // " + normalizeHashedFragment(urlString));
+ LOG.info("{} // {}", scope, normalizeHashedFragment(urlString));
return normalizeHashedFragment(urlString);
}
diff --git a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
index b350af9a1..2123d8fa9 100644
--- a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
+++ b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
@@ -114,10 +114,8 @@ public class BasicURLNormalizer implements URLNormalizer {
) {
escapedCharacters[c] = true;
} else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Character {} ({}) not handled as escaped or unescaped", c,
- (char) c);
- }
+ LOG.debug("Character {} ({}) not handled as escaped or unescaped", c,
+ (char) c);
}
}
}
diff --git a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
index e0394befe..dee16ebf3 100644
--- a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
+++ b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
@@ -104,15 +104,11 @@ public class HostURLNormalizer implements URLNormalizer {
}
if (attributeFile != null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Attribute \"file\" is defined for plugin " + pluginName
- + " as " + attributeFile);
- }
+ LOG.info("Attribute \"file\" is defined for plugin {} as {}", pluginName,
+ attributeFile);
} else {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin "
- + pluginName);
- }
+ LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin {}",
+ pluginName);
}
// precedence hierarchy for definition of normalizer rules
@@ -135,7 +131,7 @@ public class HostURLNormalizer implements URLNormalizer {
}
readConfiguration(reader);
} catch (IOException e) {
- LOG.error("Error reading " + pluginName + " rule file " + file, e);
+ LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
diff --git a/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java b/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
index abe531291..63b3db33d 100644
--- a/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
+++ b/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
@@ -166,16 +166,12 @@ public class ProtocolURLNormalizer implements URLNormalizer {
}
if (attributeFile != null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Attribute \"file\" is defined for plugin " + pluginName
- + " as " + attributeFile);
- }
+ LOG.info("Attribute \"file\" is defined for plugin {} as {}", pluginName,
+ attributeFile);
}
else {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin "
- + pluginName);
- }
+ LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin {}",
+ pluginName);
}
// precedence hierarchy for definition of normalizer rules
@@ -201,7 +197,7 @@ public class ProtocolURLNormalizer implements URLNormalizer {
}
readConfiguration(reader);
} catch (IOException | IllegalArgumentException e) {
- LOG.error("Error reading " + pluginName + " rule file " + file, e);
+ LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
diff --git a/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java
index b1d087dd7..1d40d2b24 100644
--- a/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java
+++ b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java
@@ -147,7 +147,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
try {
rules = readConfiguration(reader);
} catch (Exception e) {
- LOG.warn("Couldn't read default config: " + e);
+ LOG.warn("Couldn't read default config: {}", e);
rules = EMPTY_RULES;
}
}
@@ -158,8 +158,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
void setConfiguration(Reader reader, String scope) {
List<Rule> rules = readConfiguration(reader);
getScopedRules().put(scope, rules);
- LOG.debug("Set config for scope '" + scope + "': " + rules.size()
- + " rules.");
+ LOG.debug("Set config for scope '{}': {} rules.", scope, rules.size());
}
/**
@@ -176,17 +175,17 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
// try to populate
String configFile = getConf().get("urlnormalizer.regex.file." + scope);
if (configFile != null) {
- LOG.debug("resource for scope '" + scope + "': " + configFile);
+ LOG.debug("resource for scope '{}': {}", scope, configFile);
try {
Reader reader = getConf().getConfResourceAsReader(configFile);
curRules = readConfiguration(reader);
scopedRules.put(scope, curRules);
} catch (Exception e) {
- LOG.warn("Couldn't load resource '" + configFile + "': " + e);
+ LOG.warn("Couldn't load resource '{}': {}", configFile, e.toString());
}
}
if (curRules == EMPTY_RULES || curRules == null) {
- LOG.info("can't find rules for scope '" + scope + "', using default");
+ LOG.info("can't find rules for scope '{}', using default", scope);
scopedRules.put(scope, EMPTY_RULES);
}
}
@@ -212,14 +211,12 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
/** Reads the configuration file and populates a List of Rules. */
private List<Rule> readConfigurationFile(String filename) {
- if (LOG.isInfoEnabled()) {
- LOG.info("loading " + filename);
- }
+ LOG.info("loading {}", filename);
try {
FileReader reader = new FileReader(filename);
return readConfiguration(reader);
} catch (Exception e) {
- LOG.error("Error loading rules from '" + filename + "': " + e);
+ LOG.error("Error loading rules from '{}':", filename, e);
return EMPTY_RULES;
}
}
@@ -232,8 +229,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(reader));
Element root = doc.getDocumentElement();
- if ((!"regex-normalize".equals(root.getTagName()))
- && (LOG.isErrorEnabled())) {
+ if (!"regex-normalize".equals(root.getTagName())) {
LOG.error("bad conf file: top-level element not <regex-normalize>");
}
NodeList regexes = root.getChildNodes();
@@ -242,7 +238,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
if (!(regexNode instanceof Element))
continue;
Element regex = (Element) regexNode;
- if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) {
+ if (!"regex".equals(regex.getTagName())) {
LOG.warn("bad conf file: element not <regex>");
}
NodeList fields = regex.getChildNodes();
@@ -266,10 +262,9 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
try {
rule.pattern = Pattern.compile(patternValue);
} catch (PatternSyntaxException e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("skipped rule: " + patternValue + " -> " + subValue
- + " : invalid regular expression pattern: " + e);
- }
+ LOG.error(
+ "skipped rule: {} -> {} : invalid regular expression pattern: ",
+ patternValue, subValue, e);
continue;
}
rule.substitution = subValue;
@@ -277,9 +272,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
}
}
} catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("error parsing conf file: " + e);
- }
+ LOG.error("Error parsing conf file: ", e);
return EMPTY_RULES;
}
if (rules.size() == 0)
diff --git a/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java b/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java
index 4952a1da4..250ad2527 100644
--- a/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java
+++ b/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java
@@ -73,7 +73,7 @@ public class TestRegexURLNormalizer {
NormalizedURL[] urls = readTestFile(cname);
testData.put(cname, urls);
} catch (Exception e) {
- LOG.warn("Could load config from '" + configs[i] + "': " + e.toString());
+ LOG.warn("Could load config from '{}': {}", configs[i], e.toString());
}
}
}
@@ -99,8 +99,8 @@ public class TestRegexURLNormalizer {
String url = urls[i].url;
String normalized = normalizer.normalize(urls[i].url, scope);
String expected = urls[i].expectedURL;
- LOG.info("scope: " + scope + " url: " + url + " | normalized: "
- + normalized + " | expected: " + expected);
+ LOG.info("scope: {} url: {} | normalized: {} | expected: {}", scope, url,
+ normalized, expected);
Assert.assertEquals(urls[i].expectedURL, normalized);
}
}
@@ -119,8 +119,8 @@ public class TestRegexURLNormalizer {
Assert.fail(e.toString());
}
stopWatch.stop();
- LOG.info("bench time (" + loops + ") "
- + (stopWatch.getTime(TimeUnit.MILLISECONDS)) + "ms");
+ LOG.info("bench time ({}) {}ms", loops,
+ stopWatch.getTime(TimeUnit.MILLISECONDS));
}
private static class NormalizedURL {
@@ -176,8 +176,7 @@ public class TestRegexURLNormalizer {
TestRegexURLNormalizer test = new TestRegexURLNormalizer();
NormalizedURL[] urls = (NormalizedURL[]) test.testData.get(scope);
if (urls == null) {
- LOG.warn("Missing test data for scope '" + scope
- + "', using default scope.");
+ LOG.warn("Missing test data for scope '{}', using default scope.", scope);
scope = URLNormalizers.SCOPE_DEFAULT;
urls = (NormalizedURL[]) test.testData.get(scope);
}
diff --git a/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java b/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
index 2da831041..724575324 100644
--- a/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
+++ b/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
@@ -114,16 +114,12 @@ public class SlashURLNormalizer implements URLNormalizer {
}
if (attributeFile != null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Attribute \"file\" is defined for plugin " + pluginName
- + " as " + attributeFile);
- }
+ LOG.info("Attribute \"file\" is defined for plugin {} as {}", pluginName,
+ attributeFile);
}
else {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin "
- + pluginName);
- }
+ LOG.warn("Attribute \"file\" is not defined in plugin.xml for plugin {}",
+ pluginName);
}
// precedence hierarchy for definition of normalizer rules
@@ -147,7 +143,7 @@ public class SlashURLNormalizer implements URLNormalizer {
readConfiguration(reader);
}
catch (IOException e) {
- LOG.error("Error reading " + pluginName + " rule file " + file, e);
+ LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
diff --git a/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java b/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
index 66fa5de54..c3dab2cee 100644
--- a/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
+++ b/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
@@ -206,9 +206,7 @@ public class ContinuousCrawlTestUtil extends TestCase {
schedule.initializeSchedule(dummyURL, dbDatum); // initialize fetchInterval
dbDatum.setFetchTime(now);
- LOG.info("Emulate a continuous crawl, launched every "
- + (interval / (FetchSchedule.SECONDS_PER_DAY * 1000)) + " day ("
- + (interval / 1000) + " seconds)");
+ LOG.info("Emulate a continuous crawl, launched every {} day ({} seconds)", (interval / (FetchSchedule.SECONDS_PER_DAY * 1000)), (interval / 1000));
long maxTime = (now + duration);
long nextTime = now;
long lastFetchTime = -1;
@@ -224,14 +222,13 @@ public class ContinuousCrawlTestUtil extends TestCase {
CrawlDatum afterShouldFetch = new CrawlDatum();
int errorCount = 0;
while (nextTime < maxTime) {
- LOG.info("check: " + new Date(nextTime));
+ LOG.info("check: {}", new Date(nextTime));
fetchDatum.set(dbDatum);
copyDbDatum.set(dbDatum);
if (schedule.shouldFetch(dummyURL, fetchDatum, nextTime)) {
- LOG.info("... fetching now (" + new Date(nextTime) + ")");
+ LOG.info("... fetching now ({})", new Date(nextTime));
if (lastFetchTime > -1) {
- LOG.info("(last fetch: " + new Date(lastFetchTime) + " = "
- + TimingUtil.elapsedTime(lastFetchTime, nextTime) + " ago)");
+ LOG.info("(last fetch: {} = {} ago)", new Date(lastFetchTime), TimingUtil.elapsedTime(lastFetchTime, nextTime));
}
lastFetchTime = nextTime;
afterShouldFetch.set(fetchDatum);
@@ -246,14 +243,13 @@ public class ContinuousCrawlTestUtil extends TestCase {
assertFalse("no CrawlDatum", 0 == res.size());
assertEquals("more than one CrawlDatum", 1, res.size());
if (!check(res.get(0))) {
- LOG.info("previously in CrawlDb: " + copyDbDatum);
- LOG.info("after shouldFetch(): " + afterShouldFetch);
- LOG.info("fetch: " + fetchDatum);
- LOG.warn("wrong result in CrawlDb: " + res.get(0));
+ LOG.info("previously in CrawlDb: {}", copyDbDatum);
+ LOG.info("after shouldFetch(): {}", afterShouldFetch);
+ LOG.info("fetch: {}", fetchDatum);
+ LOG.warn("wrong result in CrawlDb: {}", res.get(0));
if (++errorCount >= maxErrors) {
if (maxErrors > 0) {
- LOG.error("Max. number of errors " + maxErrors
- + " reached. Stopping.");
+ LOG.error("Max. number of errors {} reached. Stopping.", maxErrors);
}
return false;
} else {
diff --git a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
index b125aeb3f..9e96071a0 100644
--- a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
+++ b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
@@ -72,7 +72,7 @@ public class CrawlDBTestUtil {
*/
public static void createCrawlDb(Configuration conf, FileSystem fs,
Path crawldb, List<URLCrawlDatum> init) throws Exception {
- LOG.trace("* creating crawldb: " + crawldb);
+ LOG.trace("* creating crawldb: {}", crawldb);
Path dir = new Path(crawldb, CrawlDb.CURRENT_NAME);
Option wKeyOpt = MapFile.Writer.keyClass(Text.class);
org.apache.hadoop.io.SequenceFile.Writer.Option wValueOpt = SequenceFile.Writer.valueClass(CrawlDatum.class);
@@ -81,7 +81,7 @@ public class CrawlDBTestUtil {
Iterator<URLCrawlDatum> it = init.iterator();
while (it.hasNext()) {
URLCrawlDatum row = it.next();
- LOG.info("adding:" + row.url.toString());
+ LOG.info("adding:{}", row.url.toString());
writer.append(new Text(row.url), row.datum);
}
writer.close();
diff --git a/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java b/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
index 415008809..09863656d 100644
--- a/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
+++ b/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
@@ -77,12 +77,11 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
@Override
protected boolean check(CrawlDatum result) {
if (result.getRetriesSinceFetch() > retryMax) {
- LOG.warn("Retry counter > db.fetch.retry.max: " + result);
+ LOG.warn("Retry counter > db.fetch.retry.max: {}", result);
} else if (result.getRetriesSinceFetch() == Byte.MAX_VALUE) {
- LOG.warn("Retry counter max. value reached (overflow imminent): "
- + result);
+ LOG.warn("Retry counter max. value reached (overflow imminent): {}", result);
} else if (result.getRetriesSinceFetch() < 0) {
- LOG.error("Retry counter overflow: " + result);
+ LOG.error("Retry counter overflow: {}", result);
return false;
}
// use retry counter bound to this class (totalRetries)
@@ -90,17 +89,17 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
// in CrawlDatum could be reset (eg. NUTCH-578_v5.patch)
if (totalRetries < retryMax) {
if (result.getStatus() == STATUS_DB_UNFETCHED) {
- LOG.info("ok: " + result);
+ LOG.info("ok: {}", result);
result.getRetriesSinceFetch();
return true;
}
} else {
if (result.getStatus() == STATUS_DB_GONE) {
- LOG.info("ok: " + result);
+ LOG.info("ok: {}", result);
return true;
}
}
- LOG.warn("wrong: " + result);
+ LOG.warn("wrong: {}", result);
return false;
}
@@ -174,20 +173,20 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
long secondsUntilNextFetch = (result.getFetchTime() - fetchTime) / 1000L;
if (secondsUntilNextFetch < -1) {
// next fetch time is in the past (more than one second)
- LOG.error("Next fetch time is in the past: " + result);
+ LOG.error("Next fetch time is in the past: {}", result);
return false;
}
if (secondsUntilNextFetch < 60) {
// next fetch time is in less than one minute
// (critical: Nutch can hardly be so fast)
- LOG.error("Less then one minute until next fetch: " + result);
+ LOG.error("Less then one minute until next fetch: {}", result);
}
// Next fetch time should be within min. and max. (tolerance: 60 sec.)
if (secondsUntilNextFetch + 60 < minInterval
|| secondsUntilNextFetch - 60 > maxInterval) {
- LOG.error("Interval until next fetch time ("
- + TimingUtil.elapsedTime(fetchTime, result.getFetchTime())
- + ") is not within min. and max. interval: " + result);
+ LOG.error(
+ "Interval until next fetch time ({}) is not within min. and max. interval: {}",
+ TimingUtil.elapsedTime(fetchTime, result.getFetchTime()), result);
// TODO: is this a failure?
}
}
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java b/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
index 622fc9871..7fb83f601 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
@@ -117,18 +117,18 @@ public class TestCrawlDbMerger {
createCrawlDb(conf, fs, crawldb1, init1, cd1);
createCrawlDb(conf, fs, crawldb2, init2, cd2);
CrawlDbMerger merger = new CrawlDbMerger(conf);
- LOG.debug("* merging crawldbs to " + output);
+ LOG.debug("* merging crawldbs to {}", output);
merger.merge(output, new Path[] { crawldb1, crawldb2 }, false, false);
- LOG.debug("* reading crawldb: " + output);
+ LOG.debug("* reading crawldb: {}", output);
reader = new CrawlDbReader();
String crawlDb = output.toString();
Iterator<String> it = expected.keySet().iterator();
while (it.hasNext()) {
String url = it.next();
- LOG.debug("url=" + url);
+ LOG.debug("url={}", url);
CrawlDatum cd = expected.get(url);
CrawlDatum res = reader.get(crawlDb, url, conf);
- LOG.debug(" -> " + res);
+ LOG.debug(" -> {}", res);
System.out.println("url=" + url);
System.out.println(" cd " + cd);
System.out.println(" res " + res);
@@ -142,7 +142,7 @@ public class TestCrawlDbMerger {
private void createCrawlDb(Configuration config, FileSystem fs, Path crawldb,
TreeSet<String> init, CrawlDatum cd) throws Exception {
- LOG.debug("* creating crawldb: " + crawldb);
+ LOG.debug("* creating crawldb: {}", crawldb);
Path dir = new Path(crawldb, CrawlDb.CURRENT_NAME);
Option wKeyOpt = MapFile.Writer.keyClass(Text.class);
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java b/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
index 1c0d0a7f9..c6aac88f9 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
@@ -110,7 +110,7 @@ public class TestCrawlDbStates {
}
int retryMax = conf.getInt("db.fetch.retry.max", 3);
for (String sched : schedules) {
- LOG.info("Testing state transitions with " + sched);
+ LOG.info("Testing state transitions with {}", sched);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
FetchSchedule schedule = FetchScheduleFactory
.getFetchSchedule(conf);
@@ -150,8 +150,8 @@ public class TestCrawlDbStates {
: getStatusName(fromDbStatus));
String fetchStatusName = (fetchStatus == -1 ? "<only inlinks>"
: CrawlDatum.getStatusName(fetchStatus));
- LOG.info(fromDbStatusName + " + " + fetchStatusName + " => "
- + getStatusName(toDbStatus));
+ LOG.info("{} + {} => {}", fromDbStatusName, fetchStatusName,
+ getStatusName(toDbStatus));
List<CrawlDatum> values = new ArrayList<CrawlDatum>();
for (int l = 0; l <= 2; l++) { // number of additional in-links
CrawlDatum fetch = null;
@@ -210,7 +210,7 @@ public class TestCrawlDbStates {
new CrawlDbUpdateTestDriver<Injector.InjectReducer>(injector, conf);
ScoringFilters scfilters = new ScoringFilters(conf);
for (String sched : schedules) {
- LOG.info("Testing inject with " + sched);
+ LOG.info("Testing inject with {}", sched);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
FetchSchedule schedule = FetchScheduleFactory
.getFetchSchedule(conf);
@@ -226,11 +226,10 @@ public class TestCrawlDbStates {
schedule.initializeSchedule(CrawlDbUpdateUtil.dummyURL, fromDb);
values.add(fromDb);
}
- LOG.info("inject "
- + (fromDbStatus == -1 ? "<not in CrawlDb>" : CrawlDatum
- .getStatusName(fromDbStatus)) + " + "
- + getStatusName(STATUS_INJECTED) + " => "
- + getStatusName(toDbStatus));
+ LOG.info("inject {} + {} => {}",
+ (fromDbStatus == -1 ? "<not in CrawlDb>"
+ : CrawlDatum.getStatusName(fromDbStatus)),
+ getStatusName(STATUS_INJECTED), getStatusName(toDbStatus));
CrawlDatum injected = new CrawlDatum(STATUS_INJECTED, conf.getInt(
"db.fetch.interval.default", 2592000), 0.1f);
schedule.initializeSchedule(CrawlDbUpdateUtil.dummyURL, injected);
@@ -345,10 +344,10 @@ public class TestCrawlDbStates {
protected boolean check(CrawlDatum result) {
if (lastFetchTime > 0
&& (currFetchTime - lastFetchTime) > maxFetchInterval) {
- LOG.error("last effective fetch (HTTP 200, not HTTP 304), at "
- + new Date(lastFetchTime)
- + ", took place more than db.fetch.interval.max time, "
- + "segment containing fetched content may have been deleted");
+ LOG.error(
+ "last effective fetch (HTTP 200, not HTTP 304), at {}, took place more than db.fetch.interval.max time, "
+ + "segment containing fetched content may have been deleted",
+ new Date(lastFetchTime));
return false;
}
switch (result.getStatus()) {
@@ -360,24 +359,25 @@ public class TestCrawlDbStates {
&& result.getSignature() != null
&& SignatureComparator._compare(lastSignature,
result.getSignature()) != 0) {
- LOG.error("document has changed (signature changed) but state is still "
- + getStatusName(STATUS_DB_NOTMODIFIED));
+ LOG.error(
+ "document has changed (signature changed) but state is still {}",
+ getStatusName(STATUS_DB_NOTMODIFIED));
return false;
}
- LOG.info("ok: " + result);
+ LOG.info("ok: {}", result);
return checkModifiedTime(result, firstFetchTime);
}
LOG.warn("notmodified without previous fetch");
break;
case STATUS_DB_FETCHED:
if (previousDbState == STATUS_DB_UNFETCHED) {
- LOG.info("ok (first fetch): " + result);
+ LOG.info("ok (first fetch): {}", result);
return checkModifiedTime(result, firstFetchTime);
} else if (lastSignature != null
&& result.getSignature() != null
&& SignatureComparator._compare(lastSignature,
result.getSignature()) != 0) {
- LOG.info("ok (content changed): " + result);
+ LOG.info("ok (content changed): {}", result);
// expect modified time == now
return checkModifiedTime(result, currFetchTime);
} else {
@@ -394,15 +394,15 @@ public class TestCrawlDbStates {
if (schedule.getClass() == AdaptiveFetchSchedule.class) {
LOG.info("state set to unfetched by AdaptiveFetchSchedule");
if (result.getSignature() != null) {
- LOG.warn("must reset signature: " + result);
+ LOG.warn("must reset signature: {}", result);
return false;
}
- LOG.info("ok: " + result);
+ LOG.info("ok: {}", result);
firstFetchTime = 0;
return true;
}
}
- LOG.warn("wrong result: " + result);
+ LOG.warn("wrong result: {}", result);
return false;
}
@@ -411,8 +411,8 @@ public class TestCrawlDbStates {
if (modifiedTime == result.getModifiedTime()) {
return true;
}
- LOG.error("wrong modified time: " + new Date(result.getModifiedTime())
- + " (expected " + new Date(modifiedTime) + ")");
+ LOG.error("wrong modified time: {} (expected {})",
+ new Date(result.getModifiedTime()), new Date(modifiedTime));
return false;
}
@@ -466,8 +466,7 @@ public class TestCrawlDbStates {
httpCode = 304;
datum.setStatus(STATUS_FETCH_NOTMODIFIED);
}
- LOG.info("fetched with HTTP " + httpCode + " => "
- + getStatusName(datum.getStatus()));
+ LOG.info("fetched with HTTP {} => {}", httpCode, getStatusName(datum.getStatus()));
datum.setFetchTime(currentTime);
return datum;
}
@@ -533,7 +532,7 @@ public class TestCrawlDbStates {
Context context = CrawlDBTestUtil.createContext();
Configuration conf = context.getConfiguration();
for (String sched : schedules) {
- LOG.info("Testing reset signature with " + sched);
+ LOG.info("Testing reset signature with {}", sched);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
ContinuousCrawlTestUtil crawlUtil = new CrawlTestSignatureReset(context);
try {
@@ -569,8 +568,7 @@ public class TestCrawlDbStates {
} else {
fetchState = noContentStates[(counter % 6) / 2][0];
}
- LOG.info("Step " + counter + ": fetched with "
- + getStatusName(fetchState));
+ LOG.info("Step {}: fetched with {}", counter, getStatusName(fetchState));
datum.setStatus(fetchState);
return datum;
}
@@ -579,15 +577,13 @@ public class TestCrawlDbStates {
protected boolean check(CrawlDatum result) {
if (result.getStatus() == STATUS_DB_NOTMODIFIED
&& !(fetchState == STATUS_FETCH_SUCCESS || fetchState == STATUS_FETCH_NOTMODIFIED)) {
- LOG.error("Should never get into state "
- + getStatusName(STATUS_DB_NOTMODIFIED) + " from "
- + getStatusName(fetchState));
+ LOG.error("Should never get into state {} from {}",
+ getStatusName(STATUS_DB_NOTMODIFIED), getStatusName(fetchState));
return false;
}
if (result.getSignature() != null
&& !(result.getStatus() == STATUS_DB_FETCHED || result.getStatus() == STATUS_DB_NOTMODIFIED)) {
- LOG.error("Signature not reset in state "
- + getStatusName(result.getStatus()));
+ LOG.error("Signature not reset in state {}", getStatusName(result.getStatus()));
// ok here: since it's not the problem itself (the db_notmodified), but
// the reason for it
}
diff --git a/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java b/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
index 14fd05ea4..8e634c5b9 100644
--- a/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
+++ b/src/test/org/apache/nutch/crawl/TestLinkDbMerger.java
@@ -109,14 +109,14 @@ public class TestLinkDbMerger {
createLinkDb(conf, fs, linkdb1, init1);
createLinkDb(conf, fs, linkdb2, init2);
LinkDbMerger merger = new LinkDbMerger(conf);
- LOG.debug("* merging linkdbs to " + output);
+ LOG.debug("* merging linkdbs to {}", output);
merger.merge(output, new Path[] { linkdb1, linkdb2 }, false, false);
- LOG.debug("* reading linkdb: " + output);
+ LOG.debug("* reading linkdb: {}", output);
reader = new LinkDbReader(conf, output);
Iterator<String> it = expected.keySet().iterator();
while (it.hasNext()) {
String url = it.next();
- LOG.debug("url=" + url);
+ LOG.debug("url={}", url);
String[] vals = expected.get(url);
Inlinks inlinks = reader.getInlinks(new Text(url));
// may not be null
@@ -128,7 +128,7 @@ public class TestLinkDbMerger {
links.add(in.getFromUrl());
}
for (int i = 0; i < vals.length; i++) {
- LOG.debug(" -> " + vals[i]);
+ LOG.debug(" -> {}", vals[i]);
Assert.assertTrue(links.contains(vals[i]));
}
}
@@ -138,7 +138,7 @@ public class TestLinkDbMerger {
private void createLinkDb(Configuration config, FileSystem fs, Path linkdb,
TreeMap<String, String[]> init) throws Exception {
- LOG.debug("* creating linkdb: " + linkdb);
+ LOG.debug("* creating linkdb: {}", linkdb);
Path dir = new Path(linkdb, LinkDb.CURRENT_NAME);
Option wKeyOpt = MapFile.Writer.keyClass(Text.class);
diff --git a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
index ae6d6f81f..8cc4744a2 100644
--- a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
+++ b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
@@ -307,8 +307,8 @@ public class TestSegmentMergerCrawlDatums {
for (MapFile.Reader reader : readers) {
while (reader.next(key, value)) {
- LOG.info("Reading status for: " + key.toString() + " > "
- + CrawlDatum.getStatusName(value.getStatus()));
+ LOG.info("Reading status for: {} > {}", key.toString(),
+ CrawlDatum.getStatusName(value.getStatus()));
// Only consider fetch status
if (CrawlDatum.hasFetchStatus(value)
@@ -324,8 +324,8 @@ public class TestSegmentMergerCrawlDatums {
// Remove the test directory again
fs.delete(testDir, true);
- LOG.info("Final fetch status for: http://nutch.apache.org/ > "
- + CrawlDatum.getStatusName(finalStatus));
+ LOG.info("Final fetch status for: http://nutch.apache.org/ > {}",
+ CrawlDatum.getStatusName(finalStatus));
// Return the final status
return finalStatus;
@@ -375,7 +375,7 @@ public class TestSegmentMergerCrawlDatums {
protected void createSegment(Path segment, byte status, boolean fetch,
boolean redirect) throws Exception {
- LOG.info("\nSegment: " + segment.toString());
+ LOG.info("\nSegment: {}", segment.toString());
// The URL of our main record
String url = "http://nutch.apache.org/";
@@ -402,7 +402,7 @@ public class TestSegmentMergerCrawlDatums {
// linked datum when merging
if (redirect) {
// We're writing our our main record URL with status linked
- LOG.info(url + " > " + CrawlDatum.getStatusName(CrawlDatum.STATUS_LINKED));
+ LOG.info("{} > {}", url, CrawlDatum.getStatusName(CrawlDatum.STATUS_LINKED));
value = new CrawlDatum();
value.setStatus(CrawlDatum.STATUS_LINKED);
writer.append(new Text(url), value);
@@ -410,7 +410,7 @@ public class TestSegmentMergerCrawlDatums {
// Whether we're fetching now
if (fetch) {
- LOG.info(url + " > " + CrawlDatum.getStatusName(status));
+ LOG.info("{} > {}", url, CrawlDatum.getStatusName(status));
// Set the status
value.setStatus(status);
@@ -422,8 +422,7 @@ public class TestSegmentMergerCrawlDatums {
// Whether we're handing a redirect now
if (redirect) {
// And the redirect URL with redirect status, pointing to our main URL
- LOG.info(redirectUrl + " > "
- + CrawlDatum.getStatusName(CrawlDatum.STATUS_FETCH_REDIR_TEMP));
+ LOG.info("{} > {}", redirectUrl, CrawlDatum.getStatusName(CrawlDatum.STATUS_FETCH_REDIR_TEMP));
value.setStatus(CrawlDatum.STATUS_FETCH_REDIR_TEMP);
writer.append(new Text(redirectUrl), value);
}