Coder Social home page Coder Social logo

log4j2-jboss-logmanager's Introduction

JBoss Logging

JBoss Logging is a logging facade which can bind to different log managers allowing your applications to be log manager agnostic.

Usage

JBoss Logging is similar to other logging facades in the way you get a logger and log messages. One thing to note is the format style log methods will only format the message if the log level is enabled. This helps with performance of objects which may have complex toString() methods.

private static final Logger LOGGER = Logger.getLogger(Customer.class);

public Customer getCustomer(final int id) {
    LOGGER.debugf("Looking up customer %d", id);
    try {
        final Customer customer = findCustomer(id);
        LOGGER.tracef("Found customer: %s", customer);
        return customer;
    } catch (Exception e) {
        LOGGER.errorf(e, "Error looking up customer %d", id);
    }
    return null;
}

Supported Log Managers

The following are the supported log managers and listed in the order the attempt to discover the provider is done.

  1. JBoss Log Manager

  2. Log4j 2

  3. SLF4J and Logback

  4. log4j (note this log manager is EOL’d)

  5. Java Util Logging

You can define the specific log manager you want to use by specifying the org.jboss.logging.provider system property. The following is the mapping of the property value to the log manager.

Property Value Log Manager

jboss

JBoss Log Manager

jdk

Java Util Logging

log4j2

Log4j 2

log4j

log4j

slf4j

SLF4J and Logback

Custom Provider

You can also implement your own org.jboss.logging.LoggerProvider which would be loaded from a ServiceLoader. Simply implement the API and add a META-INF/services/org.jboss.logging.LoggerProvider file with the fully qualified class name of your implementation to your library. If the system property is not defined, your implementation should be discovered.

Maven Dependency

<dependency>
    <groupId>org.jboss.logging</groupId>
    <artifactId>jboss-logging</artifactId>
    <version>${version.org.jboss.logging}</version>
</dependency>

Contributing

log4j2-jboss-logmanager's People

Contributors

dependabot[bot] avatar jamezp avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

log4j2-jboss-logmanager's Issues

Upgrade log4j2 to 2.14.0

Log4j2 2.14.0 was released. We should upgrade to the latest version before final is released.

Programmatically building logger only works with log4j2-jboss-logmanager:1.0.0

In my project, I programmatically build loggers using log4j-core to write specific messages to different log files. When I use org.jboss.logmanager:log4j2-jboss-logmanager:1.0.0.Final it all works great (I've been forcing this version for some time due to this). If I try to use any later version, I get the error: ClassCastException: class org.jboss.logmanager.log4j.JBossLoggerContext cannot be cast to class org.apache.logging.log4j.core.LoggerContext.

Is there a way to set the logger context to be the one from log4j-core, as opposed to JBOSS?

I am open to migrating to a new solution if this is no longer possible, I just can't seem to figure out how to do it.

package my.project;

import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender;
import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy.Builder;
import org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy;
import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.eclipse.microprofile.config.inject.ConfigProperty;

import com.lmco.compass.commons.collections.LruMap;

@ApplicationScoped
class ArchiveLogger {
    static final Map<String, Logger> LOGGERS = Collections.synchronizedMap(new LruMap<>(64));

    private boolean compressArchives;
    private String fileSizeTrigger;
    private String maxFilesKept;
    private String logDir;

    @Inject
    public ArchiveLogger(
            @ConfigProperty(name = "app.log.compressing-enabled", defaultValue = "true") final boolean compressArchives,
            @ConfigProperty(name = "app.log.max-files-kept", defaultValue = "10") final String maxFilesKept,
            @ConfigProperty(name = "app.log.rollover-trigger-file-size",
                    defaultValue = "10 MB") final String fileSizeTrigger,
            @ConfigProperty(name = "app.log.directory", defaultValue = "/etc/data/logs") final String logDirectory) {
        this.compressArchives = compressArchives;
        this.maxFilesKept = maxFilesKept;
        this.fileSizeTrigger = fileSizeTrigger;
        this.logDir = logDirectory;
    }

    public Logger getLogger(final String name) {
        return LOGGERS.computeIfAbsent(name, key -> createLoggerConfig(logDir, name));
    }

    private Logger createLoggerConfig(final String archiveDir, final String name) {
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(true);
        final Configuration config = ctx.getConfiguration();

        final Path filePath = Path.of(archiveDir, name);
        final Path fileName = filePath.resolve("archive.log");
        final String fileExt = compressArchives ? ".log.gz" : ".log";
        final Path filePattern = filePath.resolve("archive-%i" + fileExt);

        final TriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy(fileSizeTrigger);
        final Builder rsb = DefaultRolloverStrategy.newBuilder().withMax(maxFilesKept).withFileIndex("min");
        if (compressArchives) {
            rsb.withCompressionLevelStr("9");
        }

        final RollingRandomAccessFileAppender appender = RollingRandomAccessFileAppender.newBuilder()
                .setName(name).withFileName(fileName.toString()).withFilePattern(filePattern.toString())
                .setLayout(PatternLayout.newBuilder().withPattern("%d{ISO8601}~%logger~%m%n").build()).withPolicy(tp)
                .withStrategy(rsb.build()).build();
        appender.start();
        config.addAppender(appender);

        final AppenderRef ref = AppenderRef.createAppenderRef(name, null, null);
        final LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, name, "true",
                new AppenderRef[] { ref }, null, config, null);
        loggerConfig.addAppender(appender, null, null);
        config.addLogger(name, loggerConfig);

        return LogManager.getLogger(name);
    }
}

