Java 类org.apache.logging.log4j.util.PropertiesUtil 实例源码

项目:camel-standalone    文件:StandaloneLoggerConfiguration.java   
/**
 * Constructor to create the default configuration.
 */
public StandaloneLoggerConfiguration(ConfigurationSource source) {
    super(source);

    setName(CONFIG_NAME);
    final Appender appender = StandaloneLogEventAppender.createAppender("StandaloneLogAppender", 1000);
    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.ALL;
    root.setLevel(level);
}
项目:log4j2    文件:BaseConfiguration.java   
private void setToDefault() {
    setName(DefaultConfiguration.DEFAULT_NAME);
    final Layout<? extends Serializable> layout =
            PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n",
                    null, null, null, null);
    final Appender appender = ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false",
        "true");
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
        Level.valueOf(levelName) : Level.ERROR;
    root.setLevel(level);
}
项目:log4j2    文件:DefaultConfiguration.java   
/**
 * Constructor to create the default configuration.
 */
public DefaultConfiguration() {

    setName(DEFAULT_NAME);
    final Layout<? extends Serializable> layout =
            PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n", null, null, null, null);
    final Appender appender =
            ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false", "true");
    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);
}
项目:logging-log4j2    文件:ThreadContext.java   
/**
 * <em>Consider private, used for testing.</em>
 */
static void init() {
    ThreadContextMapFactory.init();
    contextMap = null;
    final PropertiesUtil managerProps = PropertiesUtil.getProperties();
    disableAll = managerProps.getBooleanProperty(DISABLE_ALL);
    useStack = !(managerProps.getBooleanProperty(DISABLE_STACK) || disableAll);
    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;
    }
}
项目:logging-log4j2    文件:CustomConfiguration.java   
/**
 * 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()
            .withPattern(DEFAULT_PATTERN)
            .withConfiguration(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);
}
项目:logging-log4j2    文件:AbstractJpaAppenderTest.java   
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();
    }
}
项目:logging-log4j2    文件:ClockFactory.java   
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());
    }
}
项目:logging-log4j2    文件:Activator.java   
@Override
public void start(final BundleContext context) throws Exception {
    final Provider provider = new Log4jProvider();
    final Hashtable<String, String> props = new Hashtable<>();
    props.put("APIVersion", "2.60");
    provideRegistration = context.registerService(Provider.class.getName(), provider, props);
    // 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());
    }
    if (this.contextRef.compareAndSet(null, context)) {
        context.addBundleListener(this);
        // done after the BundleListener as to not miss any new bundle installs in the interim
        scanInstalledBundlesForPlugins(context);
    }
}
项目:logging-log4j2    文件:AbstractConfiguration.java   
protected void setToDefault() {
    // LOG4J2-1176 facilitate memory leak investigation
    setName(DefaultConfiguration.DEFAULT_NAME + "@" + Integer.toHexString(hashCode()));
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .withPattern(DefaultConfiguration.DEFAULT_PATTERN)
            .withConfiguration(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);
}
项目:logging-log4j2    文件:PropertiesConfigurationBuilder.java   
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);
}
项目:logging-log4j2    文件:PropertiesConfigurationBuilder.java   
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;
}
项目:logging-log4j2    文件:ReliabilityStrategyFactory.java   
/**
 * 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 = LoaderUtil.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);
    }
}
项目:logging-log4j2    文件:LoggerContext.java   
@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);
}
项目:logging-log4j2    文件:DisruptorUtil.java   
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);
    }
}
项目:logging-log4j2    文件:DisruptorUtil.java   
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);
}
项目:MyTown2    文件:TestMain.java   
public static void main() {
    PrintStream ps = new PrintStream(new FileOutputStream(FileDescriptor.out));
    MyTown.instance = new MyTown();
    MyTown.instance.LOG = new SimpleLogger("MyTown2-Test", Level.INFO, true, true, false, false, "DD/MM/YY", null, PropertiesUtil.getProperties(), ps);

    ps = new PrintStream(new FileOutputStream(FileDescriptor.out));
    MyEssentialsCore.instance = new MyEssentialsCore();
    MyEssentialsCore.instance.LOG = new SimpleLogger("MyEssentials-Core-Test", Level.INFO, true, true, false, false, "DD/MM/YY", null, PropertiesUtil.getProperties(), ps);
}
项目:log4j2    文件:StatusConsoleListener.java   
/**
 * Creates the StatusConsoleListener using either the level configured by the
 * "org.apache.logging.log4j.StatusLevel" system property if it is set or to a
 * default value of FATAL.
 */
