Skip to content

About

Logback XML configuration to Java translation project

Resources

Security policy

Stars

18 stars

Watchers

2 watching

Forks

Latest commit

 

History

162 Commits

Folders and files

Repository files navigation

logback-tyler

Logback-tyler translates logback-classic XML configuration files into Java.

The resulting java class, namely TylerConfigurator, can be used to configure logback. It implements the Configurator interface. It can thus be declared as a custom configuration provider using Java's standard service-provider meachanism.

Custom configurators are searched by looking up a provider-configuration file resource located under the META-INF/services/ch.qos.logback.classic.spi.Configurator file in your project. This provider-configuration should contain a line with the fully qualified class name of your desired configurator, e.g TylerConfigurator.

Running TylerConfigurator does not require XML parsers and usually executes noticeably faster than JoranConfigurator, logback's XML configurator. Moreover, TylerConfigurator does not use reflection. In addition, given that it ships with your project's binaries, it is harder to modify and offers an even smaller attack surface.

At runtime, TylerConfigurator does not have any additional dependencies other than logback-classic version 1.6.6.

Online instance

A instance of logback-tyler translator is available online. Do not hesitate to experiment with it.

Running the translator locally

Logback-tyler is located at the following Maven coordinates:

 <groupId>ch.qos.logback.tyler</groupId>
 <artifactId>tyler-base</artifactId>
 <version>1.0.7</version>

Here is a sample program to translate a logback.xml as string into Java.

import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.model.Model;
import ch.qos.logback.core.util.StatusPrinter;
import ch.qos.logback.tyler.base.ModelToJava;

import java.io.IOException;

public class TylerExample {

    String xmlInput =
    """
            <configuration debug="true">
              <import class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"/>
              
              <property name="APP_NAME" value="myApp"/>
             
              <contextName>${APP_NAME}</contextName>
             
              <appender class="ch.qos.logback.core.FileAppender" name="TOTO">
                <file>toto.log</file>
                <append>true</append>
                <immediateFlush>true</immediateFlush>
                <encoder>
                  <pattern>%-4relative [%thread] %-5level %logger{35} -%kvp- %msg%n</pattern>
                </encoder>   
              </appender>         
             
             
              <root level="DEBUG">
                <appender-ref ref="TOTO"/>
              </root>             
            </configuration>                 
    """;
    
    public static void main(String[] args)  throws JoranException, IOException {
        ContextBase context = new ContextBase();
        ModelToJava m2j = new ModelToJava(context);
        Model model = m2j.extractModel(xmlInput);
        String result = m2j.toJava(model);
        System.out.println(result);
        // print any error messages occuring during the translation
        StatusPrinter.print(context);
    }
}

running the above program will produce the following output

package com.example;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.Configurator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.tyler.TylerConfiguratorBase;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.model.ModelConstants;
import ch.qos.logback.core.util.OptionHelper;
import java.net.URL;

/**
 *
 * <p>This file was generated by logback-tyler version 1.0.7</p>
 *
 * <p>Eventual errors and warnings are appended at the end.</p>
 *
 * <p>You may experiment with logback.xml to Java translation, i.e.
 * TylerConfigurator generation, at the following URL:</p>
 *
 * <p>     https://logback.qos.ch/translator/services/xml2Java.html </p>
 *
 * <p>This generated TylerConfigurator class is intended to be copied and integrated
 * into the user's project as a custom configurator. It will configure logback
 * without XML. You are free to rename TylerConfigurator as you wish.</p>
 *
 * <p>It requires logback-classic version 1.6.6 or later at runtime.</p>
 *
 * <p>Custom configurators are looked up via Java's service-provide facility. If a
 * custom provider is found, it takes precedence over logback's own configurators,
 * e.g. DefaultJoranConfigurator.</p>
 *
 * <p>To install your custom configurator to your project, add a
 * provider-configuration file to the following path:</p>
 *
 * <pre>  META-INF/services/ch.qos.logback.classic.spi.Configurator</pre>
 *
 * <p>This provider-configuration file should contain a line with the fully
 * qualified class name of your tyler configurator.</p>
 *
 * <p>See also item 1 of 'Configuration at initialization' section at </p>
 *
 * <p>  https://logback.qos.ch/manual/configuration.html#auto_configuration</p>
 *
 * <p>Configurations using TylerConfigurator can still dynamically configure
 * logger levels with the help of properties files. Moreover, configuration
 * files in properties format can be watched for changes. See the
 * documentation on PropertiesConfigurator for more details.</p>
 *
 * <p>https://logback.qos.ch/manual/configuration.html#propertiesConfigurator</p>
 *
 * <p>Please note that when logback-tyler transforms XML to Java, it performs
 * runtime analysis of classes using Java's class reflection. Thus,
 * if your logback.xml mentions classes which are unavailable on the classpath,
 * logback-tyler will fail during the translation.</p>
 *
 */
public class TylerConfigurator extends TylerConfiguratorBase implements Configurator {
  /**
   * Appender variable referencing the appender named "TOTO".
   */
  protected Appender<ILoggingEvent> appenderTOTO;

  /**
   * Since TylerConfigurator is java based, the topURL is always null.
   * However, it is still possible tos scan for changes using the
   * <propertiesConfigurator> element.
   */
  protected final URL topURL = null;

  /**
   * <p>This method performs configuration per {@link Configurator} interface.</p>
   *
   * <p>If <code>TylerConfigurator</code> is installed as a configurator service, this
   * method will be called by logback-classic during initialization.</p>
   */
  @Override
  public Configurator.ExecutionStatus configure(LoggerContext loggerContext) {
    setContext(loggerContext);
    if (toDebugBoolean("true")) {
      addOnConsoleStatusListener();
    }
    this.propertyModelHandlerHelper.handlePropertyModel(this, "APP_NAME", "myApp", "", "", "");
    setContextName(subst("${APP_NAME}"));
    this.appenderTOTO = setupAppenderTOTO();
    Logger logger_ROOT = setupLogger("ROOT", "DEBUG", null);
    logger_ROOT.addAppender(appenderTOTO);
    return ExecutionStatus.DO_NOT_INVOKE_NEXT_IF_ANY;
  }

  FileAppender setupAppenderTOTO() {
    FileAppender appender = new FileAppender();
    appender.setContext(context);
    appender.setName("TOTO");
    appender.setFile("toto.log");
    appender.setAppend(true);
    appender.setImmediateFlush(true);

    // Configure component of type PatternLayoutEncoder
    PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
    patternLayoutEncoder.setContext(context);
    patternLayoutEncoder.setPattern("%-4relative [%thread] %-5level %logger{35} -%kvp- %msg%n");
    patternLayoutEncoder.setParent(appender);
    patternLayoutEncoder.start();
    // Inject component of type PatternLayoutEncoder into parent
    appender.setEncoder(patternLayoutEncoder);

    appender.start();
    return appender;
  }

  /**
   * Interprets the logback.debug system property, or if not set, the raw debug attribute using properties of the running context.
   */
  private boolean toDebugBoolean(String debugAttribute) {
    String debugStr = OptionHelper.getSystemProperty(ModelConstants.DEBUG_SYSTEM_PROPERTY_KEY, null);
    if (debugStr == null) {
      debugStr = subst(debugAttribute);
    }
    return !(OptionHelper.isNullOrEmptyOrAllSpaces(debugStr) || debugStr.equalsIgnoreCase("false") || debugStr.equalsIgnoreCase(ModelConstants.NULL_STR));
  }
}
// 19:38:11,004 |-INFO in ch.qos.logback.tyler.base.handler.ImplicitModelHandler - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
// 19:38:11,005 |-INFO in ch.qos.logback.tyler.base.TylerProcessor@5d7148e2 - End of configuration.

Translation options

ModelToJava accepts an optional TranslationOptions instance as its second constructor argument. TranslationOptions is immutable and created via a builder.

TranslationOptions options = TranslationOptions.builder()
    .generatedClassName("org.example.MyConfigurator")
    .generatedClassSuperclassName("org.example.MyTylerConfiguratorBase")
    .translationTimeInclusionEnabled(true)
    .allowedPackages(List.of("org.example.logging"))
    .build();

ModelToJava m2j = new ModelToJava(context, options);

The available options are:

  • generatedClassName: the fully qualified name of the generated configurator class. Defaults to com.example.TylerConfigurator.

  • generatedClassSuperclassName: the fully qualified name of the superclass of the generated class. It must be a public, non-final, top-level class extending TylerConfiguratorBase with a public or protected no-argument constructor. Defaults to ch.qos.logback.classic.tyler.TylerConfiguratorBase.

  • translationTimeInclusionEnabled: if true, files referenced by <include> elements are read at translation time and their contents inlined in the generated code. Otherwise, or if an included file is unavailable, the <include> element is omitted with a warning. Variables are not supported in the attributes of <include> elements. Defaults to false. Only enable this option for trusted input.

  • allowedPackages: the packages, including their subpackages, whose classes may be loaded at translation time, e.g. classes of appenders, encoders, layouts, filters, conditions or converters. Classes of other packages are reported as errors. Classes of the ch.qos.logback package are always allowed. Defaults to the packages of logback's documentation examples, i.e. chapters.appenders, chapters.layouts and chapters.filters, which the given packages replace. Alternatively, allowAllPackages() allows the classes of all packages. As classes are loaded at translation time, only allow all packages for trusted input.

  • classLoader: the class loader used at translation time to load the classes referenced by the configuration file and to find the resources referenced by <include resource="..."> elements. For example, a build tool can pass a class loader which sees the dependencies of the project being built. Defaults to the class loader of logback.

