Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 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 @@ -166,32 +166,36 @@ public String toSerializable(final LogEvent event) {
// so we generate the message first
final String message = messageLayout != null ? messageLayout.toSerializable(event)
: event.getMessage().getFormattedMessage();
final StringBuilder buf = getStringBuilder();

buf.append('<');
buf.append(Priority.getPriority(facility, event.getLevel()));
buf.append('>');

if (header) {
final int index = buf.length() + 4;
dateConverter.format(event, buf);
// RFC 3164 says leading space, not leading zero on days 1-9
if (buf.charAt(index) == '0') {
buf.setCharAt(index, Chars.SPACE);
final StringBuilder buf = acquireStringBuilder();

try {
buf.append('<');
buf.append(Priority.getPriority(facility, event.getLevel()));
buf.append('>');

if (header) {
final int index = buf.length() + 4;
dateConverter.format(event, buf);
// RFC 3164 says leading space, not leading zero on days 1-9
if (buf.charAt(index) == '0') {
buf.setCharAt(index, Chars.SPACE);
}

buf.append(Chars.SPACE);
buf.append(localHostname);
buf.append(Chars.SPACE);
}

buf.append(Chars.SPACE);
buf.append(localHostname);
buf.append(Chars.SPACE);
}
if (facilityPrinting) {
buf.append(facility != null ? facility.name().toLowerCase() : "user").append(':');
}

if (facilityPrinting) {
buf.append(facility != null ? facility.name().toLowerCase() : "user").append(':');
buf.append(message);
// TODO: splitting message into 1024 byte chunks?
return buf.toString();
} finally {
releaseStringBuilder(buf);
}

buf.append(message);
// TODO: splitting message into 1024 byte chunks?
return buf.toString();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@
*/
package org.apache.log4j.layout;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.layout.AbstractStringLayout;
Expand All @@ -28,12 +34,6 @@
import org.apache.logging.log4j.util.ReadOnlyStringMap;
import org.apache.logging.log4j.util.Strings;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
* Port of XMLLayout in Log4j 1.x. Provided for compatibility with existing Log4j 1 configurations.
*
Expand Down Expand Up @@ -75,16 +75,24 @@ public boolean isProperties() {

@Override
public void encode(final LogEvent event, final ByteBufferDestination destination) {
final StringBuilder text = getStringBuilder();
formatTo(event, text);
getStringBuilderEncoder().encode(text, destination);
final StringBuilder text = acquireStringBuilder();
try {
formatTo(event, text);
getStringBuilderEncoder().encode(text, destination);
} finally {
releaseStringBuilder(text);
}
}

@Override
public String toSerializable(final LogEvent event) {
final StringBuilder text = getStringBuilder();
formatTo(event, text);
return text.toString();
final StringBuilder text = acquireStringBuilder();
try {
formatTo(event, text);
return text.toString();
} finally {
releaseStringBuilder(text);
}
}

private void formatTo(final LogEvent event, final StringBuilder buf) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
*/
package org.apache.logging.log4j.message;

import org.apache.logging.log4j.spi.ThreadLocalRecyclerFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;
Expand All @@ -25,35 +27,39 @@
*/
public class ReusableMessageFactoryTest {

private ReusableMessageFactory factory;

@BeforeEach
void setUp() {
factory = new ReusableMessageFactory(ThreadLocalRecyclerFactory.getInstance());
}

@Test
public void testCreateEventReturnsDifferentInstanceIfNotReleased() throws Exception {
final ReusableMessageFactory factory = new ReusableMessageFactory();
final Message message1 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 1, 2, 3, 4);
final Message message2 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 9, 8, 7, 6);
assertNotSame(message1, message2);
ReusableMessageFactory.release(message1);
ReusableMessageFactory.release(message2);
factory.recycle(message1);
factory.recycle(message2);
}

@Test
public void testCreateEventReturnsSameInstance() throws Exception {
final ReusableMessageFactory factory = new ReusableMessageFactory();
final Message message1 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 1, 2, 3, 4);

ReusableMessageFactory.release(message1);
factory.recycle(message1);
final Message message2 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 9, 8, 7, 6);
assertSame(message1, message2);

ReusableMessageFactory.release(message2);
factory.recycle(message2);
final Message message3 = factory.newMessage("text, AAA={} BBB={} p2={} p3={}", 9, 8, 7, 6);
assertSame(message2, message3);
ReusableMessageFactory.release(message3);
factory.recycle(message3);
}

private void assertReusableParameterizeMessage(final Message message, final String txt, final Object[] params) {
assertTrue(message instanceof ReusableParameterizedMessage);
final ReusableParameterizedMessage msg = (ReusableParameterizedMessage) message;
assertTrue(msg.reserved, "reserved");

assertEquals(txt, msg.getFormat());
assertEquals(msg.getParameterCount(), params.length, "count");
Expand All @@ -65,7 +71,6 @@ private void assertReusableParameterizeMessage(final Message message, final Stri

@Test
public void testCreateEventOverwritesFields() throws Exception {
final ReusableMessageFactory factory = new ReusableMessageFactory();
final Message message1 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 1, 2, 3, 4);
assertReusableParameterizeMessage(message1, "text, p0={} p1={} p2={} p3={}", new Object[]{
new Integer(1), //
Expand All @@ -74,7 +79,7 @@ public void testCreateEventOverwritesFields() throws Exception {
new Integer(4), //
});

ReusableMessageFactory.release(message1);
factory.recycle(message1);
final Message message2 = factory.newMessage("other, A={} B={} C={} D={}", 1, 2, 3, 4);
assertReusableParameterizeMessage(message1, "other, A={} B={} C={} D={}", new Object[]{
new Integer(1), //
Expand All @@ -83,12 +88,11 @@ public void testCreateEventOverwritesFields() throws Exception {
new Integer(4), //
});
assertSame(message1, message2);
ReusableMessageFactory.release(message2);
factory.recycle(message2);
}

@Test
public void testCreateEventReturnsThreadLocalInstance() throws Exception {
final ReusableMessageFactory factory = new ReusableMessageFactory();
final Message[] message1 = new Message[1];
final Message[] message2 = new Message[1];
final Thread t1 = new Thread("THREAD 1") {
Expand Down Expand Up @@ -123,8 +127,8 @@ public void run() {
new Integer(3), //
new Integer(4), //
});
ReusableMessageFactory.release(message1[0]);
ReusableMessageFactory.release(message2[0]);
factory.recycle(message1[0]);
factory.recycle(message2[0]);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.spi;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class ThreadLocalRecyclerFactoryTest {
@Test
void nestedAcquiresDoNotInterfere() {
final Recycler<AtomicInteger> r = ThreadLocalRecyclerFactory.getInstance()
.create(AtomicInteger::new, i -> i.set(0));
final var recycler = (ThreadLocalRecyclerFactory.ThreadLocalRecycler<AtomicInteger>) r;

assertThat(recycler.getQueue()).isEmpty();
final AtomicInteger first = recycler.acquire();
assertThat(recycler.getQueue()).isEmpty();
final AtomicInteger second = recycler.acquire();
assertThat(recycler.getQueue()).isEmpty();
first.set(1);
second.set(2);
final AtomicInteger third = recycler.acquire();
assertThat(recycler.getQueue()).isEmpty();
assertThat(third.get()).isEqualTo(0);
assertThat(first.get()).isEqualTo(1);
assertThat(second.get()).isEqualTo(2);
recycler.release(first);
assertThat(recycler.getQueue()).hasSize(1);
recycler.release(second);
assertThat(recycler.getQueue()).hasSize(2);
recycler.release(third);
assertThat(recycler.getQueue()).hasSize(3);
}
}
9 changes: 5 additions & 4 deletions log4j-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@
<artifactId>org.osgi.resource</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jctools</groupId>
<artifactId>jctools-core</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
Expand All @@ -52,10 +57,6 @@
<configuration>
<instructions>
<Export-Package>org.apache.logging.log4j.*</Export-Package>
<Import-Package>
sun.reflect;resolution:=optional,
*
</Import-Package>
<Bundle-Activator>org.apache.logging.log4j.util.Activator</Bundle-Activator>
<_fixupmessages>"Classes found in the wrong directory";is:=warning</_fixupmessages>
</instructions>
Expand Down
4 changes: 4 additions & 0 deletions log4j-api/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@
exports org.apache.logging.log4j.status;
exports org.apache.logging.log4j.util;

// optional support for formatting SQL date/time classes in messages properly
requires static java.sql;
// optional support for running in an OSGi environment
requires static org.osgi.framework;
// optional support for using JCTools in a Recycler
requires static org.jctools.core;
uses org.apache.logging.log4j.spi.Provider;
uses PropertySource;
uses org.apache.logging.log4j.message.ThreadDumpMessage.ThreadInfoFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

/**
* Creates messages. Implementations can provide different message format syntaxes.
* If messages created by an implementation are reusable, then the {@link #recycle(Message)} method must
* be implemented and consistently used for returning objects to be reused.
*
* @see ParameterizedMessageFactory
* @see StringFormatterMessageFactory
Expand Down Expand Up @@ -236,4 +238,16 @@ default Message newMessage(final String message, final Object p0, final Object p
final Object p6, final Object p7, final Object p8, final Object p9) {
return newMessage(message, new Object[] { p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 });
}

/**
* Recycles a message back for potential reuse or cleanup.
*
* @since 3.0.0
* @see org.apache.logging.log4j.spi.Recycler
*/
default void recycle(Message message) {
if (message instanceof ReusableMessage) {
((ReusableMessage) message).clear();
}
}
}
Loading