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

项目:log4j2-simplejson    文件:SimpleJSONLayout.java   
protected SimpleJSONLayout(final Configuration config, final boolean locationInfo,
        final boolean properties, final boolean complete, final boolean eventEol,
        final String headerPattern, final String footerPattern, final Charset charset,
        final KeyValuePair[] additionalFields) {
    super(config, charset, //
            PatternLayout.newSerializerBuilder() //
                    .setConfiguration(config).setReplace(null).setPattern(headerPattern) //
                    .setDefaultPattern(DEFAULT_HEADER) //
                    .setPatternSelector(null).setAlwaysWriteExceptions(false).setNoConsoleNoAnsi(false) //
                    .build(), //
            PatternLayout.newSerializerBuilder() //
                    .setConfiguration(config).setReplace(null).setPattern(footerPattern) //
                    .setDefaultPattern(DEFAULT_FOOTER) //
                    .setPatternSelector(null).setAlwaysWriteExceptions(false).setNoConsoleNoAnsi(false) //
                    .build());
    this.locationInfo = locationInfo;
    this.properties = properties;
    this.complete = complete;
    this.additionalFields = additionalFields;
    this.layoutStartTime = System.currentTimeMillis();
    this.layoutSequence = new AtomicLong();
    this.interpolator = new Interpolator(new MapLookup(getConfiguration().getProperties()),
            getConfiguration().getPluginPackages());
    this.eol = !eventEol ? COMPACT_EOL : DEFAULT_EOL;
}
项目:daikon    文件:Log4j2JSONLayout.java   
private static Map<String, String> unpackPairs(final KeyValuePair[] pairs) {
    final Map<String, String> additionalLogAttributes = new HashMap<>();
    if (pairs != null && pairs.length > 0) {
        for (final KeyValuePair pair : pairs) {
            final String key = pair.getKey();
            if (key == null) {
                LOGGER.error("A null key is not valid in MapFilter");
            }
            final String value = pair.getValue();
            if (value == null) {
                LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
            }
            if (additionalLogAttributes.containsKey(key)) {
                LOGGER.error("Duplicate entry for key: {} is forbidden!", key);
            }
            additionalLogAttributes.put(key, value);
        }
    }
    return additionalLogAttributes;
}
项目:logging-log4j2    文件:DynamicThresholdFilter.java   
/**
 * Creates a DynamicThresholdFilter.
 * @param key The name of the key to compare.
 * @param pairs An array of value and Level pairs.
 * @param defaultThreshold The default Level.
 * @param onMatch The action to perform if a match occurs.
 * @param onMismatch The action to perform if no match occurs.
 * @return The DynamicThresholdFilter.
 */
// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static DynamicThresholdFilter createFilter(
        @PluginAttribute("key") final String key,
        @PluginElement("Pairs") final KeyValuePair[] pairs,
        @PluginAttribute("defaultThreshold") final Level defaultThreshold,
        @PluginAttribute("onMatch") final Result onMatch,
        @PluginAttribute("onMismatch") final Result onMismatch) {
    final Map<String, Level> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        map.put(pair.getKey(), Level.toLevel(pair.getValue()));
    }
    final Level level = defaultThreshold == null ? Level.ERROR : defaultThreshold;
    return new DynamicThresholdFilter(key, map, level, onMatch, onMismatch);
}
项目:logging-log4j2    文件:AbstractJacksonLayout.java   
private static ResolvableKeyValuePair[] prepareAdditionalFields(final Configuration config, final KeyValuePair[] additionalFields) {
    if (additionalFields == null || additionalFields.length == 0) {
        // No fields set
        return new ResolvableKeyValuePair[0];
    }

    // Convert to specific class which already determines whether values needs lookup during serialization
    final ResolvableKeyValuePair[] resolvableFields = new ResolvableKeyValuePair[additionalFields.length];

    for (int i = 0; i < additionalFields.length; i++) {
        ResolvableKeyValuePair resolvable = resolvableFields[i] = new ResolvableKeyValuePair(additionalFields[i]);

        // Validate
        if (config == null && resolvable.valueNeedsLookup) {
            throw new IllegalArgumentException("configuration needs to be set when there are additional fields with variables");
        }
    }

    return resolvableFields;
}
项目:logging-log4j2    文件:GelfLayout.java   
private GelfLayout(final Configuration config, final String host, final KeyValuePair[] additionalFields, final CompressionType compressionType,
           final int compressionThreshold, final boolean includeStacktrace, final boolean includeThreadContext, final boolean includeNullDelimiter) {
    super(config, StandardCharsets.UTF_8, null, null);
    this.host = host != null ? host : NetUtils.getLocalHostname();
    this.additionalFields = additionalFields != null ? additionalFields : new KeyValuePair[0];
    if (config == null) {
        for (final KeyValuePair additionalField : this.additionalFields) {
            if (valueNeedsLookup(additionalField.getValue())) {
                throw new IllegalArgumentException("configuration needs to be set when there are additional fields with variables");
            }
        }
    }
    this.compressionType = compressionType;
    this.compressionThreshold = compressionThreshold;
    this.includeStacktrace = includeStacktrace;
    this.includeThreadContext = includeThreadContext;
    this.includeNullDelimiter = includeNullDelimiter;
    if (includeNullDelimiter && compressionType != CompressionType.OFF) {
        throw new IllegalArgumentException("null delimiter cannot be used with compression");
    }
}
项目:logging-log4j2    文件:DynamicThresholdFilterTest.java   
@Test
public void testFilter() {
    ThreadContext.put("userid", "testuser");
    ThreadContext.put("organization", "apache");
    final KeyValuePair[] pairs = new KeyValuePair[] {
            new KeyValuePair("testuser", "DEBUG"),
            new KeyValuePair("JohnDoe", "warn") };
    final DynamicThresholdFilter filter = DynamicThresholdFilter.createFilter("userid", pairs, Level.ERROR, null,
            null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null));
    ThreadContext.clearMap();
    ThreadContext.put("userid", "JohnDoe");
    ThreadContext.put("organization", "apache");
    LogEvent event = Log4jLogEvent.newBuilder().setLevel(Level.DEBUG).setMessage(new SimpleMessage("Test")).build();
    assertSame(Filter.Result.DENY, filter.filter(event));
    event = Log4jLogEvent.newBuilder().setLevel(Level.ERROR).setMessage(new SimpleMessage("Test")).build();
    assertSame(Filter.Result.NEUTRAL, filter.filter(event));
    ThreadContext.clearMap();
}
项目:logging-log4j2    文件:MapFilterTest.java   
@Test
public void testFilter() {
    final KeyValuePair[] pairs = new KeyValuePair[] { new KeyValuePair("FromAccount", "211000"),
                                                new KeyValuePair("ToAccount", "123456")};
    MapFilter filter = MapFilter.createFilter(pairs, "and", null, null);
    filter.start();
    StringMapMessage msg = new StringMapMessage();
    msg.put("ToAccount", "123456");
    msg.put("FromAccount", "211000");
    msg.put("Amount", "1000.00");
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, msg, null));
    msg.put("ToAccount", "111111");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, msg, null));
    filter = MapFilter.createFilter(pairs, "or", null, null);
    filter.start();
    msg = new StringMapMessage();
    msg.put("ToAccount", "123456");
    msg.put("FromAccount", "211000");
    msg.put("Amount", "1000.00");
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, msg, null));
    msg.put("ToAccount", "111111");
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, msg, null));
}
项目:logging-log4j2    文件:XmlLayoutTest.java   
@Test
public void testAdditionalFields() throws Exception {
    final AbstractJacksonLayout layout = XmlLayout.newBuilder()
            .setLocationInfo(false)
            .setProperties(false)
            .setIncludeStacktrace(false)
            .setAdditionalFields(new KeyValuePair[] {
                new KeyValuePair("KEY1", "VALUE1"),
                new KeyValuePair("KEY2", "${java:runtime}"), })
            .setCharset(StandardCharsets.UTF_8)
            .setConfiguration(ctx.getConfiguration())
            .build();
    final String str = layout.toSerializable(LogEventFixtures.createLogEvent());
    assertTrue(str, str.contains("<KEY1>VALUE1</KEY1>"));
    assertTrue(str, str.contains("<KEY2>" + new JavaLookup().getRuntime() + "</KEY2>"));
}
项目:logging-log4j2    文件:JsonLayoutTest.java   
@Test
public void testAdditionalFields() throws Exception {
    final AbstractJacksonLayout layout = JsonLayout.newBuilder()
            .setLocationInfo(false)
            .setProperties(false)
            .setComplete(false)
            .setCompact(true)
            .setEventEol(false)
            .setIncludeStacktrace(false)
            .setAdditionalFields(new KeyValuePair[] {
                new KeyValuePair("KEY1", "VALUE1"),
                new KeyValuePair("KEY2", "${java:runtime}"), })
            .setCharset(StandardCharsets.UTF_8)
            .setConfiguration(ctx.getConfiguration())
            .build();
    final String str = layout.toSerializable(LogEventFixtures.createLogEvent());
    assertTrue(str, str.contains("\"KEY1\":\"VALUE1\""));
    assertTrue(str, str.contains("\"KEY2\":\"" + new JavaLookup().getRuntime() + "\""));
}
项目:logging-log4j2    文件:YamlLayoutTest.java   
@Test
public void testAdditionalFields() throws Exception {
    final AbstractJacksonLayout layout = YamlLayout.newBuilder()
            .setLocationInfo(false)
            .setProperties(false)
            .setIncludeStacktrace(false)
            .setAdditionalFields(new KeyValuePair[] {
                new KeyValuePair("KEY1", "VALUE1"),
                new KeyValuePair("KEY2", "${java:runtime}"), })
            .setCharset(StandardCharsets.UTF_8)
            .setConfiguration(ctx.getConfiguration())
            .build();
    final String str = layout.toSerializable(LogEventFixtures.createLogEvent());
    assertTrue(str, str.contains("KEY1: \"VALUE1\""));
    assertTrue(str, str.contains("KEY2: \"" + new JavaLookup().getRuntime() + "\""));
}
项目:log4j2-simplejson    文件:SimpleJSONLayout.java   
@PluginFactory
public static SimpleJSONLayout createLayout( //
        @PluginConfiguration final Configuration config, //
        @PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo, //
        @PluginAttribute(value = "properties", defaultBoolean = true) final boolean properties, //
        @PluginAttribute(value = "complete", defaultBoolean = false) final boolean complete, //
        @PluginAttribute(value = "eventEol", defaultBoolean = true) final boolean eventEol, //
        @PluginAttribute(value = "header", defaultString = DEFAULT_HEADER) final String headerPattern, //
        @PluginAttribute(value = "footer", defaultString = DEFAULT_FOOTER) final String footerPattern, //
        @PluginAttribute(value = "charset", defaultString = "US-ASCII") final Charset charset, //
        @PluginElement("AdditionalField") final KeyValuePair[] additionalFields) {
    return new SimpleJSONLayout(config, locationInfo, properties, complete, eventEol, headerPattern,
            footerPattern, charset, additionalFields);
}
项目:log4j2-gelf    文件:GelfAppender.java   
protected GelfAppender(final String name,
                       final Layout<? extends Serializable> layout,
                       final Filter filter,
                       final boolean ignoreExceptions,
                       final GelfConfiguration gelfConfiguration,
                       final String hostName,
                       final boolean includeSource,
                       final boolean includeThreadContext,
                       final boolean includeStackTrace,
                       final KeyValuePair[] additionalFields,
                       final boolean includeExceptionCause) {
    super(name, filter, layout, ignoreExceptions);
    this.gelfConfiguration = gelfConfiguration;
    this.hostName = hostName;
    this.includeSource = includeSource;
    this.includeThreadContext = includeThreadContext;
    this.includeStackTrace = includeStackTrace;
    this.includeExceptionCause = includeExceptionCause;

    if (null != additionalFields) {
        this.additionalFields = new HashMap<>();
        for (KeyValuePair pair : additionalFields) {
            this.additionalFields.put(pair.getKey(), pair.getValue());
        }
    } else {
        this.additionalFields = Collections.emptyMap();
    }
}
项目:logging-log4j2    文件:LoggerNameLevelRewritePolicy.java   
/**
 * Creates a policy to rewrite levels for a given logger name.
 * 
 * @param loggerNamePrefix
 *        The logger name prefix for events to rewrite; all event logger names that start with this string will be
 *        rewritten.
 * @param levelPairs
 *        The levels to rewrite, the key is the source level, the value the target level.
 * @return a new LoggerNameLevelRewritePolicy
 */