public StatusConsoleListener() {
    final String str = PropertiesUtil.getProperties().getStringProperty(STATUS_LEVEL);
    if (str != null) {
        level = Level.toLevel(str, Level.FATAL);
    }
    stream = System.out;
}
项目:log4j2    文件:SimpleLogger.java   
public SimpleLogger(final String name, final Level defaultLevel, final boolean showLogName,
                    final boolean showShortLogName, final boolean showDateTime, final boolean showContextMap,
                    final String dateTimeFormat, final MessageFactory messageFactory, final PropertiesUtil props,
                    final PrintStream stream) {
    super(name, messageFactory);
    final String lvl = props.getStringProperty(SimpleLoggerContext.SYSTEM_PREFIX + name + ".level");
    this.level = Level.toLevel(lvl, defaultLevel);
    if (showShortLogName) {
        final int index = name.lastIndexOf(".");
        if (index > 0 && index < name.length()) {
            this.logName = name.substring(index + 1);
        } else {
            this.logName = name;
        }
    } else if (showLogName) {
        this.logName = name;
    } else {
        this.logName = null;
    }
    this.showDateTime = showDateTime;
    this.showContextMap = showContextMap;
    this.stream = stream;

    if (showDateTime) {
        try {
            this.dateFormatter = new SimpleDateFormat(dateTimeFormat);
        } catch (final IllegalArgumentException e) {
            // If the format pattern is invalid - use the default format
            this.dateFormatter = new SimpleDateFormat(SimpleLoggerContext.DEFAULT_DATE_TIME_FORMAT);
        }
    }
}
项目:log4j2    文件:SimpleLoggerContext.java   
public SimpleLoggerContext() {
    props = new PropertiesUtil("log4j2.simplelog.properties");

    showContextMap = props.getBooleanProperty(SYSTEM_PREFIX + "showContextMap", false);
    showLogName = props.getBooleanProperty(SYSTEM_PREFIX + "showlogname", false);
    showShortName = props.getBooleanProperty(SYSTEM_PREFIX + "showShortLogname", true);
    showDateTime = props.getBooleanProperty(SYSTEM_PREFIX + "showdatetime", false);
    final String lvl = props.getStringProperty(SYSTEM_PREFIX + "level");
    defaultLevel = Level.toLevel(lvl, Level.ERROR);

    dateTimeFormat = showDateTime ? props.getStringProperty(SimpleLoggerContext.SYSTEM_PREFIX + "dateTimeFormat",
            DEFAULT_DATE_TIME_FORMAT) : null;

    final String fileName = props.getStringProperty(SYSTEM_PREFIX + "logFile", "system.err");
    PrintStream ps;
    if ("system.err".equalsIgnoreCase(fileName)) {
        ps = System.err;
    } else if ("system.out".equalsIgnoreCase(fileName)) {
        ps = System.out;
    } else {
        try {
            final FileOutputStream os = new FileOutputStream(fileName);
            ps = new PrintStream(os);
        } catch (final FileNotFoundException fnfe) {
            ps = System.err;
        }
    }
    this.stream = ps;
}
项目:log4j2    文件:BaseConfiguration.java   
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;
    }
}
项目:log4j2    文件:ConfigurationFactory.java   
/**
 * Returns the ConfigurationFactory.
 * @return the ConfigurationFactory.
 */
