Skip to content

Improve configuration error handling of HttpAppender #3438

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 9 commits into from
Feb 16, 2025
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
@@ -0,0 +1,130 @@
/*
* 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.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.net.MalformedURLException;
import java.net.URL;
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.layout.JsonLayout;
import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
import org.apache.logging.log4j.test.ListStatusListener;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
import org.junit.jupiter.api.Test;

class HttpAppenderBuilderTest {

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 {
HttpAppender appender = HttpAppender.newBuilder()
.setConfiguration(new DefaultConfiguration())
.setName("TestAppender")
.setLayout(JsonLayout.createDefaultLayout()) // Providing a layout here
.build();

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 {
HttpAppender appender = HttpAppender.newBuilder()
.setConfiguration(new DefaultConfiguration())
.setName("TestAppender")
.setUrl(new URL("http://localhost:8080/logs"))
.build();

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();

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();

// Use real SslConfiguration instead of Mockito mock
SslConfiguration sslConfig = SslConfiguration.createSSLConfiguration(null, null, null, false);

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
Expand Up @@ -32,16 +32,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 +69,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 +92,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 +162,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
8 changes: 8 additions & 0 deletions src/changelog/.2.x.x/3011_http_appender_validation.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="3011" link="https://github.com/apache/logging-log4j2/issues/3011"/>
<description format="asciidoc">Improves validation of HTTP Appender.</description>
</entry>
Loading