Skip to content

Commit 2f9418f

Browse files
author
Maxim Moinat
committed
Added log4j logging
1 parent 9b1dae2 commit 2f9418f

File tree

5 files changed

+61
-26
lines changed

5 files changed

+61
-26
lines changed

Readme.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
To be run with:
1+
Run manually with:
22
```
33
hadoop jar restructurehdfs-all-0.1.0.jar webhdfs://radar-test.thehyve.net:50070 /topicAndroidPhoneNew/ output2
4+
```
5+
6+
Cron example, executing every hour (/etc/crontab):
7+
```
8+
00 * * * * root hadoop jar /home/maxim/hadoop-test/restructurehdfs-all-0.1.0.jar webhdfs://radar-test.thehyve.net:50070/ /udooE4Time/ /home/maxim/hadoop-test/outputCron > /home/maxim/hadoop-test/logCron.txt
49
```

build.gradle

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ repositories {
1212

1313
dependencies {
1414
testCompile group: 'junit', name: 'junit', version: '4.11'
15+
compile 'org.apache.logging.log4j:log4j-core:2.8.1'
1516
compile 'org.apache.hadoop:hadoop-common:2.7.3'
1617
runtime 'org.apache.hadoop:hadoop-hdfs:2.7.3'
1718
compile 'org.apache.avro:avro:1.7.7'
@@ -24,7 +25,7 @@ task fatJar(type: Jar) {
2425
manifest {
2526
attributes 'Implementation-Title': 'Gradle Jar File Example',
2627
'Implementation-Version': version,
27-
'Main-Class': 'org.radarcns.restructureAvroRecords'
28+
'Main-Class': 'org.radarcns.RestructureAvroRecords'
2829
}
2930
baseName = project.name + '-all'
3031
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }

src/main/java/org/radarcns/Frequency.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@
33
import org.apache.commons.collections.MapIterator;
44
import org.apache.commons.collections.keyvalue.MultiKey;
55
import org.apache.commons.collections.map.MultiKeyMap;
6+
import org.apache.logging.log4j.LogManager;
7+
import org.apache.logging.log4j.Logger;
68

79
import java.io.*;
810

911

1012
public class Frequency {
13+
private static final Logger logger = LogManager.getLogger(RestructureAvroRecords.class);
1114

1215
private MultiKeyMap bins = new MultiKeyMap();
1316
private String binFilePath;
@@ -31,7 +34,7 @@ public void addToBin(String topicName, String id, String timestamp, Integer coun
3134

3235
public void addToBin(String topicName, String id, Double time, Integer countToAdd) {
3336
// Hour resolution
34-
String hourlyTimestamp = restructureAvroRecords.createHourTimestamp(time);
37+
String hourlyTimestamp = RestructureAvroRecords.createHourTimestamp(time);
3538

3639
addToBin(topicName, id, hourlyTimestamp, countToAdd);
3740
}
@@ -91,9 +94,9 @@ private void addBinsFromFile() {
9194
this.addToBin(columns[0], columns[1], columns[2], Integer.valueOf(columns[3]));
9295
}
9396
} catch (IOException e) {
94-
System.out.println("Could not read the file with bins. Creating new file when writing.");
97+
logger.warn("Could not read the file with bins. Creating new file when writing.");
9598
} catch (ArrayIndexOutOfBoundsException e) {
96-
System.out.println("Unable to parse the contents of the bins file. Skipping reading.");
99+
logger.warn("Unable to parse the contents of the bins file. Skipping reading.");
97100
}
98101
}
99102
}

src/main/java/org/radarcns/restructureAvroRecords.java

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,15 @@
1111
import org.apache.hadoop.fs.LocatedFileStatus;
1212
import org.apache.hadoop.fs.Path;
1313
import org.apache.hadoop.fs.RemoteIterator;
14+
import org.apache.logging.log4j.LogManager;
15+
import org.apache.logging.log4j.Logger;
1416

1517
import java.io.*;
1618
import java.text.SimpleDateFormat;
1719
import java.util.*;
1820

19-
public class restructureAvroRecords {
21+
public class RestructureAvroRecords {
22+
private static final Logger logger = LogManager.getLogger(RestructureAvroRecords.class);
2023

2124
private final String OUTPUT_FILE_EXTENSION = "json";
2225
private final String OFFSETS_FILE_NAME = "offsets.csv";
@@ -34,23 +37,28 @@ public class restructureAvroRecords {
3437
private int processedRecordsCount;
3538

3639
public static void main(String [] args) throws Exception {
37-
restructureAvroRecords restr = new restructureAvroRecords(args[0], args[2]);
40+
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
41+
42+
logger.info(dateFormat.format(new Date()));
43+
logger.info("Starting...");
44+
logger.info("In: " + args[0] + args[1]);
45+
logger.info("Out: " + args[2]);
46+
3847
long time1 = System.currentTimeMillis();
48+
49+
RestructureAvroRecords restr = new RestructureAvroRecords(args[0], args[2]);
3950
restr.start(args[1]);
40-
System.out.printf("Processed %d files and %,d records\n", restr.getProcessedFileCount(), restr.getProcessedRecordsCount());
41-
System.out.printf("Time taken: %.2f seconds\n",(System.currentTimeMillis() - time1)/1000d);
4251

43-
// restructureAvroRecords restr = new restructureAvroRecords("webhdfs://radar-test.thehyve.net:50070", "output4/");
44-
// restr.start("/topicE4/");
52+
logger.info(String.format("Processed %d files and %,d records", restr.getProcessedFileCount(), restr.getProcessedRecordsCount()));
53+
logger.info(String.format("Time taken: %.2f seconds",(System.currentTimeMillis() - time1)/1000d));
4554

4655
// restr.processTopic(new Path("/topicE4/android_empatica_e4_temperature/"));
47-
// restr.processAvroFile(new Path("/testE4Time/android_phone_acceleration/partition=0/android_phone_acceleration+0+0000590000+0000599999.avro"),"wazaa" );
56+
// restr.processFile(new Path("/testE4Time/android_phone_acceleration/partition=0/android_phone_acceleration+0+0000590000+0000599999.avro"),"wazaa" );
4857
}
4958

50-
public restructureAvroRecords(String inputPath, String outputPath) {
59+
public RestructureAvroRecords(String inputPath, String outputPath) {
5160
this.setInputWebHdfsURL(inputPath);
5261
this.setOutputPath(outputPath);
53-
bins.setBinFilePath(outputPath + "/" + BINS_FILE_NAME);
5462
}
5563

5664
public void setInputWebHdfsURL(String fileSystemURL) {
@@ -61,6 +69,7 @@ public void setOutputPath(String path) {
6169
// Remove trailing backslash
6270
outputPath = path.replaceAll("/$","");
6371
offsetsPath = outputPath + "/" + OFFSETS_FILE_NAME;
72+
bins.setBinFilePath(outputPath + "/" + BINS_FILE_NAME);
6473
}
6574

6675
public int getProcessedFileCount() {
@@ -107,16 +116,16 @@ private void processTopic(Path topicPath) throws IOException {
107116
LocatedFileStatus locatedFileStatus = files.next();
108117

109118
if (locatedFileStatus.isFile())
110-
this.processAvroFile( locatedFileStatus.getPath(), topicName );
119+
this.processFile(locatedFileStatus.getPath(), topicName);
111120
}
112121
}
113122

114-
private void processAvroFile(Path filePath, String topicName) throws IOException {
123+
private void processFile(Path filePath, String topicName) throws IOException {
115124
String fileName = filePath.getName();
116125

117126
// Skip if extension is not .avro
118127
if (! FilenameUtils.getExtension(fileName).equals("avro")) {
119-
System.out.printf("Skipped non avro file: %s\n", fileName);
128+
logger.info("Skipped non-avro file: " + fileName);
120129
return;
121130
}
122131

@@ -125,11 +134,12 @@ private void processAvroFile(Path filePath, String topicName) throws IOException
125134
return;
126135
}
127136

128-
System.out.println(filePath);
137+
logger.info(filePath);
138+
129139
// Read and parse avro file
130140
FsInput input = new FsInput(filePath, conf);
131-
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>();
132-
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(input, datumReader);
141+
DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
142+
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(input, datumReader);
133143

134144
GenericRecord record = null;
135145
while (dataFileReader.hasNext()) {
@@ -176,9 +186,9 @@ private void appendToFile(String directoryName, String fileName, String data) {
176186
File directory = new File(directoryName);
177187
if (! directory.exists()){
178188
if (directory.mkdirs())
179-
System.out.printf("Created directory: %s\n", directory.getAbsolutePath());
189+
logger.info("Created directory: " + directory.getAbsolutePath());
180190
else
181-
System.out.printf("FAILED to create directory: %s\n", directory.getAbsolutePath());
191+
logger.warn("FAILED to create directory: " + directory.getAbsolutePath());
182192
}
183193

184194
String filePath = directoryName + "/" + fileName;
@@ -206,10 +216,10 @@ private void writeSeenOffsets(String fileName) {
206216
fromOffset = Integer.valueOf( fileNameParts[2] );
207217
toOffset = Integer.valueOf( fileNameParts[3] );
208218
} catch (IndexOutOfBoundsException e) {
209-
System.out.println("Could not split filename to the commit offsets.");
219+
logger.warn("Could not split filename to the commit offsets.");
210220
return;
211221
} catch (NumberFormatException e) {
212-
System.out.println("Could not convert offsets to integers.");
222+
logger.warn("Could not convert offsets to integers.");
213223
return;
214224
}
215225

@@ -236,9 +246,8 @@ private void readSeenOffsets() {
236246
String[] columns = line.split(",");
237247
seenFiles.add(columns[0]);
238248
}
239-
240249
} catch (IOException e) {
241-
System.out.println("No files processed yet.");
250+
logger.info("Offsets file does not exist yet, will be created.");
242251
}
243252
}
244253
}

src/main/resources/log4j2.xml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Configuration status="INFO">
3+
<Appenders>
4+
<Console name="Console" target="SYSTEM_OUT">
5+
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n" />
6+
</Console>
7+
<File name="MyFile" fileName="restructureAvroRecords.log" immediateFlush="true" append="true">
8+
<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n"/>
9+
</File>
10+
</Appenders>
11+
<Loggers>
12+
<Root level="debug">
13+
<AppenderRef ref="Console" />
14+
<AppenderRef ref="MyFile"/>
15+
</Root>
16+
</Loggers>
17+
</Configuration>

0 commit comments

Comments
 (0)