【发布时间】:2017-09-16 05:36:33
【问题描述】:
编辑:工作解决方案。下面是原始问题。
private Timestamp extractTimestamp(Object timestamp) {
try {
return Timestamp.from(Instant.ofEpochMilli(Long.valueOf(String.valueOf(timestamp))));
} catch(NumberFormatException e) {
System.out.println("Not in Epoch format");
}
try {
return Timestamp.from(Instant.parse(String.valueOf(timestamp)));
} catch(DateTimeParseException e) {
System.out.println("Not in UTC format");
}
try {
return Timestamp.valueOf(String.valueOf(timestamp));
} catch(IllegalArgumentException e) {
System.out.println("Not in SQL format");
}
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss Z");
Date date = formatter.parse(String.valueOf(timestamp));
return Timestamp.from(Instant.ofEpochMilli(date.getTime()));
} catch(ParseException e) {
System.out.println("Not in Apache Log format");
}
// Return current time if none found
return Timestamp.from(Instant.now());
}
我正在尝试从 Apache 访问日志中解析时间戳并将其转换为 Epoch 时间戳或 SQL 时间戳。我已经有代码可以从 epoch 转换为其他格式的 SQL 时间戳,所以我主要关心的是获取 Epoch 格式或任何其他易于转换的格式。我目前正在使用 Grok 模式,但是我正在寻找一种更有效的方法来提取时间。
下面是我正在提取的日志和时间戳的示例以及我当前的代码:
127.0.0.1 127.0.0.1 - - [04/Nov/2016:08:00:02 -0400] "GET /loc/ation" 200 163 "-" "-" 26 163 37526
04/Nov/2016:08:00:02 -0400
private Timestamp extractTimestamp(Object timestamp) {
try {
return Timestamp.from(Instant.ofEpochMilli(Long.valueOf(String.valueOf(timestamp))));
} catch(NumberFormatException e) {
System.out.println("Not in Epoch format");
}
try {
return Timestamp.from(Instant.parse(String.valueOf(timestamp)));
} catch(DateTimeParseException e) {
System.out.println("Not in UTC format");
}
try {
return Timestamp.valueOf(String.valueOf(timestamp));
} catch(IllegalArgumentException e) {
System.out.println("Not in SQL Time format");
}
try {
// Sample timestamp: 04/Nov/2016:08:00:02 -0400
String apacheLogExpression = "%{NUMBER:day}/%{WORD:month}/%{NUMBER:year}:%{NUMBER:hour}:%{NUMBER:minute}:%{NUMBER:second}\\s%{GREEDYDATA:offset}";
Grok compiledPattern = dictionary.compileExpression(apacheLogExpression);
Map<String, String> values = compiledPattern.extractNamedGroups(String.valueOf(timestamp));
System.out.println(values);
} catch(Exception e) {
System.out.println("Not in Apache Log format");
e.printStackTrace();
}
// Return current time if none found
return Timestamp.from(Instant.now());
}
提前感谢您的帮助!
【问题讨论】: