类org.apache.logging.log4j.core.config.Property源码实例Demo

下面列出了怎么用org.apache.logging.log4j.core.config.Property的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void testH2Properties() throws SQLException {
    Property[] properties = new Property[] {
            // @formatter:off
            Property.createProperty("username", JdbcH2TestHelper.USER_NAME),
            Property.createProperty("password", JdbcH2TestHelper.PASSWORD),
            // @formatter:on
    };
    // @formatter:off
    DriverManagerConnectionSource source = DriverManagerConnectionSource.newBuilder()
        .setConnectionString(JdbcH2TestHelper.CONNECTION_STRING_MEM)
        .setProperties(properties)
        .build();
    // @formatter:on
    try (Connection conn = source.getConnection()) {
        Assert.assertFalse(conn.isClosed());
    }
}
 
@Test
public void insertConfigurationProperties() {
  assertThat(
          new OpenCensusTraceContextDataInjector()
              .injectContextData(
                  Lists.newArrayList(
                      Property.createProperty("property1", "value1"),
                      Property.createProperty("property2", "value2")),
                  new SortedArrayStringMap())
              .toMap())
      .containsExactly(
          "property1",
          "value1",
          "property2",
          "value2",
          "traceId",
          "00000000000000000000000000000000",
          "spanId",
          "0000000000000000",
          "traceSampled",
          "false");
}
 
源代码3 项目: spectator   文件: SpectatorAppender.java
/** Create a new instance of the appender using the global spectator registry. */
@PluginFactory
public static SpectatorAppender createAppender(
    @PluginAttribute("name") String name,
    @PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
    @PluginElement("Layout") Layout<? extends Serializable> layout,
    @PluginElement("Filters") Filter filter) {

  if (name == null) {
    LOGGER.error("no name provided for SpectatorAppender");
    return null;
  }

  return new SpectatorAppender(
      Spectator.globalRegistry(),
      name, filter, layout, ignoreExceptions,
      Property.EMPTY_ARRAY);
}
 
源代码4 项目: logging-log4j2   文件: HttpAppenderTest.java
@Test
public void testAppendCustomHeader() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
        .setHeaders(new Property[] {
            Property.createProperty("X-Test", "header value"),
            Property.createProperty("X-Runtime", "${java:runtime}")
        })
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
        .withHeader("Host", containing("localhost"))
        .withHeader("X-Test", equalTo("header value"))
        .withHeader("X-Runtime", equalTo(JAVA_LOOKUP.getRuntime()))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}
 
源代码5 项目: logging-log4j2   文件: FailoverAppender.java
/**
 * Create a Failover Appender.
 * @param name The name of the Appender (required).
 * @param primary The name of the primary Appender (required).
 * @param failovers The name of one or more Appenders to fail over to (at least one is required).
 * @param retryIntervalSeconds The retry interval in seconds.
 * @param config The current Configuration (passed by the Configuration when the appender is created).
 * @param filter A Filter (optional).
 * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
 *               they are propagated to the caller.
 * @return The FailoverAppender that was created.
 */
@PluginFactory
public static FailoverAppender createAppender(
        @PluginAttribute @Required(message = "A name for the Appender must be specified") final String name,
        @PluginAttribute @Required(message = "A primary Appender must be specified") final String primary,
        @PluginElement @Required(message = "At least one failover Appender must be specified") final String[] failovers,
        @PluginAliases("retryInterval") // deprecated
        @PluginAttribute(defaultInt = DEFAULT_INTERVAL_SECONDS) final int retryIntervalSeconds,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter,
        @PluginAttribute(defaultBoolean = true) final boolean ignoreExceptions) {

    int retryIntervalMillis;
    if (retryIntervalSeconds >= 0) {
        retryIntervalMillis = retryIntervalSeconds * Constants.MILLIS_IN_SECONDS;
    } else {
        LOGGER.warn("Interval {} is less than zero. Using default", retryIntervalSeconds);
        retryIntervalMillis = DEFAULT_INTERVAL_SECONDS * Constants.MILLIS_IN_SECONDS;
    }
    return new FailoverAppender(name, filter, primary, failovers, retryIntervalMillis, config, ignoreExceptions, Property.EMPTY_ARRAY);
}
 
源代码6 项目: logging-log4j2   文件: HttpURLConnectionManager.java
public HttpURLConnectionManager(final Configuration configuration, final LoggerContext loggerContext, final String name,
                                final URL url, final String method, final int connectTimeoutMillis,
                                final int readTimeoutMillis,
                                final Property[] headers,
                                final SslConfiguration sslConfiguration,
                                final boolean verifyHostname) {
    super(configuration, loggerContext, name);
    this.url = url;
    if (!(url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https"))) {
        throw new ConfigurationException("URL must have scheme http or https");
    }
    this.isHttps = this.url.getProtocol().equalsIgnoreCase("https");
    this.method = Objects.requireNonNull(method, "method");
    this.connectTimeoutMillis = connectTimeoutMillis;
    this.readTimeoutMillis = readTimeoutMillis;
    this.headers = headers != null ? headers : new Property[0];
    this.sslConfiguration = sslConfiguration;
    if (this.sslConfiguration != null && !isHttps) {
        throw new ConfigurationException("SSL configuration can only be specified with URL scheme https");
    }
    this.verifyHostname = verifyHostname;
}
 
源代码7 项目: logging-log4j2   文件: AsyncLoggerConfig.java
/**
 * @since 3.0
 */
@PluginFactory
public static LoggerConfig createLogger(
        @PluginAttribute final String additivity,
        @PluginAttribute final Level level,
        @PluginAttribute final String includeLocation,
        @PluginElement final AppenderRef[] refs,
        @PluginElement final Property[] properties,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter) {
    final List<AppenderRef> appenderRefs = Arrays.asList(refs);
    final Level actualLevel = level == null ? Level.ERROR : level;
    final boolean additive = Booleans.parseBoolean(additivity, true);
    return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
            properties, config, AsyncLoggerConfig.includeLocation(includeLocation));
}
 
/**
 * If there are no configuration properties, this injector will return the thread context's internal data
 * structure. Otherwise the configuration properties are combined with the thread context key-value pairs into the
 * specified reusable StringMap.
 *
 * @param props list of configuration properties, may be {@code null}
 * @param ignore a {@code StringMap} instance from the log event
 * @return a {@code StringMap} combining configuration properties with thread context data
 */
@Override
public StringMap injectContextData(final List<Property> props, final StringMap ignore) {
    // If there are no configuration properties we want to just return the ThreadContext's StringMap:
    // it is a copy-on-write data structure so we are sure ThreadContext changes will not affect our copy.
    if (providers.size() == 1 && (props == null || props.isEmpty())) {
        // this will replace the LogEvent's context data with the returned instance
        return providers.get(0).supplyStringMap();
    }
    int count = props == null ? 0 : props.size();
    StringMap[] maps = new StringMap[providers.size()];
    for (int i = 0; i < providers.size(); ++i) {
        maps[i] = providers.get(i).supplyStringMap();
        count += maps[i].size();
    }
    // However, if the list of Properties is non-empty we need to combine the properties and the ThreadContext
    // data. Note that we cannot reuse the specified StringMap: some Loggers may have properties defined
    // and others not, so the LogEvent's context data may have been replaced with an immutable copy from
    // the ThreadContext - this will throw an UnsupportedOperationException if we try to modify it.
    final StringMap result = ContextDataFactory.createContextData(count);
    copyProperties(props, result);
    for (StringMap map : maps) {
        result.putAll(map);
    }
    return result;
}
 