public static ConfigurationFactory getInstance() {
    if (factories == null) {
        synchronized(TEST_PREFIX) {
            if (factories == null) {
                final List<ConfigurationFactory> list = new ArrayList<ConfigurationFactory>();
                final String factoryClass = PropertiesUtil.getProperties().getStringProperty(CONFIGURATION_FACTORY_PROPERTY);
                if (factoryClass != null) {
                    addFactory(list, factoryClass);
                }
                final PluginManager manager = new PluginManager("ConfigurationFactory");
                manager.collectPlugins();
                final Map<String, PluginType<?>> plugins = manager.getPlugins();
                final Set<WeightedFactory> ordered = new TreeSet<WeightedFactory>();
                for (final PluginType<?> type : plugins.values()) {
                    try {
                        @SuppressWarnings("unchecked")
                        final Class<ConfigurationFactory> clazz = (Class<ConfigurationFactory>)type.getPluginClass();
                        final Order order = clazz.getAnnotation(Order.class);
                        if (order != null) {
                            final int weight = order.value();
                            ordered.add(new WeightedFactory(weight, clazz));
                        }
                    } catch (final Exception ex) {
                        LOGGER.warn("Unable to add class " + type.getPluginClass());
                    }
                }
                for (final WeightedFactory wf : ordered) {
                    addFactory(list, wf.factoryClass);
                }
                factories = Collections.unmodifiableList(list);
            }
        }
    }

    return configFactory;
}
项目:log4j2    文件:SMTPManager.java   
@Override
public SMTPManager createManager(final String name, final FactoryData data) {
    final String prefix = "mail." + data.protocol;

    final Properties properties = PropertiesUtil.getSystemProperties();
    properties.put("mail.transport.protocol", data.protocol);
    if (properties.getProperty("mail.host") == null) {
        // Prevent an UnknownHostException in Java 7
        properties.put("mail.host", NetUtils.getLocalHostname());
    }

    if (null != data.host) {
        properties.put(prefix + ".host", data.host);
    }
    if (data.port > 0) {
        properties.put(prefix + ".port", String.valueOf(data.port));
    }

    final Authenticator authenticator = buildAuthenticator(data.username, data.password);
    if (null != authenticator) {
        properties.put(prefix + ".auth", "true");
    }

    final Session session = Session.getInstance(properties, authenticator);
    session.setProtocolForAddress("rfc822", data.protocol);
    session.setDebug(data.isDebug);
    MimeMessage message;

    try {
        message = new MimeMessageBuilder(session).setFrom(data.from).setReplyTo(data.replyto)
            .setRecipients(Message.RecipientType.TO, data.to).setRecipients(Message.RecipientType.CC, data.cc)
            .setRecipients(Message.RecipientType.BCC, data.bcc).setSubject(data.subject).getMimeMessage();
    } catch (final MessagingException e) {
        LOGGER.error("Could not set SMTPAppender message options.", e);
        message = null;
    }

    return new SMTPManager(name, session, message, data);
}
项目:logging-log4j2    文件:AbstractLogger.java   
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;
    }
}
项目:logging-log4j2    文件:AbstractLogger.java   
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;
    }
}
项目:logging-log4j2    文件:SimpleLogger.java   
public SimpleLogger(final String name, final Level defaultLevel, final boolean showLogName,
        final boolean showShortLogName, final boolean showDateTime, final boolean showContextMap,
        final String dateTimeFormat, final MessageFactory messageFactory, final PropertiesUtil props,
        final PrintStream stream) {
    super(name, messageFactory);
    final String lvl = props.getStringProperty(SimpleLoggerContext.SYSTEM_PREFIX + name + ".level");
    this.level = Level.toLevel(lvl, defaultLevel);
    if (showShortLogName) {
        final int index = name.lastIndexOf(".");
        if (index > 0 && index < name.length()) {
            this.logName = name.substring(index + 1);
        } else {
            this.logName = name;
        }
    } else if (showLogName) {
        this.logName = name;
    } else {
        this.logName = null;
    }
    this.showDateTime = showDateTime;
    this.showContextMap = showContextMap;
    this.stream = stream;

    if (showDateTime) {
        DateFormat format;
        try {
            format = new SimpleDateFormat(dateTimeFormat);
        } catch (final IllegalArgumentException e) {
            // If the format pattern is invalid - use the default format
            format = new SimpleDateFormat(SimpleLoggerContext.DEFAULT_DATE_TIME_FORMAT);
        }
        this.dateFormatter = format;
    } else {
        this.dateFormatter = null;
    }
}
项目:logging-log4j2    文件:SimpleLoggerContext.java   
public SimpleLoggerContext() {
    props = new PropertiesUtil("log4j2.simplelog.properties");

    showContextMap = props.getBooleanProperty(SYSTEM_PREFIX + "showContextMap", false);
    showLogName = props.getBooleanProperty(SYSTEM_PREFIX + "showlogname", false);
    showShortName = props.getBooleanProperty(SYSTEM_PREFIX + "showShortLogname", true);
    showDateTime = props.getBooleanProperty(SYSTEM_PREFIX + "showdatetime", false);
    final String lvl = props.getStringProperty(SYSTEM_PREFIX + "level");
    defaultLevel = Level.toLevel(lvl, Level.ERROR);

    dateTimeFormat = showDateTime ? props.getStringProperty(SimpleLoggerContext.SYSTEM_PREFIX + "dateTimeFormat",
            DEFAULT_DATE_TIME_FORMAT) : null;

    final String fileName = props.getStringProperty(SYSTEM_PREFIX + "logFile", SYSTEM_ERR);
    PrintStream ps;
    if (SYSTEM_ERR.equalsIgnoreCase(fileName)) {
        ps = System.err;
    } else if (SYSTEM_OUT.equalsIgnoreCase(fileName)) {
        ps = System.out;
    } else {
        try {
            final FileOutputStream os = new FileOutputStream(fileName);
            ps = new PrintStream(os);
        } catch (final FileNotFoundException fnfe) {
            ps = System.err;
        }
    }
    this.stream = ps;
}
项目:logging-log4j2    文件:CassandraRule.java   
@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();
    }
}
项目:logging-log4j2    文件:SmtpManager.java   
@Override
public SmtpManager createManager(final String name, final FactoryData data) {
    final String prefix = "mail." + data.protocol;

    final Properties properties = PropertiesUtil.getSystemProperties();
    properties.put("mail.transport.protocol", data.protocol);
    if (properties.getProperty("mail.host") == null) {
        // Prevent an UnknownHostException in Java 7
        properties.put("mail.host", NetUtils.getLocalHostname());
    }

    if (null != data.host) {
        properties.put(prefix + ".host", data.host);
    }
    if (data.port > 0) {
        properties.put(prefix + ".port", String.valueOf(data.port));
    }

    final Authenticator authenticator = buildAuthenticator(data.username, data.password);
    if (null != authenticator) {
        properties.put(prefix + ".auth", "true");
    }

    final Session session = Session.getInstance(properties, authenticator);
    session.setProtocolForAddress("rfc822", data.protocol);
    session.setDebug(data.isDebug);
    return new SmtpManager(name, session, null, data);
}
项目:logging-log4j2    文件:AbstractJpaAppenderTest.java   
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();
}
项目:logging-log4j2    文件:AbstractConfiguration.java   
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;
    }
}
项目:logging-log4j2    文件:PropertiesConfigurationBuilder.java   
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;
}
项目:logging-log4j2    文件:PropertiesConfigurationBuilder.java   
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;
}
项目:logging-log4j2    文件:CompositeConfiguration.java   
/**
 * Construct the ComponsiteConfiguration.
 *
 * @param configurations The List of Configurations to merge.
 */
