Skip to content

Add JUL to Log4j API bridge #2

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

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
154 changes: 154 additions & 0 deletions jul-to-log4j-api/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jdk-parent</artifactId>
<version>${revision}</version>
<relativePath>../parent</relativePath>
</parent>

<artifactId>jul-to-log4j-api</artifactId>
<name>JUL to Log4j API logging bridge</name>
<description>A `java.util.logging` LogManager that forwards events to the Log4j API.</description>

<properties>
<!-- Skips BND Baseline until the first release -->
<bnd.baseline.fail.on.missing>false</bnd.baseline.fail.on.missing>

<!-- TODO: Adapt to Java 9 -->
<maven.compiler.release>17</maven.compiler.release>
<maven.compiler.source>${maven.compiler.release}</maven.compiler.source>
<maven.compiler.target>${maven.compiler.release}</maven.compiler.target>
<!--
~ OSGi and JPMS options
-->
<bnd-extra-package-options>
<!-- Optional annotations -->
org.jspecify.*;resolution:=optional
</bnd-extra-package-options>
<bnd-extra-module-options>
<!-- Optional modules can not be `transitive` -->
org.jspecify;transitive=false
</bnd-extra-module-options>

<!-- Dependency versions -->
<log4j.version>3.0.0-SNAPSHOT</log4j.version>
</properties>

<dependencies>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-kit</artifactId>
</dependency>

<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-async-logger</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core-test</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>default-test</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
<configuration>
<excludes>
<exclude>**/AsyncLoggerThreadsTest.class</exclude>
<exclude>**/CustomLoggerAdapterTest.class</exclude>
</excludes>
<!-- Use custom `j.u.l.LogManager` -->
<systemPropertyVariables>
<java.util.logging.manager>org.apache.logging.jul.tolog4j.LogManager</java.util.logging.manager>
</systemPropertyVariables>
</configuration>
</execution>
<execution>
<id>async-logger-test</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
<configuration>
<includes>
<include>**/AsyncLoggerThreadsTest.class</include>
</includes>
<!-- Use custom `j.u.l.LogManager` and an asynchronous selector -->
<systemPropertyVariables>
<java.util.logging.manager>org.apache.logging.jul.tolog4j.LogManager</java.util.logging.manager>
<log4j.loggerContext.selector>org.apache.logging.log4j.async.logger.AsyncLoggerContextSelector</log4j.loggerContext.selector>
</systemPropertyVariables>
</configuration>
</execution>
<execution>
<id>custom-logger-adapter-test</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
<configuration>
<includes>
<include>**/CustomLoggerAdapterTest.class</include>
</includes>
<!-- Use custom `j.u.l.LogManager` and a custom adapter -->
<systemPropertyVariables>
<java.util.logging.manager>org.apache.logging.jul.tolog4j.LogManager</java.util.logging.manager>
<log4j.jul.loggerAdapter>org.apache.logging.jul.tolog4j.test.support.CustomLoggerAdapterTest$CustomLoggerAdapter</log4j.jul.loggerAdapter>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* 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.jul.tolog4j;

import org.apache.logging.jul.tolog4j.internal.DefaultLevelConverter;
import org.apache.logging.jul.tolog4j.internal.JulProperties;
import org.apache.logging.jul.tolog4j.spi.LevelConverter;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.kit.env.PropertyEnvironment;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.LoaderUtil;

