下面列出了怎么用org.apache.logging.log4j.util.PropertiesUtil的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* <em>Consider private, used for testing.</em>
*/
static void init() {
ThreadContextMapFactory.init();
contextMap = null;
final PropertiesUtil managerProps = PropertiesUtil.getProperties();
boolean disableAll = managerProps.getBooleanProperty(DISABLE_ALL);
useStack = !(managerProps.getBooleanProperty(DISABLE_STACK) || disableAll);
boolean useMap = !(managerProps.getBooleanProperty(DISABLE_MAP) || disableAll);
contextStack = new DefaultThreadContextStack(useStack);
if (!useMap) {
contextMap = new NoOpThreadContextMap();
} else {
contextMap = ThreadContextMapFactory.createThreadContextMap();
}
if (contextMap instanceof ReadOnlyThreadContextMap) {
readOnlyContextMap = (ReadOnlyThreadContextMap) contextMap;
} else {
readOnlyContextMap = null;
}
}
/**
* 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);
}
public void tearDown() throws SQLException {
final LoggerContext context = LoggerContext.getContext(false);
try {
String appenderName = "databaseAppender";
final Appender appender = context.getConfiguration().getAppender(appenderName);
assertNotNull("The appender '" + appenderName + "' should not be null.", appender);
assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender);
((JpaAppender) appender).getManager().close();
} finally {
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
PropertiesUtil.getProperties().reload();
context.reconfigure();
StatusLogger.getLogger().reset();
try (Statement statement = this.connection.createStatement();) {
statement.execute("SHUTDOWN");
}
this.connection.close();
}
}
private static Clock createClock() {
final String userRequest = PropertiesUtil.getProperties().getStringProperty(PROPERTY_NAME);
if (userRequest == null) {
LOGGER.trace("Using default SystemClock for timestamps.");
return logSupportedPrecision(new SystemClock());
}
Supplier<Clock> specified = aliases().get(userRequest);
if (specified != null) {
LOGGER.trace("Using specified {} for timestamps.", userRequest);
return logSupportedPrecision(specified.get());
}
try {
final Clock result = Loader.newCheckedInstanceOf(userRequest, Clock.class);
LOGGER.trace("Using {} for timestamps.", result.getClass().getName());
return logSupportedPrecision(result);
} catch (final Exception e) {
final String fmt = "Could not create {}: {}, using default SystemClock for timestamps.";
LOGGER.error(fmt, userRequest, e);
return logSupportedPrecision(new SystemClock());
}
}
@Override
public void start(final BundleContext context) throws Exception {
pluginRegistration = context.registerService(PluginService.class.getName(), new Log4jPlugins(),
new Hashtable<>());
final Provider provider = new Log4jProvider();
final Hashtable<String, String> props = new Hashtable<>();
props.put("APIVersion", "2.60");
final ContextDataProvider threadContextProvider = new ThreadContextDataProvider();
provideRegistration = context.registerService(Provider.class.getName(), provider, props);
contextDataRegistration = context.registerService(ContextDataProvider.class.getName(), threadContextProvider,
null);
loadContextProviders(context);
// allow the user to override the default ContextSelector (e.g., by using BasicContextSelector for a global cfg)
if (PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR) == null) {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BundleContextSelector.class.getName());
}
contextRef.compareAndSet(null, context);
}
protected void setToDefault() {
// LOG4J2-1176 facilitate memory leak investigation
setName(DefaultConfiguration.DEFAULT_NAME + "@" + Integer.toHexString(hashCode()));
final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
.setPattern(DefaultConfiguration.DEFAULT_PATTERN)
.setConfiguration(this)
.build();
final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
appender.start();
addAppender(appender);
final LoggerConfig rootLoggerConfig = getRootLogger();
rootLoggerConfig.addAppender(appender, null, null);
final Level defaultLevel = Level.ERROR;
final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL,
defaultLevel.name());
final Level level = Level.valueOf(levelName);
rootLoggerConfig.setLevel(level != null ? level : defaultLevel);
}
private AppenderComponentBuilder createAppender(final String key, final Properties properties) {
final String name = (String) properties.remove(CONFIG_NAME);
if (Strings.isEmpty(name)) {
throw new ConfigurationException("No name attribute provided for Appender " + key);
}
final String type = (String) properties.remove(CONFIG_TYPE);
if (Strings.isEmpty(type)) {
throw new ConfigurationException("No type attribute provided for Appender " + key);
}
final AppenderComponentBuilder appenderBuilder = builder.newAppender(name, type);
addFiltersToComponent(appenderBuilder, properties);
final Properties layoutProps = PropertiesUtil.extractSubset(properties, "layout");
if (layoutProps.size() > 0) {
appenderBuilder.add(createLayout(name, layoutProps));
}
return processRemainingProperties(appenderBuilder, properties);
}
private static <B extends ComponentBuilder<?>> B processRemainingProperties(final B builder,
final Properties properties) {
while (properties.size() > 0) {
final String propertyName = properties.stringPropertyNames().iterator().next();
final int index = propertyName.indexOf('.');
if (index > 0) {
final String prefix = propertyName.substring(0, index);
final Properties componentProperties = PropertiesUtil.extractSubset(properties, prefix);
builder.addComponent(createComponent(builder, prefix, componentProperties));
} else {
builder.addAttribute(propertyName, properties.getProperty(propertyName));
properties.remove(propertyName);
}
}
return builder;
}
/**
* Returns a new {@code ReliabilityStrategy} instance based on the value of system property
* {@code log4j.ReliabilityStrategy}. If not value was specified this method returns a new
* {@code AwaitUnconditionallyReliabilityStrategy}.
* <p>
* Valid values for this system property are {@code "AwaitUnconditionally"} (use
* {@code AwaitUnconditionallyReliabilityStrategy}), {@code "Locking"} (use {@code LockingReliabilityStrategy}) and
* {@code "AwaitCompletion"} (use the default {@code AwaitCompletionReliabilityStrategy}).
* <p>
* Users may also use this system property to specify the fully qualified class name of a class that implements the
* {@code ReliabilityStrategy} and has a constructor that accepts a single {@code LoggerConfig} argument.
*
* @param loggerConfig the LoggerConfig the resulting {@code ReliabilityStrategy} is associated with
* @return a ReliabilityStrategy that helps the specified LoggerConfig to log events reliably during or after a
* configuration change
*/
public static ReliabilityStrategy getReliabilityStrategy(final LoggerConfig loggerConfig) {
final String strategy = PropertiesUtil.getProperties().getStringProperty("log4j.ReliabilityStrategy",
"AwaitCompletion");
if ("AwaitCompletion".equals(strategy)) {
return new AwaitCompletionReliabilityStrategy(loggerConfig);
}
if ("AwaitUnconditionally".equals(strategy)) {
return new AwaitUnconditionallyReliabilityStrategy(loggerConfig);
}
if ("Locking".equals(strategy)) {
return new LockingReliabilityStrategy(loggerConfig);
}
try {
final Class<? extends ReliabilityStrategy> cls = Loader.loadClass(strategy).asSubclass(
ReliabilityStrategy.class);
return cls.getConstructor(LoggerConfig.class).newInstance(loggerConfig);
} catch (final Exception dynamicFailed) {
StatusLogger.getLogger().warn(
"Could not create ReliabilityStrategy for '{}', using default AwaitCompletionReliabilityStrategy: {}", strategy, dynamicFailed);
return new AwaitCompletionReliabilityStrategy(loggerConfig);
}
}
public static AuthorizationProvider authorizationProvider(PropertiesUtil props) {
final String authClass = props.getStringProperty(AUTHORIZATION_PROVIDER);
AuthorizationProvider provider = null;
if (authClass != null) {
try {
Object obj = LoaderUtil.newInstanceOf(authClass);
if (obj instanceof AuthorizationProvider) {
provider = (AuthorizationProvider) obj;
} else {
LOGGER.warn("{} is not an AuthorizationProvider, using default", obj.getClass().getName());
}
} catch (Exception ex) {
LOGGER.warn("Unable to create {}, using default: {}", authClass, ex.getMessage());
}
}
if (provider == null) {
provider = new BasicAuthorizationProvider(props);
}
return provider;
}
public BasicAuthorizationProvider(PropertiesUtil props) {
String userName = props.getStringProperty(PREFIXES,AUTH_USER_NAME,
() -> props.getStringProperty(CONFIG_USER_NAME));
String password = props.getStringProperty(PREFIXES, AUTH_PASSWORD,
() -> props.getStringProperty(CONFIG_PASSWORD));
String decryptor = props.getStringProperty(PREFIXES, AUTH_PASSWORD_DECRYPTOR,
() -> props.getStringProperty(PASSWORD_DECRYPTOR));
if (decryptor != null) {
try {
Object obj = LoaderUtil.newInstanceOf(decryptor);
if (obj instanceof PasswordDecryptor) {
password = ((PasswordDecryptor) obj).decryptPassword(password);
}
} catch (Exception ex) {
LOGGER.warn("Unable to decrypt password.", ex);
}
}
if (userName != null && password != null) {
authString = "Basic " + encoder.encodeToString((userName + ":" + password).getBytes());
}
}
@Override
public void start() {
LOGGER.debug("Starting LoggerContext[name={}, {}]...", getName(), this);
if (PropertiesUtil.getProperties().getBooleanProperty("log4j.LoggerContext.stacktrace.on.start", false)) {
LOGGER.debug("Stack trace to locate invoker",
new Exception("Not a real error, showing stack trace to locate invoker"));
}
if (configLock.tryLock()) {
try {
if (this.isInitialized() || this.isStopped()) {
this.setStarting();
reconfigure();
if (this.configuration.isShutdownHookEnabled()) {
setUpShutdownHook();
}
this.setStarted();
}
} finally {
configLock.unlock();
}
}
LOGGER.debug("LoggerContext[name={}, {}] started OK.", getName(), this);
}
static WaitStrategy createWaitStrategy(final String propertyName, final long timeoutMillis) {
final String strategy = PropertiesUtil.getProperties().getStringProperty(propertyName, "TIMEOUT");
LOGGER.trace("property {}={}", propertyName, strategy);
final String strategyUp = strategy.toUpperCase(Locale.ROOT); // TODO Refactor into Strings.toRootUpperCase(String)
switch (strategyUp) { // TODO Define a DisruptorWaitStrategy enum?
case "SLEEP":
return new SleepingWaitStrategy();
case "YIELD":
return new YieldingWaitStrategy();
case "BLOCK":
return new BlockingWaitStrategy();
case "BUSYSPIN":
return new BusySpinWaitStrategy();
case "TIMEOUT":
return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS);
default:
return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS);
}
}
static int calculateRingBufferSize(final String propertyName) {
int ringBufferSize = Constants.ENABLE_THREADLOCALS ? RINGBUFFER_NO_GC_DEFAULT_SIZE : RINGBUFFER_DEFAULT_SIZE;
final String userPreferredRBSize = PropertiesUtil.getProperties().getStringProperty(propertyName,
String.valueOf(ringBufferSize));
try {
int size = Integer.parseInt(userPreferredRBSize);
if (size < RINGBUFFER_MIN_SIZE) {
size = RINGBUFFER_MIN_SIZE;
LOGGER.warn("Invalid RingBufferSize {}, using minimum size {}.", userPreferredRBSize,
RINGBUFFER_MIN_SIZE);
}
ringBufferSize = size;
} catch (final Exception ex) {
LOGGER.warn("Invalid RingBufferSize {}, using default size {}.", userPreferredRBSize, ringBufferSize);
}
return Integers.ceilingNextPowerOfTwo(ringBufferSize);
}
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;
}
}
private static @Nullable Boolean getOptionalBooleanProperty(String name) {
String value = PropertiesUtil.getProperties().getStringProperty(name);
if (value == null) {
return null;
}
if (value.equalsIgnoreCase("true")) {
return Boolean.TRUE;
} else if (value.equalsIgnoreCase("false")) {
return Boolean.FALSE;
} else {
LOGGER.warn("Invalid value for boolean input property '{}': {}", name, value);
return null;
}
}
/**
* Get or create a logger with the given name.
*
* @param name The name of the logger.
* @return The logger with the given name.
*/
public static Logger getLogger(String name) {
AtomicBoolean logWarning = new AtomicBoolean(false);
initialized.updateAndGet(initialized -> {
if (!initialized && !ProviderUtil.hasProviders()) {
noLogger.set(true);
logWarning.set(true);
}
return true;
});
if (noLogger.get()) {
return loggers.computeIfAbsent(name, key -> {
Level level = FallbackLoggerConfiguration.isTraceEnabled()
? Level.TRACE
: (FallbackLoggerConfiguration.isDebugEnabled() ? Level.DEBUG : Level.INFO);
Logger logger = new SimpleLogger(name, level, true, false, true, true, "yyyy-MM-dd HH:mm:ss.SSSZ", null,
new PropertiesUtil(new Properties()), System.out);
if (logWarning.get()) {
logger.info("No Log4j2 compatible logger was found. Using default Javacord implementation!");
}
return new PrivacyProtectionLogger(logger);
});
} else {
return new PrivacyProtectionLogger(LogManager.getLogger(name));
}
}
/**
* Get or create a logger with the given name.
*
* @param name The name of the logger.
* @return The logger with the given name.
*/
public static Logger getLogger(String name) {
AtomicBoolean logWarning = new AtomicBoolean(false);
initialized.updateAndGet(initialized -> {
if (!initialized && !ProviderUtil.hasProviders()) {
noLogger.set(true);
logWarning.set(true);
}
return true;
});
if (noLogger.get()) {
return loggers.computeIfAbsent(name, key -> {
Level level = FallbackLoggerConfiguration.isTraceEnabled()
? Level.TRACE
: (FallbackLoggerConfiguration.isDebugEnabled() ? Level.DEBUG : Level.INFO);
Logger logger = new SimpleLogger(name, level, true, false, true, true, "yyyy-MM-dd HH:mm:ss.SSSZ", null,
new PropertiesUtil(new Properties()), System.out);
if (logWarning.get()) {
logger.info("No Log4j2 compatible logger was found. Using default Javacord implementation!");
}
return new PrivacyProtectionLogger(logger);
});
} else {
return new PrivacyProtectionLogger(LogManager.getLogger(name));
}
}
private static Class<? extends MessageFactory> createClassForProperty(final String property,
final Class<ReusableMessageFactory> reusableParameterizedMessageFactoryClass,
final Class<ParameterizedMessageFactory> parameterizedMessageFactoryClass) {
try {
final String fallback = Constants.ENABLE_THREADLOCALS ? reusableParameterizedMessageFactoryClass.getName()
: parameterizedMessageFactoryClass.getName();
final String clsName = PropertiesUtil.getProperties().getStringProperty(property, fallback);
return LoaderUtil.loadClass(clsName).asSubclass(MessageFactory.class);
} catch (final Throwable t) {
return parameterizedMessageFactoryClass;
}
}
private static Class<? extends FlowMessageFactory> createFlowClassForProperty(final String property,
final Class<DefaultFlowMessageFactory> defaultFlowMessageFactoryClass) {
try {
final String clsName = PropertiesUtil.getProperties().getStringProperty(property, defaultFlowMessageFactoryClass.getName());
return LoaderUtil.loadClass(clsName).asSubclass(FlowMessageFactory.class);
} catch (final Throwable t) {
return defaultFlowMessageFactoryClass;
}
}
@Override
public void cancel() {
// LOG4J2-1850 Cassandra on Windows calls System.exit in the daemon stop method
if (PropertiesUtil.getProperties().isOsWindows()) {
cancelOnWindows();
} else {
daemon.stop();
}
}
@Override
public SmtpManager createManager(final String name, final FactoryData data) {
final String prefix = "mail." + data.protocol;
final Properties properties = PropertiesUtil.getSystemProperties();
properties.setProperty("mail.transport.protocol", data.protocol);
if (properties.getProperty("mail.host") == null) {
// Prevent an UnknownHostException in Java 7
properties.setProperty("mail.host", NetUtils.getLocalHostname());
}
if (null != data.host) {
properties.setProperty(prefix + ".host", data.host);
}
if (data.port > 0) {
properties.setProperty(prefix + ".port", String.valueOf(data.port));
}
final Authenticator authenticator = buildAuthenticator(data.username, data.password);
if (null != authenticator) {
properties.setProperty(prefix + ".auth", "true");
}
if (data.protocol.equals("smtps")) {
final SslConfiguration sslConfiguration = data.sslConfiguration;
if (sslConfiguration != null) {
final SSLSocketFactory sslSocketFactory = sslConfiguration.getSslSocketFactory();
properties.put(prefix + ".ssl.socketFactory", sslSocketFactory);
properties.setProperty(prefix + ".ssl.checkserveridentity", Boolean.toString(sslConfiguration.isVerifyHostName()));
}
}
final Session session = Session.getInstance(properties, authenticator);
session.setProtocolForAddress("rfc822", data.protocol);
session.setDebug(data.isDebug);
return new SmtpManager(name, session, null, data);
}
@Override
protected String[] getSupportedTypes() {
if (!PropertiesUtil.getProperties().getBooleanProperty(ConfigurationFactory.LOG4J1_EXPERIMENTAL, Boolean.FALSE)) {
return null;
}
return new String[] {".xml"};
}
@Override
protected String[] getSupportedTypes() {
if (!PropertiesUtil.getProperties().getBooleanProperty(ConfigurationFactory.LOG4J1_EXPERIMENTAL, Boolean.FALSE)) {
return null;
}
return new String[] {".properties"};
}
public void setUp(final String configFileName) throws SQLException {
this.connection = this.setUpConnection();
final String resource = "org/apache/logging/log4j/jpa/appender/" + configFileName;
assertNotNull(getClass().getClassLoader().getResource(resource));
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
resource);
PropertiesUtil.getProperties().reload();
final LoggerContext context = LoggerContext.getContext(false);
if (context.getConfiguration() instanceof DefaultConfiguration) {
context.reconfigure();
}
StatusLogger.getLogger().reset();
}
protected Level getDefaultStatus() {
final String statusLevel = PropertiesUtil.getProperties().getStringProperty(
Constants.LOG4J_DEFAULT_STATUS_LEVEL, Level.ERROR.name());
try {
return Level.toLevel(statusLevel);
} catch (final Exception ex) {
return Level.ERROR;
}
}
private <B extends FilterableComponentBuilder<? extends ComponentBuilder<?>>> B addFiltersToComponent(
final B componentBuilder, final Properties properties) {
final Map<String, Properties> filters = PropertiesUtil.partitionOnCommonPrefixes(
PropertiesUtil.extractSubset(properties, "filter"));
for (final Map.Entry<String, Properties> entry : filters.entrySet()) {
componentBuilder.add(createFilter(entry.getKey().trim(), entry.getValue()));
}
return componentBuilder;
}
private <B extends LoggableComponentBuilder<? extends ComponentBuilder<?>>> B addLoggersToComponent(
final B loggerBuilder, final Properties properties) {
final Map<String, Properties> appenderRefs = PropertiesUtil.partitionOnCommonPrefixes(
PropertiesUtil.extractSubset(properties, "appenderRef"));
for (final Map.Entry<String, Properties> entry : appenderRefs.entrySet()) {
loggerBuilder.add(createAppenderRef(entry.getKey().trim(), entry.getValue()));
}
return loggerBuilder;
}
/**
* Construct the CompositeConfiguration.
*
* @param configurations The List of Configurations to merge.
*/
public CompositeConfiguration(final List<? extends AbstractConfiguration> configurations) {
super(configurations.get(0).getLoggerContext(), ConfigurationSource.COMPOSITE_SOURCE);
rootNode = configurations.get(0).getRootNode();
this.configurations = configurations;
final String mergeStrategyClassName = PropertiesUtil.getProperties().getStringProperty(MERGE_STRATEGY_PROPERTY,
DefaultMergeStrategy.class.getName());
try {
mergeStrategy = Loader.newInstanceOf(mergeStrategyClassName);
} catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException |
InstantiationException ex) {
mergeStrategy = new DefaultMergeStrategy();
}
for (final AbstractConfiguration config : configurations) {
mergeStrategy.mergeRootProperties(rootNode, config);
}
final StatusConfiguration statusConfig = new StatusConfiguration().setVerboseClasses(VERBOSE_CLASSES)
.setStatus(getDefaultStatus());
for (final Map.Entry<String, String> entry : rootNode.getAttributes().entrySet()) {
final String key = entry.getKey();
final String value = getStrSubstitutor().replace(entry.getValue());
if ("status".equalsIgnoreCase(key)) {
statusConfig.setStatus(value.toUpperCase());
} else if ("dest".equalsIgnoreCase(key)) {
statusConfig.setDestination(value);
} else if ("shutdownHook".equalsIgnoreCase(key)) {
isShutdownHookEnabled = !"disable".equalsIgnoreCase(value);
} else if ("shutdownTimeout".equalsIgnoreCase(key)) {
shutdownTimeoutMillis = Long.parseLong(value);
} else if ("verbose".equalsIgnoreCase(key)) {
statusConfig.setVerbosity(value);
} else if ("packages".equalsIgnoreCase(key)) {
pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR)));
} else if ("name".equalsIgnoreCase(key)) {
setName(value);
}
}
statusConfig.initialize();
}
static ExceptionHandler<RingBufferLogEvent> getAsyncLoggerExceptionHandler() {
final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ExceptionHandler");
if (cls == null) {
return new AsyncLoggerDefaultExceptionHandler();
}
try {
@SuppressWarnings("unchecked")
final Class<? extends ExceptionHandler<RingBufferLogEvent>> klass =
(Class<? extends ExceptionHandler<RingBufferLogEvent>>) Loader.loadClass(cls);
return klass.newInstance();
} catch (final Exception ignored) {
LOGGER.debug("Invalid AsyncLogger.ExceptionHandler value: error creating {}: ", cls, ignored);
return new AsyncLoggerDefaultExceptionHandler();
}
}