Comment configurer log4j 2.x purement programmatique?
comment configurer log4j 2.3
console appender
pure par programmation (pas de fichiers de configuration de n'importe quel format)?
en gros je cherche 2.x version de ce 1.code x.
dans Mes cours j'utiliserais alors
private static final Logger logger = LogManager.getLogger();
//
// some method
logger.debug(someString);
Sans aucune configuration, je suis (comme prévu) face
ERREUR StatusLogger Pas log4j2 fichier de configuration. Utilisation de la configuration par défaut: journalisation seulement des erreurs console.
alors que l'utilisation des fichiers de configuration semble être bien documenté, je ne pouvais pas trouver un bon exemple de ce nu-os code-seul cas.
Le plus proche que j'ai est cet article qui utilise encore un fichier fictif.
Voici mon mieux (même si complètement échoué) prise de vue:
private static void configureLog4J() {
PatternLayout layout = PatternLayout.createDefaultLayout();
ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
LoggerConfig loggerConfig = new LoggerConfig();
loggerConfig.addAppender(appender, DEBUG, null);
}
ai-je manqué quelque chose?
si C'est toujours un cas de RTFM, s'il vous plaît pointez-moi dans le droit direction.
4 réponses
package com;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
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 java.nio.charset.Charset;
public class MyLoggerTest {
public static void main(String[] args){
LoggerContext context= (LoggerContext) LogManager.getContext();
Configuration config= context.getConfiguration();
PatternLayout layout= PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(),false,false,null,null);
Appender appender=ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
appender.start();
AppenderRef ref= AppenderRef.createAppenderRef("CONSOLE_APPENDER",null,null);
AppenderRef[] refs = new AppenderRef[] {ref};
LoggerConfig loggerConfig= LoggerConfig.createLogger("false", Level.INFO,"CONSOLE_LOGGER","com",refs,null,null,null);
loggerConfig.addAppender(appender,null,null);
config.addAppender(appender);
config.addLogger("com", loggerConfig);
context.updateLoggers(config);
Logger logger=LogManager.getContext().getLogger("com");
logger.info("HELLO_WORLD");
}
}
ne sais Pas si c'est ce que vous cherchez. Cela crée une configuration par défaut et ajoute un logger de console. Cependant, LogManager.getLogger () ne fonctionne pas et utilise le LogManager.getContext ().getLogger () ne permet pas la hiérarchie logger. Honnêtement, je ne recommande pas l'approche programmatique, Log4j2 est allergique.
voici un exemple complet pour la configuration programmatique de log4j 2.8. Il dispose de 3 appenders: RollingFile, JDBC et SMTP.
il y a 1 classe et 2 fichiers de configuration de propriétés, un pour enregistrer la classe comme un configurationFactory log4j2, et l'autre pour définir les propriétés comme le répertoire de fichier log.
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.composant.propriétés
log4j.configurationFactory=com.websitester.config.MPLoggingConfiguration$MPConfigurationFactory
log4j.configurationFile=log4j2websitester.json
Config fichier: src/main/resources / log4j2websitester.json
{"logFilePath" : "/log/weblogic/wl-moniport/"}
dans mon cas, j'ai défini toutes les propriétés (accessibles en MPLoggingConfiguration via le système.getProperty) dans d'autres classes, par exemple:
System.setProperty("log4jjdbcjndiName", "weblogic-monitor");
lorsque vous avez changé certaines propriétés et que vous voulez reconfigurer log4j2, vous devez faire cet appel:
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
ctx.reconfigure();
Espérons que cette aide
Vous pouvez personnaliser votre propre ConfigurationFactory dans log4j. Voirhttps://logging.apache.org/log4j/2.x/manual/customconfig.html