源代码9 项目: logging-log4j2   文件: AbstractFileAppender.java
private AbstractFileAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
        final M manager, final String filename, final boolean ignoreExceptions,
        final boolean immediateFlush, final Advertiser advertiser, Property[] properties) {

    super(name, layout, filter, ignoreExceptions, immediateFlush, properties, manager);
    if (advertiser != null) {
        final Map<String, String> configuration = new HashMap<>(layout.getContentFormat());
        configuration.putAll(manager.getContentFormat());
        configuration.put("contentType", layout.getContentType());
        configuration.put("name", name);
        advertisement = advertiser.advertise(configuration);
    } else {
        advertisement = null;
    }
    this.fileName = filename;
    this.advertiser = advertiser;
}
 
源代码10 项目: logging-log4j2   文件: PropertiesRewritePolicy.java
@Override
public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append(" {");
    boolean first = true;
    for (final Map.Entry<Property, Boolean> entry : properties.entrySet()) {
        if (!first) {
            sb.append(", ");
        }
        final Property prop = entry.getKey();
        sb.append(prop.getName()).append('=').append(prop.getValue());
        first = false;
    }
    sb.append('}');
    return sb.toString();
}
 
源代码11 项目: SkyEye   文件: KafkaAppender.java
@PluginFactory
public static KafkaAppender createAppender(
        @PluginElement("Layout") final Layout<? extends Serializable> layout,
        @PluginElement("Filter") final Filter filter,
        @Required(message = "No name provided for KafkaAppender") @PluginAttribute("name") final String name,
        @Required(message = "No topic provided for KafkaAppender") @PluginAttribute("topic") final String topic,
        @Required(message = "No zkServers provided for KafkaAppender") @PluginAttribute("zkServers") final String zkServers,
        @Required(message = "No mail provided for KafkaAppender") @PluginAttribute("mail") final String mail,
        @Required(message = "No rpc provided for KafkaAppender") @PluginAttribute("rpc") final String rpc,
        @Required(message = "No app provided for KafkaAppender") @PluginAttribute("app") final String app,
        @PluginElement("Properties") final Property[] properties,
        @PluginConfiguration final Configuration configuration) {
    final KafkaManager kafkaManager = new KafkaManager(configuration.getLoggerContext(), name, topic, zkServers, mail, rpc, app, SysUtil.host, properties);
    return new KafkaAppender(name, layout, filter, kafkaManager);
}
 
源代码12 项目: mycore   文件: MCRWebCLIContainer.java
ProcessCallable(MCRSession session, Session webSocketSession, ReentrantLock lock) {
    this.commands = new ArrayList<>();
    this.session = session;
    this.lock = lock;
    this.stopLogs = false;
    this.webSocketSession = webSocketSession;
    this.logGrabber = new Log4JGrabber(MCRWebCLIContainer.class.getSimpleName() + session.getID(), null,
        PatternLayout.createDefaultLayout(), true, Property.EMPTY_ARRAY);
    this.logGrabber.start();
    startLogging(true);
    cmdListPublisher = new SubmissionPublisher<>(ForkJoinPool.commonPool(), 1);
    this.currentCommand = "";
    this.continueIfOneFails = false;
    startSendingCommandQueue();
}
 
protected Properties toProperties(final Property[] properties) {
    final Properties props = new Properties();
    for (final Property property : properties) {
        props.setProperty(property.getName(), property.getValue());
    }
    return props;
}
 
源代码14 项目: pulsar   文件: PulsarManager.java
public PulsarManager(final LoggerContext loggerContext,
                     final String name,
                     final String serviceUrl,
                     final String topic,
                     final boolean syncSend,
                     final Property[] properties,
                     final String key) {
    super(loggerContext, name);
    this.serviceUrl = Objects.requireNonNull(serviceUrl, "serviceUrl");
    this.topic = Objects.requireNonNull(topic, "topic");
    this.syncSend = syncSend;
    this.key = key;
}
 
源代码15 项目: spectator   文件: SpectatorAppender.java
/**
 * Add the spectator appender to the root logger. This method is intended to be called once
 * as part of the applications initialization process.
 *
 * @param registry
 *     Spectator registry to use for the appender.
 * @param name
 *     Name for the appender.
 * @param ignoreExceptions
 *     If set to true then the stack trace metrics are disabled.
 */
