Skip to content

Port date & time formatter rewrite to main #3150

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

Merged
merged 3 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ private static void writer(
private void verifyFile(final int count) throws Exception {
// String expected = "[\\w]* \\[\\s*\\] INFO TestLogger - Test$";
final String expected =
"^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} \\[[^\\]]*\\] INFO TestLogger - Test";
"^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{3} \\[[^\\]]*\\] INFO TestLogger - Test";
final Pattern pattern = Pattern.compile(expected);
int lines = 0;
try (final BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME)))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.time.internal.format.FastDateFormat;
import org.apache.logging.log4j.core.time.MutableInstant;
import org.apache.logging.log4j.core.util.internal.instant.InstantPatternFormatter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

Expand All @@ -46,7 +47,8 @@ public class OnStartupTriggeringPolicyTest {

private static final String TARGET_PATTERN = "/test1-%d{MM-dd-yyyy}-%i.log";
private static final String TEST_DATA = "Hello world!";
private static final FastDateFormat formatter = FastDateFormat.getInstance("MM-dd-yyyy");
private static final InstantPatternFormatter formatter =
InstantPatternFormatter.newBuilder().setPattern("MM-dd-yyyy").build();

@TempDir
Path tempDir;
Expand All @@ -56,7 +58,9 @@ public void testPolicy() throws Exception {
final Configuration configuration = new DefaultConfiguration();
final Path target = tempDir.resolve("testfile");
final long timeStamp = Instant.now().minus(Duration.ofDays(1)).toEpochMilli();
final String expectedDate = formatter.format(timeStamp);
final MutableInstant instant = new MutableInstant();
instant.initFromEpochMilli(timeStamp, 0);
final String expectedDate = formatter.format(instant);
final Path rolled = tempDir.resolve("test1-" + expectedDate + "-1.log");
final long copied;
try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes(StandardCharsets.UTF_8))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat.FixedFormat;
import org.apache.logging.log4j.test.junit.CleanUpDirectories;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -76,9 +74,7 @@ public void testAppender(final LoggerContext context) throws Exception {
assertTrue(files.length > 0, "Dir " + DIR + " should contain files");
for (final File file : files) {
final BasicFileAttributes fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
System.out.println(file + " (" + fileAttributes.size() + "B) "
+ FixedDateFormat.create(FixedFormat.ABSOLUTE)
.format(fileAttributes.lastModifiedTime().toMillis()));
System.out.println(file + " (" + fileAttributes.size() + "B) " + fileAttributes.lastModifiedTime());
}
final List<String> expected = List.of("my-1.log", "my-2.log", "my-3.log", "my-4.log", "my-5.log");
assertEquals(expected.size() + 6, files.length, Arrays.toString(files));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat.FixedFormat;
import org.apache.logging.log4j.test.junit.CleanUpDirectories;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -77,9 +75,7 @@ public void testAppender(final LoggerContext context) throws Exception {
assertTrue(files.length > 0, "Dir " + DIR + " should contain files");
for (final File file : files) {
final BasicFileAttributes fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
System.out.println(file + " (" + fileAttributes.size() + "B) "
+ FixedDateFormat.create(FixedFormat.ABSOLUTE)
.format(fileAttributes.lastModifiedTime().toMillis()));
System.out.println(file + " (" + fileAttributes.size() + "B) " + fileAttributes.lastModifiedTime());
}
// sometimes "test-9.log", sometimes "test-10.log" remains
final List<String> expected = List.of("my-1.log", "my-2.log", "my-3.log", "my-4.log", "my-5.log");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat.FixedFormat;
import org.apache.logging.log4j.test.junit.CleanUpDirectories;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -61,9 +59,7 @@ public void testAppender(final LoggerContext context) throws Exception {
assertTrue(files.length > 0, "Dir " + DIR + " should contain files");
for (final File file : files) {
final BasicFileAttributes fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
System.out.println(file + " (" + fileAttributes.size() + "B) "
+ FixedDateFormat.create(FixedFormat.ABSOLUTE)
.format(fileAttributes.lastModifiedTime().toMillis()));
System.out.println(file + " (" + fileAttributes.size() + "B) " + fileAttributes.lastModifiedTime());
}
assertEquals(4, files.length, Arrays.toString(files));
long total = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat.FixedFormat;
import org.apache.logging.log4j.test.junit.CleanUpDirectories;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -76,9 +74,7 @@ public void testAppender(final LoggerContext context) throws Exception {
assertTrue(files.length > 0, "Dir " + DIR + " should contain files");
for (final File file : files) {
final BasicFileAttributes fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
System.out.println(file + " (" + fileAttributes.size() + "B) "
+ FixedDateFormat.create(FixedFormat.ABSOLUTE)
.format(fileAttributes.lastModifiedTime().toMillis()));
System.out.println(file + " (" + fileAttributes.size() + "B) " + fileAttributes.lastModifiedTime());
}

final List<String> expected = Arrays.asList("my-1.log", "my-2.log", "my-3.log", "my-4.log", "my-5.log");
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,19 @@
*/
package org.apache.logging.log4j.core.layout;

import static org.apache.logging.log4j.core.time.internal.format.FixedDateFormat.FixedFormat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.AbstractLogEvent;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
Expand All @@ -45,7 +38,6 @@
import org.apache.logging.log4j.core.test.junit.ConfigurationFactoryType;
import org.apache.logging.log4j.core.time.Instant;
import org.apache.logging.log4j.core.time.MutableInstant;
import org.apache.logging.log4j.core.time.internal.format.FixedDateFormat;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.test.junit.UsingAnyThreadContext;
Expand Down Expand Up @@ -243,68 +235,7 @@ public void testLayoutWithDatePatternUnixMillis() {
assertEquals("<td>" + event.getTimeMillis() + "</td>", actual, "Incorrect date:" + actual);
}

@Test
public void testLayoutWithDatePatternFixedFormat() {
for (final String timeZone : new String[] {"GMT+8", "GMT+0530", "UTC", null}) {
for (final FixedDateFormat.FixedFormat format : FixedDateFormat.FixedFormat.values()) {
testLayoutWithDatePatternFixedFormat(format, timeZone);
}
}
}

private String getDateLine(final String logEventString) {
return logEventString.split(System.lineSeparator())[2];
}

private void testLayoutWithDatePatternFixedFormat(final FixedFormat format, final String timezone) {
final HtmlLayout layout = HtmlLayout.newBuilder()
.setConfiguration(new DefaultConfiguration())
.setDatePattern(format.name())
.setTimezone(timezone)
.build();

final LogEvent event = new MyLogEvent();
final String actual = getDateLine(layout.toSerializable(event));

// build expected date string
final java.time.Instant instant = java.time.Instant.ofEpochSecond(
event.getInstant().getEpochSecond(), event.getInstant().getNanoOfSecond());
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
if (timezone != null) {
zonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of(timezone));
}

// LOG4J2-3019 HtmlLayoutTest.testLayoutWithDatePatternFixedFormat test fails on windows
// https://issues.apache.org/jira/browse/LOG4J2-3019
// java.time.format.DateTimeFormatterBuilder.toFormatter() defaults to using
// Locale.getDefault(Locale.Category.FORMAT)
final Locale formatLocale = Locale.getDefault(Locale.Category.FORMAT);
final Locale locale = Locale.getDefault().equals(formatLocale) ? formatLocale : Locale.getDefault();

// For DateTimeFormatter of jdk,
// Pattern letter 'S' means fraction-of-second, 'n' means nano-of-second. Log4j2 needs S.
// Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero,
// whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'. Log4j2 needs x.
final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(
format.getPattern().replace('n', 'S').replace('X', 'x'), locale);
String expected = zonedDateTime.format(dateTimeFormatter);

final String offset = zonedDateTime.getOffset().toString();

// Truncate minutes if timeZone format is HH and timeZone has minutes. This is required because according to
// DateTimeFormatter,
// One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is
// also output, such as '+0130'
// ref : https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
if (FixedDateFormat.FixedTimeZoneFormat.HH.equals(format.getTimeZoneFormat())
&& offset.contains(":")
&& !"00".equals(offset.split(":")[1])) {
expected = expected.substring(0, expected.length() - 2);
}

assertEquals(
"<td>" + expected + "</td>",
actual,
MessageFormat.format("Incorrect date={0}, format={1}, timezone={2}", actual, format.name(), timezone));
}
}
Loading