下面列出了org.springframework.boot.logging.LogFile#org.apache.logging.log4j.core.config.ConfigurationSource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Nullable
private static LoggerContext init() {
try {
String fileRef = Boolean.getBoolean(ApplicationProperties.CONSULO_MAVEN_CONSOLE_LOG) ? "/log4j2-console.xml" : "/log4j2-default.xml";
String text = FileUtil.loadTextAndClose(Log4J2LoggerFactory.class.getResourceAsStream(fileRef));
text = StringUtil.replace(text, SYSTEM_MACRO, StringUtil.replace(ContainerPathManager.get().getSystemPath(), "\\", "\\\\"));
text = StringUtil.replace(text, APPLICATION_MACRO, StringUtil.replace(ContainerPathManager.get().getHomePath(), "\\", "\\\\"));
text = StringUtil.replace(text, LOG_DIR_MACRO, StringUtil.replace(ContainerPathManager.get().getLogPath(), "\\", "\\\\"));
File file = new File(ContainerPathManager.get().getLogPath());
if (!file.mkdirs() && !file.exists()) {
System.err.println("Cannot create log directory: " + file);
}
ConfigurationSource source = new ConfigurationSource(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
return Configurator.initialize(Log4J2LoggerFactory.class.getClassLoader(), source);
}
catch (Exception e) {
e.printStackTrace();
StartupUtil.showMessage("Consulo", e);
return null;
}
}
/**
* Configure log4j by reading in a log4j.dtd compliant XML
* configuration file.
*/
@Override
public void doConfigure() throws FactoryConfigurationError {
ConfigurationSource source = getConfigurationSource();
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
InputSource inputSource = new InputSource(source.getInputStream());
inputSource.setSystemId("dummy://log4j.dtd");
return parser.parse(inputSource);
}
public String toString() {
return getConfigurationSource().getLocation();
}
};
doConfigure(action);
}
/**
* Configure log4j by reading in a log4j.dtd compliant XML
* configuration file.
*/
private void doConfigure() throws FactoryConfigurationError {
ConfigurationSource source = configuration.getConfigurationSource();
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
InputSource inputSource = new InputSource(source.getInputStream());
inputSource.setSystemId("dummy://log4j.dtd");
return parser.parse(inputSource);
}
public String toString() {
return configuration.getConfigurationSource().getLocation();
}
};
doConfigure(action);
}
private LoggerContext configure(String configLocation) throws Exception {
File file = new File(configLocation);
InputStream is = new FileInputStream(file);
ConfigurationSource source = new ConfigurationSource(is, file);
LoggerContextFactory factory = org.apache.logging.log4j.LogManager.getFactory();
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration;
if (configLocation.endsWith(".xml")) {
configuration = new XmlConfigurationFactory().getConfiguration(context, source);
} else {
configuration = new PropertiesConfigurationFactory().getConfiguration(context, source);
}
assertNotNull("No configuration created", configuration);
Configurator.reconfigure(configuration);
return context;
}
/**
* Constructor to create the default configuration.
*/
public CustomConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
super(loggerContext, source);
setName(CONFIG_NAME);
final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
.setPattern(DEFAULT_PATTERN)
.setConfiguration(this)
.build();
final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
appender.start();
addAppender(appender);
final LoggerConfig root = getRootLogger();
root.addAppender(appender, null, null);
final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL);
final Level level = levelName != null && Level.valueOf(levelName) != null ?
Level.valueOf(levelName) : Level.ERROR;
root.setLevel(level);
}
@Override
public void setConfigText(final String configText, final String charsetName) {
LOGGER.debug("---------");
LOGGER.debug("Remote request to reconfigure from config text.");
try {
final InputStream in = new ByteArrayInputStream(configText.getBytes(charsetName));
final ConfigurationSource source = new ConfigurationSource(in);
final Configuration updated = ConfigurationFactory.getInstance().getConfiguration(loggerContext, source);
loggerContext.start(updated);
LOGGER.debug("Completed remote request to reconfigure from config text.");
} catch (final Exception ex) {
final String msg = "Could not reconfigure from config text";
LOGGER.error(msg, ex);
throw new IllegalArgumentException(msg, ex);
}
}
private ConfigurationSource getConfigurationSource(URL url) throws IOException, URISyntaxException {
URLConnection urlConnection = url.openConnection();
AuthorizationProvider provider = ConfigurationFactory.authorizationProvider(PropertiesUtil.getProperties());
provider.addAuthorization(urlConnection);
if (url.getProtocol().equals(HTTPS)) {
SslConfiguration sslConfiguration = SslConfigurationFactory.getSslConfiguration();
if (sslConfiguration != null) {
((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory());
if (!sslConfiguration.isVerifyHostName()) {
((HttpsURLConnection) urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE);
}
}
}
File file = FileUtils.fileFromUri(url.toURI());
try {
if (file != null) {
return new ConfigurationSource(urlConnection.getInputStream(), FileUtils.fileFromUri(url.toURI()));
} else {
return new ConfigurationSource(urlConnection.getInputStream(), url, urlConnection.getLastModified());
}
} catch (FileNotFoundException ex) {
LOGGER.info("Unable to locate file {}, ignoring.", url.toString());
return null;
}
}
/**
* Loads the LoggerContext using the ContextSelector.
* @param fqcn The fully qualified class name of the caller.
* @param loader The ClassLoader to use or null.
* @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
* @param currentContext If true returns the current Context, if false returns the Context appropriate
* for the caller if a more appropriate Context can be determined.
* @param source The configuration source.
* @return The LoggerContext.
*/
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
final boolean currentContext, final ConfigurationSource source) {
final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null);
if (externalContext != null && ctx.getExternalContext() == null) {
ctx.setExternalContext(externalContext);
}
if (ctx.getState() == LifeCycle.State.INITIALIZED) {
if (source != null) {
ContextAnchor.THREAD_CONTEXT.set(ctx);
final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, source);
LOGGER.debug("Starting LoggerContext[name={}] from configuration {}", ctx.getName(), source);
ctx.start(config);
ContextAnchor.THREAD_CONTEXT.remove();
} else {
ctx.start();
}
}
return ctx;
}
private ConfigurationSource getConfigurationSource(URL url) throws IOException {
InputStream stream = url.openStream();
if (FILE_PROTOCOL.equals(url.getProtocol())) {
return new ConfigurationSource(stream, ResourceUtil.getFile(url));
}
return new ConfigurationSource(stream, url);
}
@Issue("#1466")
@Test
void filterWhenRootLoggerAdditivityIsFalseShouldWork() throws IOException {
ConfigurationSource source = new ConfigurationSource(getClass().getResourceAsStream("/binder/logging/log4j2-root-logger-additivity-false.xml"));
Configurator.initialize(null, source);
Logger logger = LogManager.getLogger(Log4j2MetricsTest.class);
new Log4j2Metrics().bindTo(registry);
assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(0);
logger.info("Hello, world!");
assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1);
}
/**
* Apply the logging configuration.
*/
public void apply() {
LoggerContext context = getLoggerContext();
Configuration config = context.getConfiguration();
ConfigurationSource configSource = config.getConfigurationSource();
String packageHomeDir = WekaPackageManager.getPackageHome().getPath();
if (ConfigurationSource.NULL_SOURCE.equals(configSource)) {
// Use log4j2.xml shipped with the package ...
URI uri = Paths.get(packageHomeDir, "wekaDeeplearning4j", "src", "main", "resources",
"log4j2.xml").toUri();
context.setConfigLocation(uri);
log.info("Logging configuration loaded from source: {}", uri.toString());
}
String fileAppenderName = "fileAppender";
if (!context.getRootLogger().getAppenders().containsKey(fileAppenderName)) {
// Get console appender layout
Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console");
Layout<? extends Serializable> layout = consoleAppender.getLayout();
// Add file appender
String filePath = resolveLogFilePath();
FileAppender.Builder appenderBuilder = new FileAppender.Builder();
appenderBuilder.withFileName(filePath);
appenderBuilder.withAppend(append);
appenderBuilder.withName(fileAppenderName);
appenderBuilder.withLayout(layout);
FileAppender appender = appenderBuilder.build();
appender.start();
context.getRootLogger().addAppender(appender);
}
}
/** Initialize log4j2 from a default (in XML non-strict format) */
private static void defaultLogging() {
byte b[] = StrUtils.asUTF8bytes(getDefaultString());
try (InputStream input = new ByteArrayInputStream(b)) {
ConfigurationSource source = new ConfigurationSource(input);
ConfigurationFactory factory = ConfigurationFactory.getInstance();
Configuration configuration = factory.getConfiguration(null, source);
Configurator.initialize(configuration);
}
catch (IOException ex) {
IOX.exception(ex);
}
}
/**
* Apply the logging configuration.
*/
public void apply() {
LoggerContext context = getLoggerContext();
Configuration config = context.getConfiguration();
ConfigurationSource configSource = config.getConfigurationSource();
String packageHomeDir = WekaPackageManager.getPackageHome().getPath();
if (ConfigurationSource.NULL_SOURCE.equals(configSource)) {
// Use log4j2.xml shipped with the package ...
URI uri = Paths.get(packageHomeDir, "wekaDeeplearning4j", "src", "main", "resources",
"log4j2.xml").toUri();
context.setConfigLocation(uri);
log.info("Logging configuration loaded from source: {}", uri.toString());
}
String fileAppenderName = "fileAppender";
if (!context.getRootLogger().getAppenders().containsKey(fileAppenderName)) {
// Get console appender layout
Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console");
Layout<? extends Serializable> layout = consoleAppender.getLayout();
// Add file appender
String filePath = resolveLogFilePath();
FileAppender.Builder appenderBuilder = new FileAppender.Builder();
appenderBuilder.withFileName(filePath);
appenderBuilder.withAppend(append);
appenderBuilder.withName(fileAppenderName);
appenderBuilder.withLayout(layout);
FileAppender appender = appenderBuilder.build();
appender.start();
context.getRootLogger().addAppender(appender);
}
}
public void run () {
try {
ConfigurationSource cs = new ConfigurationSource(Main.class.getClassLoader().getResourceAsStream("org/logger/config/log4j2.xml"));
Configurator.initialize(null, cs);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//LoggerContext.getContext().setConfiguration(cs);
//System.setProperty("log4j.configurationFile", MyLogger.class.getClassLoader().getResource("org/logger/config/log4j2.xml").getPath());
MyLogger.setMode(MyLogger.CONSOLE_MODE);
MyLogger.setLevel(GlobalConfig.getProperty("loglevel"));
LogManager.getLogger(Main.class).info("JAVA_HOME : "+System.getProperty("java.home"));
OS.getFolderFirmwaresDownloaded();
OS.getFolderFirmwaresPrepared();
OS.getFolderFirmwaresSinExtracted();
OS.getFolderMyDevices();
OS.getFolderRegisteredDevices();
AWTKillerThread k = new AWTKillerThread();
k.start();
try {
Main.initLinuxUsb();
if (console) {
processConsole();
}
else {
MyLogger.setMode(MyLogger.GUI_MODE);
MainSWT window = new MainSWT();
window.open();
}
}
catch (Exception e) {
e.printStackTrace();
}
k.done();
}
@Override
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
try {
setLogDir();
setLevel();
String configuration = readLog4jConfiguration(source.getInputStream());
Properties properties = getProperties();
Matcher m = Pattern.compile("\\$\\{(?:ctx:)?([^}]*)\\}").matcher(configuration); //Look for properties in the Log4J2 XML
Map<String, String> substitutions = new HashMap<>();
while (m.find()) {
String key = m.group(1);
String value = resolveValueRecursively(properties, key);
if(value != null) {
substitutions.put(key, value);
}
}
ThreadContext.putAll(substitutions); //Only add the substituted variables to the ThreadContext
//We have to 'reset' the source as the old stream has been read.
return new XmlConfiguration(loggerContext, source.resetInputStream());
} catch (IOException e) {
System.err.println(LOG_PREFIX + "unable to configure Log4J2");
throw new IllegalStateException(LOG_PREFIX + "unable to configure Log4J2", e);
}
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
final ConfigurationBuilder<BuiltConfiguration> builder;
try (final InputStream configStream = source.getInputStream()) {
builder = new Log4j1ConfigurationParser().buildConfigurationBuilder(configStream);
} catch (final IOException e) {
throw new ConfigurationException("Unable to load " + source, e);
}
return builder.build();
}
/**
* Read the configuration file <code>configFilename</code> if it
* exists. Moreover, a thread will be created that will periodically
* check if <code>configFilename</code> has been created or
* modified. The period is determined by the <code>delay</code>
* argument. If a change or file creation is detected, then
* <code>configFilename</code> is read to configure log4j.
*
* @param configFilename A log4j configuration file in XML format.
* @param delay The delay in milliseconds to wait between each check.
*/
public static void configureAndWatch(final String configFilename, final long delay) {
try {
File file = new File(configFilename);
InputStream is = new FileInputStream(file);
ConfigurationSource source = new ConfigurationSource(is, file);
int seconds = (int) TimeUnit.MILLISECONDS.toSeconds(delay);
XmlConfigurationFactory factory = new XmlConfigurationFactory(source, seconds);
factory.doConfigure();
org.apache.logging.log4j.core.config.Configurator.reconfigure(factory.getConfiguration());
} catch (IOException ioe) {
LOGGER.error("Unable to process configuration file {} due to {}", configFilename, ioe.getMessage());
}
}
/**
* A static version of doConfigure(URL).
*/
public static void configure(final URL url) throws FactoryConfigurationError {
try {
InputStream is = url.openStream();
ConfigurationSource source = new ConfigurationSource(is, url);
XmlConfigurationFactory factory = new XmlConfigurationFactory(source, 0);
factory.doConfigure();
org.apache.logging.log4j.core.config.Configurator.reconfigure(factory.getConfiguration());
} catch (IOException ioe) {
LOGGER.error("Unable to process configuration {} due to {}", url.toString(), ioe.getMessage());
}
}
@Override
public void doConfigure(InputStream inputStream, LoggerContext loggerContext) {
try {
ConfigurationSource source = new ConfigurationSource(inputStream);
configuration = new Log4j1Configuration(loggerContext, source, 0);
doConfigure();
} catch (IOException ioe) {
LOGGER.error("Unable to process configuration due to {}", ioe.getMessage());
}
}
@Override
public void doConfigure(URL url, LoggerContext loggerContext) {
try {
ConfigurationSource source = new ConfigurationSource(url.openStream(), url);
configuration = new Log4j1Configuration(loggerContext, source, 0);
doConfigure();
} catch (IOException ioe) {
LOGGER.error("Unable to process configuration due to {}", ioe.getMessage());
}
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
final ConfigurationBuilder<BuiltConfiguration> builder;
try (final InputStream configStream = source.getInputStream()) {
builder = new Log4j1ConfigurationParser().buildConfigurationBuilder(configStream);
} catch (final IOException e) {
throw new ConfigurationException("Unable to load " + source, e);
}
return builder.build();
}
public BasicConfiguration(final LoggerContext loggerContext) {
super(loggerContext, ConfigurationSource.NULL_SOURCE);
final LoggerConfig root = getRootLogger();
setName("BasicConfiguration");
final String levelName = System.getProperty(DEFAULT_LEVEL);
final Level level = (levelName != null && Level.getLevel(levelName) != null) ? Level.getLevel(levelName)
: Level.DEBUG;
root.setLevel(level);
}
public BasicConfiguration(final LoggerContext loggerContext) {
super(loggerContext, ConfigurationSource.NULL_SOURCE);
final LoggerConfig root = getRootLogger();
setName("BasicConfiguration");
final String levelName = System.getProperty(DEFAULT_LEVEL);
final Level level = (levelName != null && Level.getLevel(levelName) != null) ? Level.getLevel(levelName)
: Level.DEBUG;
root.setLevel(level);
}
private LoggerContext configure(String configLocation) throws Exception {
File file = new File(configLocation);
InputStream is = new FileInputStream(file);
ConfigurationSource source = new ConfigurationSource(is, file);
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = new PropertiesConfigurationFactory().getConfiguration(context, source);
assertNotNull("No configuration created", configuration);
Configurator.reconfigure(configuration);
return context;
}
private LoggerContext configure(String configLocation) throws Exception {
File file = new File(configLocation);
InputStream is = new FileInputStream(file);
ConfigurationSource source = new ConfigurationSource(is, file);
LoggerContextFactory factory = org.apache.logging.log4j.LogManager.getFactory();
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = new XmlConfigurationFactory().getConfiguration(context, source);
assertNotNull("No configuration created", configuration);
Configurator.reconfigure(configuration);
return context;
}
@Override
public String getConfigText(final String charsetName) throws IOException {
try {
final ConfigurationSource source = loggerContext.getConfiguration().getConfigurationSource();
final ConfigurationSource copy = source.resetInputStream();
final Charset charset = Charset.forName(charsetName);
return readContents(copy.getInputStream(), charset);
} catch (final Exception ex) {
final StringWriter sw = new StringWriter(BUFFER_SIZE);
ex.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
if (!isActive) {
return null;
}
return new YamlConfiguration(loggerContext, source);
}
@Override
public Configuration reconfigure() {
try {
final ConfigurationSource source = getConfigurationSource().resetInputStream();
if (source == null) {
return null;
}
return new YamlConfiguration(getLoggerContext(), source);
} catch (final IOException ex) {
LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex);
}
return null;
}
@Override
public Configuration reconfigure() {
try {
final ConfigurationSource source = getConfigurationSource().resetInputStream();
if (source == null) {
return null;
}
return new JsonConfiguration(getLoggerContext(), source);
} catch (final IOException ex) {
LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex);
}
return null;
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
if (!isActive) {
return null;
}
return new JsonConfiguration(loggerContext, source);
}