public static void addToRootLogger(
    Registry registry,
    String name,
    boolean ignoreExceptions) {
  final Appender appender = new SpectatorAppender(
      registry, name, null, null, ignoreExceptions, Property.EMPTY_ARRAY);
  appender.start();

  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();

  addToRootLogger(appender);
  config.addListener(reconfigurable -> addToRootLogger(appender));
}
 
源代码16 项目: spectator   文件: SpectatorAppender.java
/** Create a new instance of the appender. */
SpectatorAppender(
    Registry registry,
    String name,
    Filter filter,
    Layout<? extends Serializable> layout,
    boolean ignoreExceptions,
    Property[] properties) {
  super(name, filter, layout, ignoreExceptions, properties);
  this.registry = registry;
}
 
源代码17 项目: spectator   文件: SpectatorAppenderTest.java
@BeforeEach
public void before() {
  registry = new DefaultRegistry();
  appender = new SpectatorAppender(
      registry, "foo", null, null, false, Property.EMPTY_ARRAY);
  appender.start();
}
 
源代码18 项目: logging-log4j2   文件: AsyncLogger.java
/**
 * This method is called by the EventHandler that processes the RingBufferLogEvent in a separate thread.
 * Merges the contents of the configuration map into the contextData, after replacing any variables in the property
 * values with the StrSubstitutor-supplied actual values.
 *
 * @param event the event to log
 */
public void actualAsyncLog(final RingBufferLogEvent event) {
    final LoggerConfig privateConfigLoggerConfig = privateConfig.loggerConfig;
    final List<Property> properties = privateConfigLoggerConfig.getPropertyList();

    if (properties != null) {
        onPropertiesPresent(event, properties);
    }

    privateConfigLoggerConfig.getReliabilityStrategy().log(this, event);
}
 
源代码19 项目: syncope   文件: MemoryAppender.java
protected MemoryAppender(
        final String name,
        final int size,
        final Filter filter,
        final boolean ignoreExceptions) {

    super(name, filter, null, ignoreExceptions, Property.EMPTY_ARRAY);
    this.statements = new CircularFifoQueue<>(size);
}
 
源代码20 项目: common   文件: StructuredJsonLayoutPlugin.java
@PluginFactory
public static StructuredLayout createLayout(
    @PluginElement("Properties") final Property[] properties) {
  final JsonConverter converter = new JsonConverter();
  converter.configure(
      Arrays.stream(properties).collect(
          Collectors.toMap(Property::getName, Property::getValue)
      ),
      false
  );
  return new StructuredLayout(struct -> converter.fromConnectData("", struct.schema(), struct));
}
 
源代码21 项目: logging-log4j2   文件: ThreadContextBenchmark.java
static Map<String, String> createMap(final List<Property> properties) {
    final Map<String, String> contextMap = ThreadContext.getImmutableContext();
    if (properties == null || properties.isEmpty()) {
        return contextMap; // may be ThreadContext.EMPTY_MAP but not null
    }
    final Map<String, String> map = new HashMap<>(contextMap);

    for (final Property prop : properties) {
        if (!map.containsKey(prop.getName())) {
            map.put(prop.getName(), prop.getValue());
        }
    }
    return Collections.unmodifiableMap(map);
}
 
源代码22 项目: logging-log4j2   文件: SmtpAppender.java
/**
 * Create a SmtpAppender.
 * @deprecated Use {@link #newBuilder()} to create and configure a {@link Builder} instance.
 * @see Builder
 */