Adapt log4j2.ThreadContext to jboss-logging.MDC

Currently when using the Log4j2 frontend (log4j2-jboss-logmanager-1.1.1.Final) with the jboss-logging backend and calling log4j2.ThreadContext.put("foo", "bar") this invocation is not bridged towards the jboss-logging.MDC.

This specifically hits me in combination with Quarkus, reactive-messaging and smallrye-context-propagation, where it looks like only the jboss-logging.MDC is propagated but not the log4j2.ThreadContext.
Additionally I observed that context, that is put to the jboss-logging.MDC, is not rendered when the log message is created with the log4j-API.

I verified this by adding a very naive implementation of a MdcBridge, but this is probably not a candidate for an initial PR because it results in heavy use of MDC.getMap(), which is documented as "expensive and should be used sparingly". Additionally I had to cast the Map<String, Object> to Map<String, String>.

Fix permissions issues with attachments

When attaching objects to a logger a permission check is done. This should be wrapped in a privileged action as need to attach objects regardless of whether or not the security manager is being used.

log4j2-jboss-logmanager LevelTranslator NullPointer

We found the following Nullpointer Exception

Caused by: java.lang.NullPointerException
	at org.jboss.logmanager.log4j.LevelTranslator.translateLevel(LevelTranslator.java:95)
	at org.jboss.logmanager.log4j.JBossLogger.getLevel(JBossLogger.java:156)

....
Reason seems that LevelTranslator is not defensive enough. Suggestion:

    java.util.logging.Level translateLevel(final Level level) {
        //level null is same as level not translated
    	if(level == null) {
        	return org.jboss.logmanager.Level.INFO;
        }
    	final java.util.logging.Level result = log4jToJul.get(level.intLevel());
        return result == null ? org.jboss.logmanager.Level.INFO : result;
    }

    Level translateLevel(final java.util.logging.Level level) {
     //level null is same as level not translated        
        if(level == null) {
        	return Level.INFO;
        }
    	final Level result = julToLog4j.get(level.intValue());
        return result == null ? Level.INFO : result;
    }

Copied from https://issues.redhat.com/browse/LOGMGR-266.

Increase the priority for the provider

Currently the JBossProvider has a priority of 5. This is lower than the priority of the log4j-core provider. This is should have a higher priority the jboss-logmanager is like the backing log manager.

Support for custom log levels

Mapping custom log levels to a default level (whether DEBUG, INFO or other) breaks tool chains in complex projects. With DEBUG as default, production environments are forced to that level of logging for some packages, when the custom log levels cannot be avoided.

Some SPI handling or even manual introduction of custom log levels could improve the behavior of the LevelTranslator for such cases.

add logic similar to how log4j2 handle filters

The Logger class in log4j2 contains a built-in feature that applies filters before evaluating the log level. This functionality can be useful to users. You can find an example of this implementation on GitHub at: https://github.com/apache/logging-log4j2/blob/2.x/log4j-core/src/main/java/org/apache/logging/log4j/core/Logger.java#L177 . In the filter function, if the filter returns a positive result, the message will be logged.

Any chance we can add the similar logic in this library? Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.