@PluginFactory
public static LoggerNameLevelRewritePolicy createPolicy(
        // @formatter:off
        @PluginAttribute("logger") final String loggerNamePrefix,
        @PluginElement("KeyValuePair") final KeyValuePair[] levelPairs) {
        // @formatter:on
    final Map<Level, Level> newMap = new HashMap<>(levelPairs.length);
    for (final KeyValuePair keyValuePair : levelPairs) {
        newMap.put(getLevel(keyValuePair.getKey()), getLevel(keyValuePair.getValue()));
    }
    return new LoggerNameLevelRewritePolicy(loggerNamePrefix, newMap);
}
项目:logging-log4j2    文件:MapRewritePolicy.java   
/**
 * The factory method to create the MapRewritePolicy.
 * @param mode The string representation of the Mode.
 * @param pairs key/value pairs for the new Map keys and values.
 * @return The MapRewritePolicy.
 */
@PluginFactory
public static MapRewritePolicy createPolicy(
        @PluginAttribute("mode") final String mode,
        @PluginElement("KeyValuePair") final KeyValuePair[] pairs) {
    Mode op = mode == null ? op = Mode.Add : Mode.valueOf(mode);
    if (pairs == null || pairs.length == 0) {
        LOGGER.error("keys and values must be specified for the MapRewritePolicy");
        return null;
    }
    final Map<String, Object> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        final String key = pair.getKey();
        if (key == null) {
            LOGGER.error("A null key is not valid in MapRewritePolicy");
            continue;
        }
        final String value = pair.getValue();
        if (value == null) {
            LOGGER.error("A null value for key " + key + " is not allowed in MapRewritePolicy");
            continue;
        }
        map.put(pair.getKey(), pair.getValue());
    }
    if (map.isEmpty()) {
        LOGGER.error("MapRewritePolicy is not configured with any valid key value pairs");
        return null;
    }
    return new MapRewritePolicy(map, op);
}
项目:logging-log4j2    文件:ThreadContextMapFilter.java   
@PluginFactory
public static ThreadContextMapFilter createFilter(
        @PluginElement("Pairs") final KeyValuePair[] pairs,
        @PluginAttribute("operator") final String oper,
        @PluginAttribute("onMatch") final Result match,
        @PluginAttribute("onMismatch") final Result mismatch) {
    if (pairs == null || pairs.length == 0) {
        LOGGER.error("key and value pairs must be specified for the ThreadContextMapFilter");
        return null;
    }
    final Map<String, List<String>> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        final String key = pair.getKey();
        if (key == null) {
            LOGGER.error("A null key is not valid in MapFilter");
            continue;
        }
        final String value = pair.getValue();
        if (value == null) {
            LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
            continue;
        }
        List<String> list = map.get(pair.getKey());
        if (list != null) {
            list.add(value);
        } else {
            list = new ArrayList<>();
            list.add(value);
            map.put(pair.getKey(), list);
        }
    }
    if (map.isEmpty()) {
        LOGGER.error("ThreadContextMapFilter is not configured with any valid key value pairs");
        return null;
    }
    final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
    return new ThreadContextMapFilter(map, isAnd, match, mismatch);
}
项目:logging-log4j2    文件:MapFilter.java   
@PluginFactory
public static MapFilter createFilter(
        @PluginElement("Pairs") final KeyValuePair[] pairs,
        @PluginAttribute("operator") final String oper,
        @PluginAttribute("onMatch") final Result match,
        @PluginAttribute("onMismatch") final Result mismatch) {
    if (pairs == null || pairs.length == 0) {
        LOGGER.error("keys and values must be specified for the MapFilter");
        return null;
    }
    final Map<String, List<String>> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        final String key = pair.getKey();
        if (key == null) {
            LOGGER.error("A null key is not valid in MapFilter");
            continue;
        }
        final String value = pair.getValue();
        if (value == null) {
            LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
            continue;
        }
        List<String> list = map.get(pair.getKey());
        if (list != null) {
            list.add(value);
        } else {
            list = new ArrayList<>();
            list.add(value);
            map.put(pair.getKey(), list);
        }
    }
    if (map.isEmpty()) {
        LOGGER.error("MapFilter is not configured with any valid key value pairs");
        return null;
    }
    final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
    return new MapFilter(map, isAnd, match, mismatch);
}
项目:logging-log4j2    文件:StructuredDataFilter.java   
/**
 * Creates the StructuredDataFilter.
 * @param pairs Key and value pairs.
 * @param oper The operator to perform. If not "or" the operation will be an "and".
 * @param match The action to perform on a match.
 * @param mismatch The action to perform on a mismatch.
 * @return The StructuredDataFilter.
 */
// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static StructuredDataFilter createFilter(
        @PluginElement("Pairs") final KeyValuePair[] pairs,
        @PluginAttribute("operator") final String oper,
        @PluginAttribute("onMatch") final Result match,
        @PluginAttribute("onMismatch") final Result mismatch) {
    if (pairs == null || pairs.length == 0) {
        LOGGER.error("keys and values must be specified for the StructuredDataFilter");
        return null;
    }
    final Map<String, List<String>> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        final String key = pair.getKey();
        if (key == null) {
            LOGGER.error("A null key is not valid in MapFilter");
            continue;
        }
        final String value = pair.getValue();
        if (value == null) {
            LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
            continue;
        }
        List<String> list = map.get(pair.getKey());
        if (list != null) {
            list.add(value);
        } else {
            list = new ArrayList<>();
            list.add(value);
            map.put(pair.getKey(), list);
        }
    }
    if (map.isEmpty()) {
        LOGGER.error("StructuredDataFilter is not configured with any valid key value pairs");
        return null;
    }
    final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
    return new StructuredDataFilter(map, isAnd, match, mismatch);
}
项目:logging-log4j2    文件:JsonLayout.java   
private JsonLayout(final Configuration config, final boolean locationInfo, final boolean properties,
                   final boolean encodeThreadContextAsList,
                   final boolean complete, final boolean compact, final boolean eventEol,
                   final String headerPattern, final String footerPattern, final Charset charset,
                   final boolean includeStacktrace, final boolean stacktraceAsString,
                   final boolean includeNullDelimiter,
                   final KeyValuePair[] additionalFields, final boolean objectMessageAsJsonObject) {
    super(config, new JacksonFactory.JSON(encodeThreadContextAsList, includeStacktrace, stacktraceAsString, objectMessageAsJsonObject).newWriter(
            locationInfo, properties, compact),
            charset, compact, complete, eventEol,
            PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
            PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build(),
            includeNullDelimiter,
            additionalFields);
}
项目:logging-log4j2    文件:LoggerFields.java   
/**
 * Create a LoggerFields from KeyValuePairs.
 *
 * @param keyValuePairs
 *            An array of KeyValuePairs.
 * @param sdId
 *            The SD-ID in an SD-ELEMENT
 * @param enterpriseId
 *            The IANA assigned enterprise number
 * @param discardIfAllFieldsAreEmpty
 *            this SD-ELEMENT should be discarded if all fields are empty
 * @return A LoggerFields instance containing a Map&lt;String, String&gt;.
 */