/**
* Utility class to convert between JDK Levels and Log4j 2 Levels.
*
* @since 2.1
*/
public final class LevelTranslator {

/**
* Custom Log4j level corresponding to the {@link java.util.logging.Level#FINEST} logging level. This maps to a
* level more specific than {@link org.apache.logging.log4j.Level#TRACE}.
*/
public static final Level FINEST = Level.forName("FINEST", Level.TRACE.intLevel() + 100);

/**
* Custom Log4j level corresponding to the {@link java.util.logging.Level#CONFIG} logging level. This maps to a
* level in between {@link org.apache.logging.log4j.Level#INFO} and {@link org.apache.logging.log4j.Level#DEBUG}.
*/
public static final Level CONFIG = Level.forName("CONFIG", Level.INFO.intLevel() + 50);

private static final Logger LOGGER = StatusLogger.getLogger();
private static final LevelConverter LEVEL_CONVERTER;

static {
final Class<? extends LevelConverter> levelConverterClass =
PropertyEnvironment.getGlobal().getProperty(JulProperties.class).levelConverter();
if (levelConverterClass != null) {
LevelConverter levelConverter;
try {
levelConverter = LoaderUtil.newInstanceOf(levelConverterClass);
} catch (final Exception e) {
LOGGER.error("Could not create custom LevelConverter [{}].", levelConverterClass.getName(), e);
levelConverter = new DefaultLevelConverter();
}
LEVEL_CONVERTER = levelConverter;
} else {
LEVEL_CONVERTER = new DefaultLevelConverter();
}
}

/**
* Converts a JDK logging Level to a Log4j logging Level.
*
* @param level JDK Level to convert, may be null per the JUL specification.
* @return converted Level or null
*/
public static Level toLevel(final java.util.logging.Level level) {
return LEVEL_CONVERTER.toLevel(level);
}

/**
* Converts a Log4j logging Level to a JDK logging Level.
*
* @param level Log4j Level to convert.
* @return converted Level.
*/
public static java.util.logging.Level toJavaLevel(final Level level) {
return LEVEL_CONVERTER.toJavaLevel(level);
}

private LevelTranslator() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* 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.jul.tolog4j;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import org.apache.logging.jul.tolog4j.internal.ApiLoggerAdapter;
import org.apache.logging.jul.tolog4j.internal.JulProperties;
import org.apache.logging.jul.tolog4j.internal.NoOpLogger;
import org.apache.logging.jul.tolog4j.spi.AbstractLoggerAdapter;
import org.apache.logging.log4j.kit.env.PropertyEnvironment;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.LoaderUtil;

/**
* Log4j implementation of {@link java.util.logging.LogManager}.
* <p>
* Note that the system property {@code java.util.logging.manager} must be set to
* {@code org.apache.logging.jul.tolog4j.LogManager} in order to use this adaptor.
* This LogManager requires the {@code log4j-api} library to be available.
* </p>
* <p>
* To override the default {@link AbstractLoggerAdapter} that is used, specify the Log4j property
* {@code log4j.jul.LoggerAdapter} and set it to the fully qualified class name of a custom
* implementation.
* All implementations must have a default constructor.
* </p>
*
* @since 2.1
*/
public class LogManager extends java.util.logging.LogManager {

private static final org.apache.logging.log4j.Logger LOGGER = StatusLogger.getLogger();
private final AbstractLoggerAdapter loggerAdapter;
// Contains the set of logger names that are actively being requested using getLogger.
private final ThreadLocal<Set<String>> recursive = ThreadLocal.withInitial(HashSet::new);

public LogManager() {
AbstractLoggerAdapter adapter = null;
final Class<? extends AbstractLoggerAdapter> adapterClass =
PropertyEnvironment.getGlobal().getProperty(JulProperties.class).loggerAdapter();
if (adapterClass != null) {
try {
LOGGER.info("Trying to use LoggerAdapter [{}] specified by Log4j property.", adapterClass.getName());
adapter = LoaderUtil.newInstanceOf(adapterClass);
} catch (final Exception e) {
LOGGER.error(
"Specified LoggerAdapter [{}] can not be created, using default.", adapterClass.getName(), e);
}
}
if (adapter == null) {
// Use API by default
// See https://github.com/apache/logging-log4j2/issues/2353
adapter = new ApiLoggerAdapter();
}
loggerAdapter = adapter;
LOGGER.info("Registered Log4j as the java.util.logging.LogManager.");
}

@Override
public boolean addLogger(final Logger logger) {
// in order to prevent non-bridged loggers from being registered, we always return false to indicate that
// the named logger should be obtained through getLogger(name)
return false;
}

@Override
public Logger getLogger(final String name) {
LOGGER.trace("Call to LogManager.getLogger({})", name);
final Set<String> activeRequests = recursive.get();
if (activeRequests.add(name)) {
try {
return loggerAdapter.getLogger(name);
} finally {
activeRequests.remove(name);
}
}
LOGGER.warn("Recursive call to getLogger for {} ignored.", name);
return new NoOpLogger(name);
}

@Override
public Enumeration<String> getLoggerNames() {
return Collections.enumeration(
loggerAdapter.getLoggersInContext(loggerAdapter.getContext()).keySet());
}
}
Loading
Loading