Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add %{{TIME_NOW}} pattern for sprintf #16906

Merged
merged 7 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/static/event-data.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,23 @@ These formats are not directly interchangeable, and we advise you to begin using

NOTE: A Logstash timestamp represents an instant on the UTC-timeline, so using sprintf formatters will produce results that may not align with your machine-local timezone.

You can generate a fresh timestamp by using `%{{TIME_NOW}}` syntax instead of relying on the value in `@timestamp`.
This is particularly useful when you need to estimate the time span of each plugin.

[source,js]
----------------------------------
input {
heartbeat {
add_field => { "heartbeat_time" => "%{{TIME_NOW}}" }
}
}
filter {
mutate {
add_field => { "mutate_time" => "%{{TIME_NOW}}" }
}
}
----------------------------------

[discrete]
[[conditionals]]
==== Conditionals
Expand Down
20 changes: 14 additions & 6 deletions logstash-core/src/main/java/org/logstash/StringInterpolation.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

public final class StringInterpolation {

private static final String TIME_NOW = "TIME_NOW";
private static final ThreadLocal<StringBuilder> STRING_BUILDER =
new ThreadLocal<StringBuilder>() {
@Override
Expand Down Expand Up @@ -83,13 +84,20 @@ public static String evaluate(final Event event, final String template) throws J
// JAVA-style @timestamp formatter:
// - `%{{yyyy-MM-dd}}` -> `2021-08-11`
// - `%{{YYYY-'W'ww}}` -> `2021-W32`
// A special pattern to generate a fresh current time
// - `%{{TIME_NOW}}` -> `2025-01-16T16:57:12.488955Z`
close = close + 1; // consume extra closing squiggle
final Timestamp t = event.getTimestamp();
if (t != null) {
final String javaTimeFormatPattern = template.substring(open+3, close-1);
final java.time.format.DateTimeFormatter javaDateTimeFormatter = DateTimeFormatter.ofPattern(javaTimeFormatPattern).withZone(ZoneOffset.UTC);
final String formattedTimestamp = javaDateTimeFormatter.format(t.toInstant());
builder.append(formattedTimestamp);
final String pattern = template.substring(open+3, close-1);
if (pattern.equals(TIME_NOW)) {
final Timestamp now = new Timestamp();
builder.append(now);
} else {
final Timestamp t = event.getTimestamp();
if (t != null) {
final DateTimeFormatter javaDateTimeFormatter = DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC);
final String formattedTimestamp = javaDateTimeFormatter.format(t.toInstant());
builder.append(formattedTimestamp);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe all this time related logic could be extracted in separate helper method.

}
} else if (template.charAt(open + 2) == '+') {
// JODA-style @timestamp formatter:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;


public class StringInterpolationTest extends RubyTestBase {
Expand Down Expand Up @@ -149,6 +151,24 @@ public void TestValueIsHash() throws IOException {
assertEquals("{\"k1\":\"v\"}", StringInterpolation.evaluate(event, path));
}

@Test
public void TestTimeNow() throws IOException {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know that the other test methods starts with capital letter, but in Java methods starts with lowercase.
I would also suggest to rename:

  • TestTimeNow -> testGivenAnEventWithTimeNowSubstitutionVariableWhenEvaluatedReplaceWithCurrentTimestamp
  • TestBadTimeNow -> testGivenAnEventWithASubstitutionVariableThatContainsTheTimeNowMarkerWhenEvaluatedNoReplacementWithCurrentTimestampHappen

Event event = getTestEvent();
String pattern = "%{{TIME_NOW}}";
Timestamp before = new Timestamp();
Timestamp result = new Timestamp(StringInterpolation.evaluate(event, pattern));
Timestamp after = new Timestamp();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Secondary note, that you could leave out: I know that it's hard two creation of Instant falls into the same nanosecond, but without a minimal sleep we can't grant that the Timestamps a monotonically increasing, they could result in same value.

assertTrue(before.compareTo(result) < 0);
assertTrue(after.compareTo(result) > 0);
}

@Test
public void TestBadTimeNow() throws IOException {
Event event = getTestEvent();
String pattern = "%{{BAD_TIME_NOW}}";
assertThrows(IllegalArgumentException.class, () -> StringInterpolation.evaluate(event, pattern));
}

public Event getTestEvent() {
Map<String, Object> data = new HashMap<>();
Map<String, String> inner = new HashMap<>();
Expand Down
Loading