public static SmtpAppender createAppender(final Configuration config, final String name, final String to,
                                          final String cc, final String bcc, final String from,
                                          final String replyTo, final String subject, final String smtpProtocol,
                                          final String smtpHost, final String smtpPortStr,
                                          final String smtpUsername, final String smtpPassword,
                                          final String smtpDebug, final String bufferSizeStr,
                                          Layout<? extends Serializable> layout, Filter filter,
                                          final String ignore) {
    if (name == null) {
        LOGGER.error("No name provided for SmtpAppender");
        return null;
    }

    final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
    final int smtpPort = AbstractAppender.parseInt(smtpPortStr, 0);
    final boolean isSmtpDebug = Boolean.parseBoolean(smtpDebug);
    final int bufferSize = bufferSizeStr == null ? DEFAULT_BUFFER_SIZE : Integer.parseInt(bufferSizeStr);

    if (layout == null) {
        layout = HtmlLayout.createDefaultLayout();
    }
    if (filter == null) {
        filter = ThresholdFilter.createFilter(null, null, null);
    }
    final Configuration configuration = config != null ? config : new DefaultConfiguration();

    final SmtpManager manager = SmtpManager.getSmtpManager(configuration, to, cc, bcc, from, replyTo, subject, smtpProtocol,
        smtpHost, smtpPort, smtpUsername, smtpPassword, isSmtpDebug, filter.toString(),  bufferSize, null);
    if (manager == null) {
        return null;
    }

    return new SmtpAppender(name, filter, layout, ignoreExceptions, Property.EMPTY_ARRAY, manager);
}
 
/**
 * @deprecated Use {@link #newPoolingDriverConnectionSourceBuilder()}.
 */
@Deprecated
public PoolingDriverConnectionSource(final String driverClassName, final String connectionString,
        final char[] userName, final char[] password, final Property[] properties, final String poolName)
        throws SQLException {
    super(driverClassName, connectionString, URL_PREFIX + poolName, userName, password, properties);
    this.poolName = poolName;
    setupDriver(connectionString, null);
}
 
@Test
public void testH2Properties() throws SQLException {
    final Property[] properties = new Property[] {
            // @formatter:off
            Property.createProperty("username", JdbcH2TestHelper.USER_NAME),
            Property.createProperty("password", JdbcH2TestHelper.PASSWORD),
            // @formatter:on
    };
    // @formatter:off
    final PoolingDriverConnectionSource source = PoolingDriverConnectionSource.newPoolingDriverConnectionSourceBuilder()
        .setConnectionString(JdbcH2TestHelper.CONNECTION_STRING_MEM)
        .setProperties(properties)
        .build();
    openAndClose(source);
}
 
public AbstractDriverManagerConnectionSource(final String driverClassName, final String connectionString,
        String actualConnectionString, final char[] userName, final char[] password, final Property[] properties) {
    super();
    this.driverClassName = driverClassName;
    this.connectionString = connectionString;
    this.actualConnectionString = actualConnectionString;
    this.userName = userName;
    this.password = password;
    this.properties = properties;
}
 
源代码26 项目: logging-log4j2   文件: JeroMqAppender.java
private JeroMqAppender(final String name, final Filter filter, final Layout<? extends Serializable> layout,
        final boolean ignoreExceptions, final List<String> endpoints, final long affinity, final long backlog,
        final boolean delayAttachOnConnect, final byte[] identity, final boolean ipv4Only, final long linger,
        final long maxMsgSize, final long rcvHwm, final long receiveBufferSize, final int receiveTimeOut,
        final long reconnectIVL, final long reconnectIVLMax, final long sendBufferSize, final int sendTimeOut,
        final long sndHWM, final int tcpKeepAlive, final long tcpKeepAliveCount, final long tcpKeepAliveIdle,
        final long tcpKeepAliveInterval, final boolean xpubVerbose, Property[] properties) {
    super(name, filter, layout, ignoreExceptions, properties);
    this.manager = JeroMqManager.getJeroMqManager(name, affinity, backlog, delayAttachOnConnect, identity, ipv4Only,
        linger, maxMsgSize, rcvHwm, receiveBufferSize, receiveTimeOut, reconnectIVL, reconnectIVLMax,
        sendBufferSize, sendTimeOut, sndHWM, tcpKeepAlive, tcpKeepAliveCount, tcpKeepAliveIdle,
        tcpKeepAliveInterval, xpubVerbose, endpoints);
    this.endpoints = endpoints;
}
 