@PluginFactory
public static LoggerFields createLoggerFields(
    @PluginElement("LoggerFields") final KeyValuePair[] keyValuePairs,
    @PluginAttribute("sdId") final String sdId,
    @PluginAttribute("enterpriseId") final String enterpriseId,
    @PluginAttribute(value = "discardIfAllFieldsAreEmpty") final boolean discardIfAllFieldsAreEmpty) {
    final Map<String, String> map = new HashMap<>();

    for (final KeyValuePair keyValuePair : keyValuePairs) {
        map.put(keyValuePair.getKey(), keyValuePair.getValue());
    }

    return new LoggerFields(map, sdId, enterpriseId, discardIfAllFieldsAreEmpty);
}
项目:logging-log4j2    文件:YamlLayout.java   
private YamlLayout(final Configuration config, final boolean locationInfo, final boolean properties,
                   final boolean complete, final boolean compact, final boolean eventEol,
                   final String headerPattern, final String footerPattern, final Charset charset,
                   final boolean includeStacktrace, final boolean stacktraceAsString,
                   final boolean includeNullDelimiter,
                   final KeyValuePair[] additionalFields) {
    super(config, new JacksonFactory.YAML(includeStacktrace, stacktraceAsString).newWriter(locationInfo, properties, compact),
            charset, compact, complete, eventEol,
            PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
            PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build(),
            includeNullDelimiter,
            additionalFields);
}
项目:logging-log4j2    文件:XmlLayout.java   
private XmlLayout(final Configuration config, final boolean locationInfo, final boolean properties,
                  final boolean complete, final boolean compact, final Charset charset,
                  final boolean includeStacktrace, final boolean stacktraceAsString,
                  final boolean includeNullDelimiter,
                  final KeyValuePair[] additionalFields) {
    super(config, new JacksonFactory.XML(includeStacktrace, stacktraceAsString).newWriter(
        locationInfo, properties, compact),
        charset, compact, complete, false, null, null, includeNullDelimiter,
        additionalFields);
}
项目:logging-log4j2    文件:AbstractJacksonLayout.java   
protected AbstractJacksonLayout(final Configuration config, final ObjectWriter objectWriter, final Charset charset,
        final boolean compact, final boolean complete, final boolean eventEol, final Serializer headerSerializer,
        final Serializer footerSerializer, final boolean includeNullDelimiter,
        final KeyValuePair[] additionalFields) {
    super(config, charset, headerSerializer, footerSerializer);
    this.objectWriter = objectWriter;
    this.compact = compact;
    this.complete = complete;
    this.eol = compact && !eventEol ? COMPACT_EOL : DEFAULT_EOL;
    this.includeNullDelimiter = includeNullDelimiter;
    this.additionalFields = prepareAdditionalFields(config, additionalFields);
}
项目:logging-log4j2    文件:GelfLayout.java   
/**
 * @deprecated Use {@link #newBuilder()} instead
 */
