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
Expand Up @@ -58,8 +58,10 @@
import org.springframework.boot.logging.LoggingInitializationContext;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.LoggingSystemFactory;
import org.springframework.boot.logging.LoggingSystemProperties;
import org.springframework.core.Conventions;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
Expand Down Expand Up @@ -128,6 +130,11 @@ public class Log4J2LoggingSystem extends AbstractLoggingSystem {
this.loggerContext = loggerContext;
}

@Override
public LoggingSystemProperties getSystemProperties(ConfigurableEnvironment environment) {
return new Log4J2LoggingSystemProperties(environment, getDefaultValueResolver(environment), null);
}

@Override
protected String[] getStandardConfigLocations() {
// With Log4J2 we use the ConfigurationFactory
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@

package org.springframework.boot.logging.log4j2;

import java.util.function.BiConsumer;
import java.util.function.Function;

import org.jspecify.annotations.Nullable;

import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LoggingSystemProperties;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import org.springframework.util.unit.DataSize;

/**
* {@link Log4J2LoggingSystemProperties} for Log4j2.
*
* @see Log4J2RollingPolicySystemProperty
* @author Andrey Timonin
* @since 4.1.0
*/
public class Log4J2LoggingSystemProperties extends LoggingSystemProperties {

public Log4J2LoggingSystemProperties(Environment environment) {
super(environment);
}

/**
* Create a new {@link Log4J2LoggingSystemProperties} instance.
* @param environment the source environment
* @param setter setter used to apply the property
*/
public Log4J2LoggingSystemProperties(Environment environment,
@Nullable BiConsumer<String, @Nullable String> setter) {
super(environment, setter);
}

/**
* Create a new {@link Log4J2LoggingSystemProperties} instance.
* @param environment the source environment
* @param defaultValueResolver function used to resolve default values or {@code null}
* @param setter setter used to apply the property or {@code null} for system
* properties
*/
public Log4J2LoggingSystemProperties(Environment environment,
@Nullable Function<@Nullable String, @Nullable String> defaultValueResolver,
@Nullable BiConsumer<String, @Nullable String> setter) {
super(environment, defaultValueResolver, setter);
}

@Override
protected void apply(@Nullable LogFile logFile, PropertyResolver resolver) {
super.apply(logFile, resolver);
applyRollingPolicyProperties(resolver);
}

private void applyRollingPolicyProperties(PropertyResolver resolver) {
applyRollingPolicy(Log4J2RollingPolicySystemProperty.FILE_NAME_PATTERN, resolver);
applyRollingPolicy(Log4J2RollingPolicySystemProperty.MAX_FILE_SIZE, resolver, DataSize.class);
applyRollingPolicy(Log4J2RollingPolicySystemProperty.TOTAL_SIZE_CAP, resolver, DataSize.class);
applyRollingPolicy(Log4J2RollingPolicySystemProperty.MAX_HISTORY, resolver);
}

private void applyRollingPolicy(Log4J2RollingPolicySystemProperty property, PropertyResolver resolver) {
applyRollingPolicy(property, resolver, String.class);
}

private <T> void applyRollingPolicy(Log4J2RollingPolicySystemProperty property, PropertyResolver resolver,
Class<T> type) {
T value = getProperty(resolver, property.getApplicationPropertyName(), type);
if (value != null) {
String stringValue = String.valueOf((value instanceof DataSize dataSize) ? dataSize.toBytes() : value);
setSystemProperty(property.getEnvironmentVariableName(), stringValue);
}
}

@SuppressWarnings("unchecked")
private <T> @Nullable T getProperty(PropertyResolver resolver, String key, Class<T> type) {
try {
return resolver.getProperty(key, type);
}
catch (ConversionFailedException | ConverterNotFoundException ex) {
if (type != DataSize.class) {
throw ex;
}
String value = resolver.getProperty(key);
return (T) DataSize.parse(value);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

package org.springframework.boot.logging.log4j2;

/**
* Log4j2 rolling policy system properties that can later be used by log configuration
* files.
*
* @see Log4J2LoggingSystemProperties
* @author Andrey Timonin
* @since 4.1.0
*/
public enum Log4J2RollingPolicySystemProperty {

/**
* Logging system property for the rolled-over log file name pattern.
*/
FILE_NAME_PATTERN("file-name-pattern"),

/**
* Logging system property for the file log max size.
*/
MAX_FILE_SIZE("max-file-size"),

/**
* Logging system property for the file total size cap.
*/
TOTAL_SIZE_CAP("total-size-cap"),

/**
* Logging system property for the file log max history.
*/
MAX_HISTORY("max-history");

private final String environmentVariableName;

private final String applicationPropertyName;

Log4J2RollingPolicySystemProperty(String applicationPropertyName) {
this.environmentVariableName = "LOG4J2_ROLLINGPOLICY_" + name();
this.applicationPropertyName = "logging.log4j2.rollingpolicy." + applicationPropertyName;
}

/**
* Return the name of environment variable that can be used to access this property.
* @return the environment variable name
*/
public String getEnvironmentVariableName() {
return this.environmentVariableName;
}

String getApplicationPropertyName() {
return this.applicationPropertyName;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<ThresholdFilter level="${sys:CONSOLE_LOG_THRESHOLD:-TRACE}"/>
</Filters>
</Console>
<RollingFile name="File" fileName="${sys:LOG_FILE}" filePattern="${sys:LOG_PATH}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
<RollingFile name="File" fileName="${sys:LOG_FILE}" filePattern="${sys:LOG4J2_ROLLINGPOLICY_FILE_NAME_PATTERN:-${sys:LOG_PATH}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz}">
<Select>
<SystemPropertyArbiter propertyName="FILE_LOG_STRUCTURED_FORMAT">
<StructuredLogLayout format="${sys:FILE_LOG_STRUCTURED_FORMAT}" charset="${sys:FILE_LOG_CHARSET}"/>
Expand All @@ -34,8 +34,14 @@
<ThresholdFilter level="${sys:FILE_LOG_THRESHOLD:-TRACE}"/>
</Filters>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB"/>
<SizeBasedTriggeringPolicy size="${sys:LOG4J2_ROLLINGPOLICY_MAX_FILE_SIZE:-10 MB}"/>
</Policies>
<DefaultRolloverStrategy max="${sys:LOG4J2_ROLLINGPOLICY_MAX_HISTORY:-7}">
<Delete basePath="${sys:LOG_PATH}" maxDepth="1">
<IfFileName glob="*.log.gz" />
<IfAccumulatedFileSize exceeds="${sys:LOG4J2_ROLLINGPOLICY_TOTAL_SIZE_CAP:-}"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright 2012-present the original author or authors.
*
* Licensed 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
*
* https://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.springframework.boot.logging.log4j2;

import java.util.HashSet;
import java.util.Set;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.boot.logging.LoggingSystemProperty;
import org.springframework.core.convert.support.ConfigurableConversionService;
import org.springframework.mock.env.MockEnvironment;

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

/**
* Tests for {@link Log4J2LoggingSystemProperties}.
*
* @author Andrey Timonin
*/
class Log4J2LoggingSystemPropertiesTests {

private Set<Object> systemPropertyNames;

private MockEnvironment environment;

@BeforeEach
void captureSystemPropertyNames() {
for (LoggingSystemProperty loggingSystemProperties : LoggingSystemProperty.values()) {
System.getProperties().remove(loggingSystemProperties);
}
this.systemPropertyNames = new HashSet<>(System.getProperties().keySet());
this.environment = new MockEnvironment();
this.environment
.setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance());
}

@AfterEach
void restoreSystemProperties() {
System.getProperties().keySet().retainAll(this.systemPropertyNames);
}

@Test
void applySetsStandardSystemProperties() {
this.environment.setProperty("logging.threshold.console", "lts");
new Log4J2LoggingSystemProperties(this.environment).apply();
assertThat(System.getProperties())
.containsEntry(LoggingSystemProperty.CONSOLE_THRESHOLD.getEnvironmentVariableName(), "lts");
}

@Test
void applySetsLog4J2SystemProperties() {
this.environment.setProperty("logging.log4j2.rollingpolicy.file-name-pattern", "fnp");
this.environment.setProperty("logging.log4j2.rollingpolicy.max-file-size", "1KB");
this.environment.setProperty("logging.log4j2.rollingpolicy.total-size-cap", "2KB");
this.environment.setProperty("logging.log4j2.rollingpolicy.max-history", "mh");
new Log4J2LoggingSystemProperties(this.environment).apply();
assertThat(System.getProperties())
.containsEntry(Log4J2RollingPolicySystemProperty.FILE_NAME_PATTERN.getEnvironmentVariableName(), "fnp")
.containsEntry(Log4J2RollingPolicySystemProperty.MAX_FILE_SIZE.getEnvironmentVariableName(), "1024")
.containsEntry(Log4J2RollingPolicySystemProperty.TOTAL_SIZE_CAP.getEnvironmentVariableName(), "2048")
.containsEntry(Log4J2RollingPolicySystemProperty.MAX_HISTORY.getEnvironmentVariableName(), "mh");
}

}