gpt4 book ai didi

java - 将 Apache Log 时间转换为 Epoch 时间

转载 作者:行者123 更新时间:2023-12-02 13:22:53 26 4
gpt4 key购买 nike

编辑:工作解决方案。原始问题如下。

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 时间戳。我已经有代码可以从纪元转换为其他格式的 SQL 时间戳,因此我主要关心的是获取纪元格式或任何其他易于转换的格式。我目前正在使用 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/11/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());
}

预先感谢您的帮助!

最佳答案

    String logTime = "04/Nov/2016:08:00:02 -0400";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss Z");
Date date = formatter.parse(logTime);
System.out.println(date);

将打印 Fri Nov 04 14:00:02 EET 2016 并基本上获取 java.util.Date 对象

关于java - 将 Apache Log 时间转换为 Epoch 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com