@Deprecated
public static GelfLayout createLayout(
        //@formatter:off
        @PluginAttribute("host") final String host,
        @PluginElement("AdditionalField") final KeyValuePair[] additionalFields,
        @PluginAttribute(value = "compressionType",
            defaultString = "GZIP") final CompressionType compressionType,
        @PluginAttribute(value = "compressionThreshold",
            defaultInt = COMPRESSION_THRESHOLD) final int compressionThreshold,
        @PluginAttribute(value = "includeStacktrace",
            defaultBoolean = true) final boolean includeStacktrace) {
        // @formatter:on
    return new GelfLayout(null, host, additionalFields, compressionType, compressionThreshold, includeStacktrace, true, false);
}
项目:logging-log4j2    文件:LoggerNameLevelRewritePolicyTest.java   
@Test
public void testUpdate() {
    final KeyValuePair[] rewrite = new KeyValuePair[] {
            new KeyValuePair("INFO", "DEBUG"),
            new KeyValuePair("WARN", "INFO") };
    final String loggerNameRewrite = "com.foo.bar";
    LogEvent logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameRewrite)
            .setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.INFO)
            .setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none")
            .setTimeMillis(1).build();
    final LoggerNameLevelRewritePolicy updatePolicy = LoggerNameLevelRewritePolicy.createPolicy(loggerNameRewrite,
            rewrite);
    LogEvent rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.DEBUG, rewritten.getLevel());
    logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameRewrite)
            .setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.WARN)
            .setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none")
            .setTimeMillis(1).build();
    rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.INFO, rewritten.getLevel());
    final String loggerNameReadOnly = "com.nochange";
    logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameReadOnly)
            .setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.INFO)
            .setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none")
            .setTimeMillis(1).build();
    rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.INFO, rewritten.getLevel());
    logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameReadOnly)
            .setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.WARN)
            .setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none")
            .setTimeMillis(1).build();
    rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.WARN, rewritten.getLevel());
}
项目:logging-log4j2    文件:MapRewritePolicyTest.java   
@BeforeClass
public static void setupClass() {
    stringMap.putValue("test1", "one");
    stringMap.putValue("test2", "two");
    map = stringMap.toMap(); 
    logEvent0 = Log4jLogEvent.newBuilder() //
            .setLoggerName("test") //
            .setContextData(stringMap) //
            .setLoggerFqcn("MapRewritePolicyTest.setupClass()") //
            .setLevel(Level.ERROR) //
            .setMessage(new SimpleMessage("Test")) //
            .setThrown(new RuntimeException("test")) //
            .setThreadName("none")
            .setSource(new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 28))
            .setTimeMillis(2).build();

    logEvent1 = ((Log4jLogEvent) logEvent0).asBuilder() //
            .setMessage(new StringMapMessage(map)) //
            .setSource(new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 29)) //
            .build();

    final ThreadContextStack stack = new MutableThreadContextStack(new ArrayList<>(map.values()));
    logEvent2 = ((Log4jLogEvent) logEvent0).asBuilder() //
            .setContextStack(stack) //
            .setMarker(MarkerManager.getMarker("test")) //
            .setLevel(Level.TRACE) //
            .setMessage(new StructuredDataMessage("test", "Nothing", "test", map)) //
            .setTimeMillis(20000000) //
            .setSource(new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 30)) //
            .build();
    logEvent3 = ((Log4jLogEvent) logEvent0).asBuilder() //
            .setContextStack(stack) //
            .setLevel(Level.ALL) //
            .setMessage(new StringMapMessage(map)) //
            .setTimeMillis(Long.MAX_VALUE) //
            .setSource(new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 31)) //
            .build();
    rewrite = new KeyValuePair[]{new KeyValuePair("test2", "2"), new KeyValuePair("test3", "three")};
}
项目:logging-log4j2    文件:DynamicThresholdFilterTest.java   
@Test
public void testFilterWorksWhenParamsArePassedAsArguments() {
    ThreadContext.put("userid", "testuser");
    ThreadContext.put("organization", "apache");
    final KeyValuePair[] pairs = new KeyValuePair[] {
            new KeyValuePair("testuser", "DEBUG"),
            new KeyValuePair("JohnDoe", "warn") };
    final DynamicThresholdFilter filter = DynamicThresholdFilter.createFilter("userid", pairs, Level.ERROR, Filter.Result.ACCEPT, Filter.Result.NEUTRAL);
    filter.start();
    assertTrue(filter.isStarted());
    final Object [] replacements = {"one", "two", "three"};
    assertSame(Filter.Result.ACCEPT, filter.filter(null, Level.DEBUG, null, "some test message", replacements)); 
    assertSame(Filter.Result.ACCEPT, filter.filter(null, Level.DEBUG, null, "some test message", "one", "two", "three")); 
    ThreadContext.clearMap();
}
项目:logging-log4j2    文件:ThreadContextMapFilterTest.java   
@Test
public void testFilter() {
    ThreadContext.put("userid", "testuser");
    ThreadContext.put("organization", "Apache");
    final KeyValuePair[] pairs = new KeyValuePair[] { new KeyValuePair("userid", "JohnDoe"),
                                                new KeyValuePair("organization", "Apache")};
    ThreadContextMapFilter filter = ThreadContextMapFilter.createFilter(pairs, "and", null, null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.remove("userid");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.put("userid", "JohnDoe");
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null));
    ThreadContext.put("organization", "ASF");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.clearMap();
    filter = ThreadContextMapFilter.createFilter(pairs, "or", null, null);
    filter.start();
    assertTrue(filter.isStarted());
    ThreadContext.put("userid", "testuser");
    ThreadContext.put("organization", "Apache");
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.put("organization", "ASF");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.remove("organization");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    final KeyValuePair[] single = new KeyValuePair[] {new KeyValuePair("userid", "testuser")};
    filter = ThreadContextMapFilter.createFilter(single, null, null, null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.clearMap();
}
项目:log4j2-simplejson    文件:SimpleJSONLayout.java   
private final String format(final LogEvent event) {
    final StringBuilder sb = getStringBuilder();
    if (complete && eventCount > 0) {
        sb.append(", ");
    }
    sb.append('{');
    // Internal Info
    json(sb, "layout.version", LAYOUT_VERSION);
    json(sb, "layout.start", layoutStartTime);
    json(sb, "layout.sequence", layoutSequence.incrementAndGet());
    // Basic Info
    json(sb, "timestamp", event.getTimeMillis());
    json(sb, "thread", event.getThreadName());
    json(sb, "threadId", event.getThreadId());
    json(sb, "level", event.getLevel().toString());
    json(sb, "logger", event.getLoggerName());
    // Caller info
    if (locationInfo) {
        final StackTraceElement source = event.getSource();
        json(sb, "source");
        sb.append('{');
        json(sb, "class", source.getClassName());
        json(sb, "method", source.getMethodName());
        json(sb, "file", source.getFileName());
        json(sb, "line", source.getLineNumber());
        sb.setLength(sb.length() - 1);
        sb.append('}').append(',');
    }
    // Diagnostic Context
    if (properties) {
        if (!event.getContextStack().isEmpty()) {
            json(sb, "ndc", event.getContextStack().asList());
        }
        if (!event.getContextData().isEmpty()) {
            json(sb, "mdc", event.getContextData().toMap());
        }
    }
    // Additional Fields
    for (int i = 0; i < additionalFields.length; i++) {
        final KeyValuePair kv = additionalFields[i];
        final String key = kv.getKey();
        final String value = kv.getValue();
        final String iv = interpolator.lookup(event, value);
        if (iv != null) {
            json(sb, (key != null) ? key : value, iv);
        }
    }
    // Message
    json(sb, "msg", event.getMessage().getFormattedMessage());
    // Exceptions
    if (event.getThrownProxy() != null) {
        final ThrowableProxy throwableInfo = event.getThrownProxy();
        final Throwable t = throwableInfo.getThrowable();
        final String exClass = t.getClass().getCanonicalName();
        if (exClass != null) {
            json(sb, "exception", exClass);
        }
        final String exMsg = t.getMessage();
        if (exMsg != null) {
            json(sb, "cause", exMsg);
        }
        // TODO: Change pure string to complex list/maps of stacktraces?
        final String stackTrace = throwableInfo.getExtendedStackTraceAsString("");
        if (stackTrace != null) {
            json(sb, "stacktrace", stackTrace);
        }
    }
    sb.setLength(sb.length() - 1);
    sb.append('}').append(eol);
    return sb.toString();
}
项目:daikon    文件:Log4j2JSONLayout.java   
/**
 * Creates a JSON Layout.
 *
 * @param locationInfo
 *        If "true", includes the location information in the generated JSON.
 * @param properties
 *        If "true", includes the thread context in the generated JSON.
 * @param complete
 *        If "true", includes the JSON header and footer, defaults to "false".
 * @param compact
 *        If "true", does not use end-of-lines and indentation, defaults to "false".
 * @param eventEol
 *        If "true", forces an EOL after each log event (even if compact is "true"), defaults to "false". This
 *        allows one even per line, even in compact mode.
 * @param charset
 *        The character set to use, if {@code null}, uses "UTF-8".
 * @param pairs
 *          MDC attributes
 * @return A JSON Layout.
 */
@PluginFactory
public static AbstractStringLayout createLayout(
        // @formatter:off
        @PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo,
        @PluginAttribute(value = "properties", defaultBoolean = false) final boolean properties,
        @PluginAttribute(value = "complete", defaultBoolean = false) final boolean complete,
        @PluginAttribute(value = "compact", defaultBoolean = false) final boolean compact,
        @PluginAttribute(value = "eventEol", defaultBoolean = false) final boolean eventEol,
        @PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset,
        @PluginElement("Pairs") final KeyValuePair[] pairs
        // @formatter:on
) {

    //Unpacke the pairs list
    final Map<String, String> additionalLogAttributes = unpackPairs(pairs);
    return new Log4j2JSONLayout(locationInfo, charset, additionalLogAttributes);

}
项目:logging-log4j2    文件:JsonLayout.java   
@Override
public KeyValuePair[] getAdditionalFields() {
    return additionalFields;
}
项目:logging-log4j2    文件:JsonLayout.java   
@Override
public B setAdditionalFields(KeyValuePair[] additionalFields) {
    this.additionalFields = additionalFields;
    return asBuilder();
}
项目:logging-log4j2    文件:AbstractJacksonLayout.java   
public KeyValuePair[] getAdditionalFields() {
    return additionalFields;
}
项目:logging-log4j2    文件:AbstractJacksonLayout.java   
ResolvableKeyValuePair(KeyValuePair pair) {
    this.key = pair.getKey();
    this.value = pair.getValue();
    this.valueNeedsLookup = AbstractJacksonLayout.valueNeedsLookup(this.value);
}
项目:logging-log4j2    文件:GelfLayout.java   
public KeyValuePair[] getAdditionalFields() {
    return additionalFields;
}
项目:logging-log4j2    文件:GelfLayout.java   
/**
 * @deprecated Use {@link #newBuilder()} instead
 */
@Deprecated
public GelfLayout(final String host, final KeyValuePair[] additionalFields, final CompressionType compressionType,
                  final int compressionThreshold, final boolean includeStacktrace) {
    this(null, host, additionalFields, compressionType, compressionThreshold, includeStacktrace, true, false);
}
项目:logging-log4j2    文件:GelfLayout.java   
private StringBuilder toText(final LogEvent event, final StringBuilder builder, final boolean gcFree) {
    builder.append('{');
    builder.append("\"version\":\"1.1\",");
    builder.append("\"host\":\"");
    JsonUtils.quoteAsString(toNullSafeString(host), builder);
    builder.append(QC);
    builder.append("\"timestamp\":").append(formatTimestamp(event.getTimeMillis())).append(C);
    builder.append("\"level\":").append(formatLevel(event.getLevel())).append(C);
    if (event.getThreadName() != null) {
        builder.append("\"_thread\":\"");
        JsonUtils.quoteAsString(event.getThreadName(), builder);
        builder.append(QC);
    }
    if (event.getLoggerName() != null) {
        builder.append("\"_logger\":\"");
        JsonUtils.quoteAsString(event.getLoggerName(), builder);
        builder.append(QC);
    }
    if (additionalFields.length > 0) {
        final StrSubstitutor strSubstitutor = getConfiguration().getStrSubstitutor();
        for (final KeyValuePair additionalField : additionalFields) {
            builder.append(QU);
            JsonUtils.quoteAsString(additionalField.getKey(), builder);
            builder.append("\":\"");
            final String value = valueNeedsLookup(additionalField.getValue())
                ? strSubstitutor.replace(event, additionalField.getValue())
                : additionalField.getValue();
            JsonUtils.quoteAsString(toNullSafeString(value), builder);
            builder.append(QC);
        }
    }
    if (includeThreadContext) {
        event.getContextData().forEach(WRITE_KEY_VALUES_INTO, builder);
    }
    if (event.getThrown() != null) {
        builder.append("\"full_message\":\"");
        if (includeStacktrace) {
            JsonUtils.quoteAsString(formatThrowable(event.getThrown()), builder);
        } else {
            JsonUtils.quoteAsString(event.getThrown().toString(), builder);
        }
        builder.append(QC);
    }

    builder.append("\"short_message\":\"");
    final Message message = event.getMessage();
    if (message instanceof CharSequence) {
        JsonUtils.quoteAsString(((CharSequence)message), builder);
    } else if (gcFree && message instanceof StringBuilderFormattable) {
        final StringBuilder messageBuffer = getMessageStringBuilder();
        try {
            ((StringBuilderFormattable) message).formatTo(messageBuffer);
            JsonUtils.quoteAsString(messageBuffer, builder);
        } finally {
            trimToMaxSize(messageBuffer);
        }
    } else {
        JsonUtils.quoteAsString(toNullSafeString(message.getFormattedMessage()), builder);
    }
    builder.append(Q);
    builder.append('}');
    if (includeNullDelimiter) {
        builder.append('\0');
    }
    return builder;
}
项目:logging-log4j2    文件:AbstractJacksonLayout.java   
/**
 * Additional fields to set on each log event.
 *
 * @return this builder
 */
public B setAdditionalFields(KeyValuePair[] additionalFields) {
    this.additionalFields = additionalFields;
    return asBuilder();
}
项目:logging-log4j2    文件:GelfLayout.java   
/**
 * Additional fields to set on each log event.
 *
 * @return this builder
 */
public B setAdditionalFields(final KeyValuePair[] additionalFields) {
    this.additionalFields = additionalFields;
    return asBuilder();
}