The ModelToJava(Context) constructor uses TranslationOptions.DEFAULT.

Maven plugin

As of version 1.0.7, the tyler-maven-plugin translates a logback.xml file into a custom configurator at build time. The generated class is compiled with the rest of your project and installed as a service provider in META-INF/services/ch.qos.logback.classic.spi.Configurator. Thus, logback picks it up at initialization without any further configuration.

<build>
  <plugins>
    <plugin>
      <groupId>ch.qos.logback.tyler</groupId>
      <artifactId>tyler-maven-plugin</artifactId>
      <version>1.0.7</version>
      <executions>
        <execution>
          <goals>
            <goal>generate</goal>
          </goals>
        </execution>
      </executions>
      <configuration>
        <configurationFile>${project.basedir}/src/main/resources/logback.xml</configurationFile>
        <className>org.example.logging.MyConfigurator</className>
      </configuration>
    </plugin>
  </plugins>
</build>

The generate goal runs in the generate-sources phase. It writes the generated class under target/generated-sources/tyler and the provider-configuration file under target/generated-resources/tyler, and adds both directories to the project.

The available parameters are listed below. Each parameter can also be set via the user property shown in parentheses, e.g. -Dtyler.skip=true.

  • configurationFile (tyler.configurationFile): the logback.xml file to translate. Defaults to ${project.basedir}/src/main/resources/logback.xml.

  • className (tyler.className): the fully qualified name of the generated configurator class. Defaults to com.example.TylerConfigurator.

  • superclassName (tyler.superclassName): the fully qualified name of the superclass of the generated class, see generatedClassSuperclassName above. Defaults to ch.qos.logback.classic.tyler.TylerConfiguratorBase.

  • translationTimeInclusionEnabled (tyler.translationTimeInclusionEnabled): whether files referenced by <include> elements are inlined at translation time, see above. Defaults to false.

  • allowedPackages (tyler.allowedPackages): the packages whose classes may be referenced by the configuration file, in addition to ch.qos.logback, see above. As the configuration file belongs to your project, all packages are allowed if this parameter is not set.

  • failOnWarning (tyler.failOnWarning): whether warnings issued during translation fail the build. Errors always do. Defaults to false.

  • skip (tyler.skip): skips the translation. Defaults to false.

  • outputDirectory and resourcesOutputDirectory: the directories where the generated class and the provider-configuration file are written.

Classes referenced by the configuration file, e.g. third-party appenders or encoders, are looked up in the compile class path of your project. Thus, they must be declared as dependencies with compile scope, which is required anyway to compile the generated class. Resources referenced by <include resource="..."> elements are looked up in the resource directories of your project. Relative paths in <include file="..."> elements are resolved against the current working directory of Maven.

Errors and warnings issued during translation are reported in the Maven build log.

Please note that the provider-configuration file is part of your main resources. Consequently, the generated configurator also takes precedence over any logback-test.xml file when running tests.

Gradle plugin

As of version 1.0.7, the ch.qos.logback.tyler Gradle plugin performs the same translation as the Maven plugin. For Java projects, it registers the generateTylerConfigurator task and adds its outputs to the main source set. Thus, the generated configurator is compiled, and the provider-configuration file packaged, with the rest of your project.

plugins {
    java
    id("ch.qos.logback.tyler") version "1.0.7"
}

tyler {
    configurationFile = file("src/main/resources/logback.xml")
    className = "org.example.logging.MyConfigurator"
}

The tyler extension supports the following properties, with the same meaning and defaults as the parameters of the Maven plugin: configurationFile, className, superclassName, translationTimeInclusionEnabled, allowedPackages and failOnWarning. If allowedPackages is empty, which is the default, all packages are allowed.

Classes referenced by the configuration file are looked up in the compile class path of the main source set, including other projects of your build, and resources referenced by <include resource="..."> elements in its resource directories. The generated files are written under build/generated/tyler. The task supports up-to-date checks, the build cache and the configuration cache.

The Gradle plugin is built with Gradle, separately from the other modules. To build it, first install tyler-base with mvn install in the top-level directory, then run ./gradlew build in the tyler-gradle-plugin directory.

About

Logback XML configuration to Java translation project

Resources

Security policy

Stars

18 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages