Skip to content
Closed
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
@@ -0,0 +1,147 @@
/*
* 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.core.appender;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
import org.apache.logging.log4j.core.layout.JsonLayout;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.test.ListStatusListener;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.net.MalformedURLException;
import java.net.URL;

import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class HttpAppenderBuilderTest {

// Mock the LOGGER to verify error logs
private final StatusLogger mockStatusLogger = Mockito.mock(StatusLogger.class);

private HttpAppender.Builder<?> getBuilder() {
Configuration mockConfig = new DefaultConfiguration();
return HttpAppender.newBuilder()
.setConfiguration(mockConfig)
.setName("TestHttpAppender"); // Name is required
}

@Test
@UsingStatusListener
void testBuilderWithoutUrl(final ListStatusListener listener) throws Exception {
// Build the HttpAppender without URL
HttpAppender appender = HttpAppender.newBuilder()
.setConfiguration(new DefaultConfiguration())
.setName("TestAppender")
.setLayout(JsonLayout.createDefaultLayout()) // Providing a layout here
.build();

// Verify that the error message for missing URL is captured
assertThat(listener.findStatusData(Level.ERROR))
.anyMatch(statusData -> statusData.getMessage().getFormattedMessage().contains("HttpAppender requires URL to be set."));
}

@Test
@UsingStatusListener
void testBuilderWithUrlAndWithoutLayout(final ListStatusListener listener) throws Exception {
// Build the HttpAppender with URL but without Layout
HttpAppender appender = HttpAppender.newBuilder()
.setConfiguration(new DefaultConfiguration())
.setName("TestAppender")
.setUrl(new URL("http://localhost:8080/logs")) // Providing the URL
.build();

// Verify that the error message for missing layout is captured
assertThat(listener.findStatusData(Level.ERROR))
.anyMatch(statusData -> statusData.getMessage().getFormattedMessage().contains("HttpAppender requires a layout to be set."));
}


@Test
void testBuilderWithValidConfiguration() throws Exception {
URL url = new URL("http://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout(); // Valid layout

HttpAppender.Builder<?> builder = getBuilder()
.setUrl(url)
.setLayout(layout);

HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with valid configuration.");
}

@Test
void testBuilderWithCustomMethod() throws Exception {
URL url = new URL("http://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout();
String customMethod = "PUT";

HttpAppender.Builder<?> builder = getBuilder()
.setUrl(url)
.setLayout(layout)
.setMethod(customMethod);

HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with a custom HTTP method.");
}

@Test
void testBuilderWithHeaders() throws Exception {
URL url = new URL("http://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout();
Property[] headers = new Property[]{
Property.createProperty("Header1", "Value1"),
Property.createProperty("Header2", "Value2")
};

HttpAppender.Builder<?> builder = getBuilder()
.setUrl(url)
.setLayout(layout)
.setHeaders(headers);

HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with headers.");
}

@Test
void testBuilderWithSslConfiguration() throws Exception {
URL url = new URL("https://example.com");
Layout<?> layout = JsonLayout.createDefaultLayout();
SslConfiguration sslConfig = mock(SslConfiguration.class);

HttpAppender.Builder<?> builder = getBuilder()
.setUrl(url)
.setLayout(layout)
.setSslConfiguration(sslConfig);

HttpAppender appender = builder.build();
assertNotNull(appender, "HttpAppender should be created with SSL configuration.");
}

@Test
void testBuilderWithInvalidUrl() {
assertThrows(MalformedURLException.class, () -> new URL("invalid-url"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* 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.core.appender;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.spi.ExtendedLogger;
import org.apache.logging.log4j.core.script.ScriptRef; // Correct import for ScriptRef
import org.apache.logging.log4j.core.config.Configuration; // Import for Configuration
import org.junit.jupiter.api.Test;

@LoggerContextSource("log4j-script-ref-test.xml")
class ScriptConfigurationTest {

@Test
void testScriptRefConfiguration(final Configuration configuration) {
// Verify that the main Scripts element is initialized
assertNotNull(configuration.getScriptManager(), "ScriptManager should not be null");

// Verify a ScriptRef element is correctly resolved
ScriptRef scriptRef = (ScriptRef) configuration.getScriptManager().getScript("ExampleScriptRef");
assertNotNull(scriptRef, "ScriptRef should not be null");
assertThat(scriptRef.getLanguage(), containsString("groovy"));
assertThat(scriptRef.getScriptText(), containsString("return \"Hello, Log4j!\";"));

// Ensure that the script executes correctly
Object result = configuration.getScriptManager().execute("ExampleScriptRef", null);
assertNotNull(result, "Script execution result should not be null");
assertThat(result.toString(), containsString("Hello, Log4j!"));

// Verify that the console appender is initialized
final ConsoleAppender consoleAppender = (ConsoleAppender) configuration.getAppender("Console");
assertNotNull(consoleAppender, "Console appender should be initialized");

// Verify that the log messages are printed to the console
ExtendedLogger logger = configuration.getLoggerContext().getLogger(ScriptConfigurationTest.class);
logger.info("Test message");

// Capture console output (depending on test framework, this might need a mock or special handling)
// Check if the expected log message is printed in the console output
assertThat(consoleAppender.getLayout().toString(), containsString("Test message"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,30 @@ public void setup() {
rootLogger.getAttributes().put("level", "INFO");
loggers.getChildren().add(rootLogger);

if (map != null) {
// Add Properties Node only if the map is not null and has entries
if (map != null && !map.isEmpty()) {
final Node properties = newNode(rootNode, "Properties");
rootNode.getChildren().add(properties);

for (final Entry<String, String> entry : map.entrySet()) {
// Create Property node with "name" and "value" attributes
final Node property = newNode(properties, "Property");
property.getAttributes().put("name", entry.getKey());
property.getAttributes().put("value", entry.getValue());
properties.getChildren().add(property);
}
}

// Add a Scripts Node if required (Example for flexibility in testing)
final Node scripts = newNode(rootNode, "Scripts");
rootNode.getChildren().add(scripts);

// Add sample script node for testing purposes
final Node script = newNode(scripts, "Script");
script.getAttributes().put("name", "TestScript");
script.getAttributes().put("language", "JavaScript");
script.getAttributes().put("scriptText", "print('Hello, Log4j!');");
scripts.getChildren().add(script);
}

private Node newNode(final Node parent, final String name) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<Appenders>
<List name="List">
<PatternLayout pattern="[%-5level] %c{1.} %msg%n"/>

</List>
</Appenders>
<Loggers>
Expand Down
18 changes: 18 additions & 0 deletions log4j-core-test/src/test/resources/log4j-script-ref-test.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" name="TestConfig">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console" />
</Root>
</Loggers>
<Scripts>
<Script name="ExampleScriptRef" language="groovy">
return "Hello, Log4j!";
</Script>
</Scripts>
</Configuration>
Original file line number Diff line number Diff line change
@@ -1,19 +1,3 @@
/*
* 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.core.appender;

import java.io.Serializable;
Expand All @@ -32,16 +16,15 @@
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
import org.apache.logging.log4j.status.StatusLogger;

/**
* Sends log events over HTTP.
*/
@Plugin(name = "Http", category = Node.CATEGORY, elementType = Appender.ELEMENT_TYPE, printObject = true)
public final class HttpAppender extends AbstractAppender {

private static final StatusLogger LOGGER = StatusLogger.getLogger();

/**
* Builds HttpAppender instances.
* @param <B> The type to build
*/
public static class Builder<B extends Builder<B>> extends AbstractAppender.Builder<B>
implements org.apache.logging.log4j.core.util.Builder<HttpAppender> {
Expand Down Expand Up @@ -70,6 +53,18 @@ public static class Builder<B extends Builder<B>> extends AbstractAppender.Build

@Override
public HttpAppender build() {
// Validate URL presence
if (url == null) {
LOGGER.error("HttpAppender requires URL to be set.");
return null; // Return null if URL is missing
}

// Validate layout presence
if (getLayout() == null) {
LOGGER.error("HttpAppender requires a layout to be set.");
return null; // Return null if layout is missing
}

final HttpManager httpManager = new HttpURLConnectionManager(
getConfiguration(),
getConfiguration().getLoggerContext(),
Expand All @@ -81,10 +76,12 @@ public HttpAppender build() {
headers,
sslConfiguration,
verifyHostname);

return new HttpAppender(
getName(), getLayout(), getFilter(), isIgnoreExceptions(), httpManager, getPropertyArray());
}

// Getter and Setter methods
public URL getUrl() {
return url;
}
Expand Down Expand Up @@ -149,9 +146,6 @@ public B setVerifyHostname(final boolean verifyHostname) {
}
}

/**
* @return a builder for a HttpAppender.
*/
@PluginBuilderFactory
public static <B extends Builder<B>> B newBuilder() {
return new Builder<B>().asBuilder();
Expand Down
Loading