源代码27 项目: logging-log4j2   文件: KafkaManager.java
private KafkaManager(final LoggerContext loggerContext, final String name, final String topic, final boolean syncSend,
        final boolean sendTimestamp, final Property[] properties, final String key, final String retryCount) {
    super(loggerContext, name);
    this.topic = Objects.requireNonNull(topic, "topic");
    this.syncSend = syncSend;
    this.sendTimestamp = sendTimestamp;
    config.setProperty("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    config.setProperty("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    config.setProperty("batch.size", "0");

    if(retryCount!=null) {
    	try {
    		Integer.parseInt(retryCount);
    		config.setProperty("retries", retryCount);
    	}catch(NumberFormatException numberFormatException) {

    	}


    }

    for (final Property property : properties) {
        config.setProperty(property.getName(), property.getValue());
    }

    this.key = key;

    this.timeoutMillis = Integer.parseInt(config.getProperty("timeout.ms", DEFAULT_TIMEOUT_MILLIS));
}
 
源代码28 项目: logging-log4j2   文件: KafkaManager.java
public static KafkaManager getManager(final LoggerContext loggerContext, final String name, final String topic,
        final boolean syncSend, final boolean sendTimestamp, final Property[] properties, final String key,
        final String retryCount) {
    StringBuilder sb = new StringBuilder(name);
    for (Property prop: properties) {
        sb.append(" ").append(prop.getName()).append("=").append(prop.getValue());
    }
    return getManager(sb.toString(), factory, new FactoryData(loggerContext, topic, syncSend, sendTimestamp,
            properties, key, retryCount));
}
 
源代码29 项目: logging-log4j2   文件: FailoverAppender.java
private FailoverAppender(final String name, final Filter filter, final String primary, final String[] failovers,
        final int intervalMillis, final Configuration config, final boolean ignoreExceptions,
        Property[] properties) {
    super(name, filter, null, ignoreExceptions, properties);
    this.primaryRef = primary;
    this.failovers = failovers;
    this.config = config;
    this.intervalNanos = TimeUnit.MILLISECONDS.toNanos(intervalMillis);
}
 
源代码30 项目: logging-log4j2   文件: FlumePersistentManager.java
/**
 * Returns a FlumeAvroManager.
 * @param name The name of the manager.
 * @param agents The agents to use.
 * @param properties Properties to pass to the Manager.
 * @param batchSize The number of events to include in a batch.
 * @param retries The number of times to retry connecting before giving up.
 * @param connectionTimeout The amount of time to wait to establish a connection.
 * @param requestTimeout The amount of time to wait for a response to a request.
 * @param delayMillis Amount of time to delay before delivering a batch.
 * @param lockTimeoutRetryCount The number of times to retry after a lock timeout.
 * @param dataDir The location of the Berkeley database.
 * @return A FlumeAvroManager.
 */
public static FlumePersistentManager getManager(final String name, final Agent[] agents,
                                                final Property[] properties, int batchSize, final int retries,
                                                final int connectionTimeout, final int requestTimeout,
                                                final int delayMillis, final int lockTimeoutRetryCount,
                                                final String dataDir) {
    if (agents == null || agents.length == 0) {
        throw new IllegalArgumentException("At least one agent is required");
    }

    if (batchSize <= 0) {
        batchSize = 1;
    }
    final String dataDirectory = Strings.isEmpty(dataDir) ? DEFAULT_DATA_DIR : dataDir;

    final StringBuilder sb = new StringBuilder("FlumePersistent[");
    boolean first = true;
    for (final Agent agent : agents) {
        if (!first) {
            sb.append(',');
        }
        sb.append(agent.getHost()).append(':').append(agent.getPort());
        first = false;
    }
    sb.append(']');
    sb.append(' ').append(dataDirectory);
    return getManager(sb.toString(), factory, new FactoryData(name, agents, batchSize, retries,
        connectionTimeout, requestTimeout, delayMillis, lockTimeoutRetryCount, dataDir, properties));
}
 
 类所在包
 类方法
 同包方法