web-dev-qa-db-fra.com

Comment configurer log4j 2.x uniquement par programme?

Comment configurer log4j 2.3 avec console appender pur par programmation (aucun fichier de configuration de n'importe quel format)?

Fondamentalement, je recherche une version 2.x de cette code 1.x .

Dans mes cours, j'utilisais ensuite

private static final Logger logger = LogManager.getLogger();
// 
    // some method
       logger.debug(someString);

Sans aucune configuration, je suis (comme prévu) face

ERREUR StatusLogger Aucun fichier de configuration log4j2 trouvé. Utilisation de la configuration par défaut: journalisation uniquement des erreurs sur la console.

Bien que l'utilisation des fichiers de configuration semble être correctement documentée , je n'ai pas pu trouver un bon exemple de cas de code nu.

Le plus proche que j'ai obtenu est cet article qui utilise toujours un fichier factice.

Voici ma meilleure photo (bien que complètement infructueuse):

private static void configureLog4J() {
    PatternLayout layout = PatternLayout.createDefaultLayout();
    ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    LoggerConfig loggerConfig = new LoggerConfig();
    loggerConfig.addAppender(appender, DEBUG, null);
}

Ai-je raté quelque chose?

S'il s'agit toujours d'un cas RTFM, veuillez m'orienter dans la bonne direction.

22
PM 77-1

Voici un exemple complet de configuration par programme de log4j 2.8. Il a 3 appenders: RollingFile, JDBC et SMTP.

Il existe 1 classe et 2 fichiers de configuration des propriétés, un pour enregistrer la classe en tant que configurationFactory log4j2 et l'autre pour les propriétés définies comme le répertoire du fichier journal.

Classe # 1: MPLoggingConfiguration

package com.websitester.config;

import Java.io.Serializable;
import Java.nio.charset.Charset;
import Java.util.Zip.Deflater;

import org.Apache.logging.log4j.Level;
import org.Apache.logging.log4j.core.Appender;
import org.Apache.logging.log4j.core.Layout;
import org.Apache.logging.log4j.core.LoggerContext;
import org.Apache.logging.log4j.core.appender.RollingFileAppender;
import org.Apache.logging.log4j.core.appender.SmtpAppender;
import org.Apache.logging.log4j.core.appender.db.ColumnMapping;
import org.Apache.logging.log4j.core.appender.db.jdbc.ColumnConfig;
import org.Apache.logging.log4j.core.appender.db.jdbc.ConnectionSource;
import org.Apache.logging.log4j.core.appender.db.jdbc.DataSourceConnectionSource;
import org.Apache.logging.log4j.core.appender.db.jdbc.JdbcAppender;
import org.Apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy;
import org.Apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
import org.Apache.logging.log4j.core.appender.rolling.OnStartupTriggeringPolicy;
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.ConfigurationFactory;
import org.Apache.logging.log4j.core.config.ConfigurationSource;
import org.Apache.logging.log4j.core.config.DefaultConfiguration;
import org.Apache.logging.log4j.core.config.LoggerConfig;
import org.Apache.logging.log4j.core.config.Order;
import org.Apache.logging.log4j.core.config.Property;
import org.Apache.logging.log4j.core.config.plugins.Plugin;
import org.Apache.logging.log4j.core.layout.HtmlLayout;
import org.Apache.logging.log4j.core.layout.PatternLayout;

public class MPLoggingConfiguration {

    public static final String WEBSITESTER_LOGGER_NAME = "com.websitester";
    public static final String FILE_PATTERN_LAYOUT = "%n[%d{yyyy-MM-dd HH:mm:ss}] [%-5p] [%l]%n\t%m%n%n";
    public static final String LOG_FILE_NAME = "awmonitor.log";
    public static final String LOG_FILE_NAME_PATTERN = "awmonitor-%i.log";  

    /**
     * Just to make JVM visit this class to initialize the static parts.
     */
    public static void configure() {
    }

    @Plugin(category = ConfigurationFactory.CATEGORY, name = "MPConfigurationFactory")
    @Order(15)
    public static class MPConfigurationFactory  extends ConfigurationFactory {
        public static final String[] SUFFIXES = new String[] {".json", "*"};

        @Override
        protected String[] getSupportedTypes() {
            return SUFFIXES;
        }

        @Override
        public Configuration getConfiguration(LoggerContext arg0, ConfigurationSource arg1) {
            return new Log4j2Configuration(arg1);
        }
    }

    private static class Log4j2Configuration extends DefaultConfiguration {

        public Log4j2Configuration(ConfigurationSource source) {
            super.doConfigure();
            setName("mp-log4j2");

            String logFilePath = "/log/weblogic/wl-moniport/";

            // LOGGERS
            //      com.websitester
            AppenderRef[] refs = new AppenderRef[] {};
            Property[] properties = new Property[] {};
            LoggerConfig websitesterLoggerConfig = LoggerConfig.createLogger(true, Level.INFO, WEBSITESTER_LOGGER_NAME, "true", refs, properties, this, null);
            addLogger(WEBSITESTER_LOGGER_NAME, websitesterLoggerConfig);


            // APPENDERS
            final Charset charset = Charset.forName("UTF-8");

            //      MP ROLLING FILE
            TriggeringPolicy mpFileCompositePolicy = CompositeTriggeringPolicy.createPolicy(
                    SizeBasedTriggeringPolicy.createPolicy("3 M"),
                    OnStartupTriggeringPolicy.createPolicy(1));
            final DefaultRolloverStrategy mpFileRolloverStrategy = DefaultRolloverStrategy.createStrategy("9", "1", "max", Deflater.NO_COMPRESSION + "", null, true, this);
            Layout<? extends Serializable> mpFileLayout = PatternLayout.newBuilder()
                    .withPattern(FILE_PATTERN_LAYOUT)
                    .withPatternSelector(null)
                    .withConfiguration(this)
                    .withRegexReplacement(null)
                    .withCharset(charset)
                    .withAlwaysWriteExceptions(isShutdownHookEnabled)
                    .withNoConsoleNoAnsi(isShutdownHookEnabled)
                    .withHeader(null)
                    .withFooter(null)
                    .build();
            Appender mpFileAppender = RollingFileAppender.newBuilder()
                    .withAdvertise(Boolean.parseBoolean(null))
                    .withAdvertiseUri(null)
                    .withAppend(true)
                    .withBufferedIo(true)
                    .withBufferSize(8192)
                    .setConfiguration(this)
                    .withFileName(logFilePath + LOG_FILE_NAME)
                    .withFilePattern(logFilePath + LOG_FILE_NAME_PATTERN)
                    .withFilter(null)
                    .withIgnoreExceptions(true)
                    .withImmediateFlush(true)
                    .withLayout(mpFileLayout)
                    .withCreateOnDemand(false)
                    .withLocking(false)
                    .withName("error_file_web")
                    .withPolicy(mpFileCompositePolicy)
                    .withStrategy(mpFileRolloverStrategy)
                    .build();
            mpFileAppender.start();
            addAppender(mpFileAppender);
            getLogger(WEBSITESTER_LOGGER_NAME).addAppender(mpFileAppender, Level.DEBUG, null);


            // JDBC
            if (System.getProperty("log4jjdbcjndiName") != null){
                ColumnConfig[] columnConfigs = new ColumnConfig[] {
                        ColumnConfig.newBuilder()
                        .setConfiguration(this)
                        .setName("DATED")
                        .setPattern(null)
                        .setLiteral(null)
                        .setEventTimestamp(true)
                        .setUnicode(false)
                        .setClob(false)
                        .build(),
                        ColumnConfig.newBuilder()
                        .setConfiguration(this)
                        .setName("LOGGER")
                        .setPattern("%logger")
                        .setLiteral(null)
                        .setEventTimestamp(false)
                        .setUnicode(false)
                        .setClob(false)
                        .build(),
                        ColumnConfig.newBuilder()
                        .setConfiguration(this)
                        .setName("LOG_LEVEL")
                        .setPattern("%level")
                        .setLiteral(null)
                        .setEventTimestamp(false)
                        .setUnicode(false)
                        .setClob(false)
                        .build(),
                        ColumnConfig.newBuilder()
                        .setConfiguration(this)
                        .setName("MESSAGE")
                        .setPattern("%message")
                        .setLiteral(null)
                        .setEventTimestamp(false)
                        .setUnicode(false)
                        .setClob(false)
                        .build(),
                        ColumnConfig.newBuilder()
                        .setConfiguration(this)
                        .setName("NODE")
                        .setPattern("" + System.getProperty("log4jmpserverid"))
                        .setLiteral(null)
                        .setEventTimestamp(false)
                        .setUnicode(false)
                        .setClob(false)
                        .build()
                };
                ConnectionSource dataSourceConnectionSource = DataSourceConnectionSource.createConnectionSource(System.getProperty("log4jjdbcjndiName"));
                if (dataSourceConnectionSource != null){
                    Appender jdbcAppender = JdbcAppender.newBuilder()
                            .setBufferSize(0)
                            .setColumnConfigs(columnConfigs)
                            .setColumnMappings(new ColumnMapping[]{})
                            .setConnectionSource(dataSourceConnectionSource)
                            .setTableName("MTDTLOGS")
                            .withName("databaseAppender")
                            .withIgnoreExceptions(true)
                            .withFilter(null)
                            .build();
                    jdbcAppender.start();
                    addAppender(jdbcAppender);
                    getLogger(WEBSITESTER_LOGGER_NAME).addAppender(jdbcAppender, Level.WARN, null);
                }
            };

            // SMTP
            if (System.getProperty("log4jemailSubject") != null){
                if (System.getProperty("log4jemailLevel").equalsIgnoreCase("error")) {
                    Layout<? extends Serializable> mpHtmlLayout = HtmlLayout.createLayout(false, "Monitor de Portales", null, null, "x-small", null);

                    Appender smtpAppender = SmtpAppender.createAppender(
                            this,
                            "SMTP",
                            System.getProperty("log4jemailTo"), 
                            System.getProperty("log4jemailcc"), 
                            System.getProperty("log4jemailbcc"), 
                            System.getProperty("log4jemailFrom"), 
                            System.getProperty("log4jemailreplyTo"), 
                            System.getProperty("log4jemailSubject"), 
                            System.getProperty("log4jemailProtocol"), 
                            System.getProperty("log4jemailHost"), 
                            System.getProperty("log4jemailPort"), 
                            System.getProperty("log4jemailUserName"), 
                            System.getProperty("log4jemailPassword"), 
                            "false", 
                            "50", 
                            mpHtmlLayout, 
                            null, 
                            "true");
                    smtpAppender.start();
                    addAppender(smtpAppender);
                    getLogger(WEBSITESTER_LOGGER_NAME).addAppender(smtpAppender, Level.ERROR, null);
                }
            }
        }
    }
}

Fichier de configuration: src/main/resources/log4j2.component.properties

log4j.configurationFactory=com.websitester.config.MPLoggingConfiguration$MPConfigurationFactory
log4j.configurationFile=log4j2websitester.json

Fichier de configuration: src/main/resources/log4j2websitester.json

{"logFilePath" : "/log/weblogic/wl-moniport/"}

Dans mon cas, j'ai défini toutes les propriétés (accessibles dans MPLoggingConfiguration via System.getProperty) dans d'autres classes, par exemple:

System.setProperty("log4jjdbcjndiName", "weblogic-monitor");

Lorsque vous avez modifié certaines propriétés et souhaitez reconfigurer log4j2, vous devez effectuer cet appel:

final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
ctx.reconfigure();

J'espère que cela t'aides

11
Carlos Cuesta

si vous le souhaitez pour la console appender, il existe un moyen très simple si vous utilisez maven, mettez simplement ces 2 dépendances dans votre pom.xml et tout sera imprimé sur votre console. rien nécessaire ... aucun fichier log4j.properties du tout. slf4j étend log4j et possède de nombreuses fonctionnalités riches.

          <dependency>
                 <groupId>org.slf4j</groupId>
                 <artifactId>slf4j-api</artifactId>
                 <version>1.7.5</version>
                 <scope>compile</scope>
          </dependency>

          <dependency>
                 <groupId>org.slf4j</groupId>
                 <artifactId>slf4j-simple</artifactId>
                 <version>1.7.5</version>
          </dependency>
3
Bhupi

Vous pouvez personnaliser votre propre ConfigurationFactory dans log4j. Veuillez vous référer à https://logging.Apache.org/log4j/2.x/manual/customconfig.html . Il semble qu'il puisse répondre à vos besoins.


Désolé. Est-ce que cela répond à votre besoin? Je viens de tester, et il fonctionne bien même s'il génère toujours le message d'erreur que vous avez mentionné ci-dessus.

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout<? extends Serializable> layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, config, null,
        null,true, true,null,null);

    Appender appender = FileAppender.createAppender("/tmp/log4jtest.txt", "false", "false", "File", "true",
        "false", "false", "4000", layout, null, "false", null, config);
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
    AppenderRef[] refs = new AppenderRef[] {ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "org.Apache.logging.log4j",
        "true", refs, null, config, null );
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("simpleTestLogger", loggerConfig);
    ctx.updateLoggers();


    Logger l = ctx.getLogger("simpleTestLogger");
    l.info("message of info level shoud be output properly");
    l.error("error message");
3
Yiping Huang