public CompositeConfiguration(final List<? extends AbstractConfiguration> configurations) {
    super(configurations.get(0).getLoggerContext(), ConfigurationSource.NULL_SOURCE);
    rootNode = configurations.get(0).getRootNode();
    this.configurations = configurations;
    final String mergeStrategyClassName = PropertiesUtil.getProperties().getStringProperty(MERGE_STRATEGY_PROPERTY,
            DefaultMergeStrategy.class.getName());
    try {
        mergeStrategy = LoaderUtil.newInstanceOf(mergeStrategyClassName);
    } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException |
            InstantiationException ex) {
        mergeStrategy = new DefaultMergeStrategy();
    }
    for (final AbstractConfiguration config : configurations) {
        mergeStrategy.mergeRootProperties(rootNode, config);
    }
    final StatusConfiguration statusConfig = new StatusConfiguration().withVerboseClasses(VERBOSE_CLASSES)
            .withStatus(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.withStatus(value.toUpperCase());
        } else if ("dest".equalsIgnoreCase(key)) {
            statusConfig.withDestination(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.withVerbosity(value);
        } else if ("packages".equalsIgnoreCase(key)) {
            pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR)));
        } else if ("name".equalsIgnoreCase(key)) {
            setName(value);
        }
    }
    statusConfig.initialize();
}
项目:logging-log4j2    文件:ConfigurationFactory.java   
/**
 * Returns the ConfigurationFactory.
 * @return the ConfigurationFactory.
 */
public static ConfigurationFactory getInstance() {
    // volatile works in Java 1.6+, so double-checked locking also works properly
    //noinspection DoubleCheckedLocking
    if (factories == null) {
        LOCK.lock();
        try {
            if (factories == null) {
                final List<ConfigurationFactory> list = new ArrayList<>();
                final String factoryClass = PropertiesUtil.getProperties().getStringProperty(CONFIGURATION_FACTORY_PROPERTY);
                if (factoryClass != null) {
                    addFactory(list, factoryClass);
                }
                final PluginManager manager = new PluginManager(CATEGORY);
                manager.collectPlugins();
                final Map<String, PluginType<?>> plugins = manager.getPlugins();
                final List<Class<? extends ConfigurationFactory>> ordered = new ArrayList<>(plugins.size());
                for (final PluginType<?> type : plugins.values()) {
                    try {
                        ordered.add(type.getPluginClass().asSubclass(ConfigurationFactory.class));
                    } catch (final Exception ex) {
                        LOGGER.warn("Unable to add class {}", type.getPluginClass(), ex);
                    }
                }
                Collections.sort(ordered, OrderComparator.getInstance());
                for (final Class<? extends ConfigurationFactory> clazz : ordered) {
                    addFactory(list, clazz);
                }
                // see above comments about double-checked locking
                //noinspection NonThreadSafeLazyInitialization
                factories = Collections.unmodifiableList(list);
            }
        } finally {
            LOCK.unlock();
        }
    }

    LOGGER.debug("Using configurationFactory {}", configFactory);
    return configFactory;
}
项目:logging-log4j2    文件:DisruptorUtil.java   
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>>) LoaderUtil.loadClass(cls);
        return klass.newInstance();
    } catch (final Exception ignored) {
        LOGGER.debug("Invalid AsyncLogger.ExceptionHandler value: error creating {}: ", cls, ignored);
        return new AsyncLoggerDefaultExceptionHandler();
    }
}
项目:logging-log4j2    文件:DisruptorUtil.java   
static ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper> getAsyncLoggerConfigExceptionHandler() {
    final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLoggerConfig.ExceptionHandler");
    if (cls == null) {
        return new AsyncLoggerConfigDefaultExceptionHandler();
    }
    try {
        @SuppressWarnings("unchecked")
        final Class<? extends ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper>> klass =
                (Class<? extends ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper>>) LoaderUtil.loadClass(cls);
        return klass.newInstance();
    } catch (final Exception ignored) {
        LOGGER.debug("Invalid AsyncLoggerConfig.ExceptionHandler value: error creating {}: ", cls, ignored);
        return new AsyncLoggerConfigDefaultExceptionHandler();
    }
}
项目:logging-log4j2    文件:AsyncQueueFullPolicyFactory.java   
/**
 * Creates and returns {@link AsyncQueueFullPolicy} instances based on user-specified system properties.
 * <p>
 * Property {@code "log4j2.AsyncQueueFullPolicy"} controls the routing behaviour. If this property is not specified or
 * has value {@code "Default"}, this method returns {@link DefaultAsyncQueueFullPolicy} objects.
 * </p> <p>
 * If this property has value {@code "Discard"}, this method returns {@link DiscardingAsyncQueueFullPolicy} objects.
 * </p> <p>
 * For any other value, this method interprets the value as the fully qualified name of a class implementing the
 * {@link AsyncQueueFullPolicy} interface. The class must have a default constructor.
 * </p>
 *
 * @return a new AsyncQueueFullPolicy
 */
public static AsyncQueueFullPolicy create() {
    final String router = PropertiesUtil.getProperties().getStringProperty(PROPERTY_NAME_ASYNC_EVENT_ROUTER);
    if (router == null || PROPERTY_VALUE_DEFAULT_ASYNC_EVENT_ROUTER.equals(router)
            || DefaultAsyncQueueFullPolicy.class.getSimpleName().equals(router)
            || DefaultAsyncQueueFullPolicy.class.getName().equals(router)) {
        return new DefaultAsyncQueueFullPolicy();
    }
    if (PROPERTY_VALUE_DISCARDING_ASYNC_EVENT_ROUTER.equals(router)
            || DiscardingAsyncQueueFullPolicy.class.getSimpleName().equals(router)
            || DiscardingAsyncQueueFullPolicy.class.getName().equals(router)) {
        return createDiscardingAsyncQueueFullPolicy();
    }
    return createCustomRouter(router);
}
项目:logging-log4j2    文件:AsyncQueueFullPolicyFactory.java   
private static AsyncQueueFullPolicy createDiscardingAsyncQueueFullPolicy() {
    final PropertiesUtil util = PropertiesUtil.getProperties();
    final String level = util.getStringProperty(PROPERTY_NAME_DISCARDING_THRESHOLD_LEVEL, Level.INFO.name());
    final Level thresholdLevel = Level.toLevel(level, Level.INFO);
    LOGGER.debug("Creating custom DiscardingAsyncQueueFullPolicy(discardThreshold:{})", thresholdLevel);
    return new DiscardingAsyncQueueFullPolicy(thresholdLevel);
}
项目:logging-log4j2    文件:ThreadContextDataInjectorTest.java   
private void prepareThreadContext(boolean isThreadContextMapInheritable) {
    System.setProperty("log4j2.isThreadContextMapInheritable", Boolean.toString(isThreadContextMapInheritable));
    PropertiesUtil.getProperties().reload();
    ThreadContextTest.reinitThreadContext();
    ThreadContext.remove("baz");
    ThreadContext.put("foo", "bar");
}
项目:logging-log4j2    文件:AbstractAsyncThreadContextTestBase.java   
void init() {
    System.clearProperty("log4j2.threadContextMap");
    final String PACKAGE = "org.apache.logging.log4j.spi.";
    System.setProperty("log4j2.threadContextMap", PACKAGE + implClassSimpleName());
    PropertiesUtil.getProperties().reload();
    ThreadContextTestAccess.init();
}