org.apache.logging.log4j.core.layout.PatternLayout Java Examples

The following examples show how to use org.apache.logging.log4j.core.layout.PatternLayout. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Main.java    From homework_tester with MIT License 7 votes vote down vote up
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

    PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
    appender.start();
    AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null);
    AppenderRef[] refs = new AppenderRef[]{ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null);
    loggerConfig.addAppender(appender, null, null);

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
 
Example #2
Source File: Log4j2Util.java    From summerframework with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private static void createAppenderAndStart(String loggerName, String fileName, String filePattern) {

    Layout layout = PatternLayout.newBuilder().withConfiguration(config)
        .withPattern("[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n").build();
    TimeBasedTriggeringPolicy tbtp = TimeBasedTriggeringPolicy.createPolicy(null, null);
    TriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy("10M");
    CompositeTriggeringPolicy policyComposite = CompositeTriggeringPolicy.createPolicy(tbtp, tp);

    String loggerDir = datalogDir + File.separator;

    String loggerPathPrefix = loggerDir + File.separator;
    RollingFileAppender.Builder builder = RollingFileAppender.newBuilder().withFilePattern(filePattern)
        .withStrategy(null).withPolicy(policyComposite).withConfiguration(config);
    RollingFileAppender appender = builder.build();
    appender.start();
    config.addAppender(appender);

    AppenderRef ref = AppenderRef.createAppenderRef(loggerName, Level.INFO, null);
    AppenderRef[] refs = new AppenderRef[] {ref};
    LoggerConfig loggerConfig =
        LoggerConfig.createLogger(false, Level.ALL, loggerName, "true", refs, null, config, null);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger(loggerName, loggerConfig);
    ctx.updateLoggers();
}
 
Example #3
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 7 votes vote down vote up
private static String logWithSpanAndLog4jConfiguration(
    String log4jPattern, SpanContext spanContext, Function<Logger, Void> loggingFunction) {
  StringWriter output = new StringWriter();
  StringLayout layout = PatternLayout.newBuilder().withPattern(log4jPattern).build();
  Appender appender =
      WriterAppender.newBuilder()
          .setTarget(output)
          .setLayout(layout)
          .setName("TestAppender")
          .build();
  ((LoggerContext) LogManager.getContext(false)).updateLoggers();
  appender.start();
  logger.addAppender(appender);
  logger.setLevel(Level.ALL);
  try {
    logWithSpan(spanContext, loggingFunction, logger);
    return output.toString();
  } finally {
    logger.removeAppender(appender);
  }
}
 
Example #4
Source File: Main.java    From homework_tester with MIT License 6 votes vote down vote up
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

    PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
    appender.start();
    AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null);
    AppenderRef[] refs = new AppenderRef[]{ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null);
    loggerConfig.addAppender(appender, null, null);

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
 
Example #5
Source File: ColumnMapping.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public ColumnMapping build() {
    if (pattern != null) {
        layout = PatternLayout.newBuilder()
            .setPattern(pattern)
            .setConfiguration(configuration)
            .setAlwaysWriteExceptions(false)
            .build();
    }
    if (!(layout == null
        || literal == null
        || Date.class.isAssignableFrom(type)
        || ReadOnlyStringMap.class.isAssignableFrom(type)
        || ThreadContextMap.class.isAssignableFrom(type)
        || ThreadContextStack.class.isAssignableFrom(type))) {
        LOGGER.error("No 'layout' or 'literal' value specified and type ({}) is not compatible with ThreadContextMap, ThreadContextStack, or java.util.Date for the mapping", type, this);
        return null;
    }
    if (literal != null && parameter != null) {
        LOGGER.error("Only one of 'literal' or 'parameter' can be set on the column mapping {}", this);
        return null;
    }
    return new ColumnMapping(name, source, layout, literal, parameter, type);
}
 
Example #6
Source File: RegexReplacementConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an instance of the class.
 *
 * @param config The current Configuration.
 * @param options pattern options, may be null.  If first element is "short",
 *                only the first line of the throwable will be formatted.
 * @return instance of class.
 */
public static RegexReplacementConverter newInstance(final Configuration config, final String[] options) {
    if (options.length != 3) {
        LOGGER.error("Incorrect number of options on replace. Expected 3 received " + options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on replace");
        return null;
    }
    if (options[1] == null) {
        LOGGER.error("No regular expression supplied on replace");
        return null;
    }
    if (options[2] == null) {
        LOGGER.error("No substitution supplied on replace");
        return null;
    }
    final Pattern p = Pattern.compile(options[1]);
    final PatternParser parser = PatternLayout.createPatternParser(config);
    final List<PatternFormatter> formatters = parser.parse(options[0]);
    return new RegexReplacementConverter(formatters, p, options[2]);
}
 
Example #7
Source File: MaxLengthConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an instance of the class.
 *
 * @param config  The current Configuration.
 * @param options pattern options, an array of two elements: pattern, max length (defaults to 100 on invalid value).
 * @return instance of class.
 */
public static MaxLengthConverter newInstance(final Configuration config, final String[] options) {
    if (options.length != 2) {
        LOGGER.error("Incorrect number of options on maxLength: expected 2 received {}: {}", options.length,
            options);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on maxLength");
        return null;
    }
    if (options[1] == null) {
        LOGGER.error("No length supplied on maxLength");
        return null;
    }
    final PatternParser parser = PatternLayout.createPatternParser(config);
    final List<PatternFormatter> formatters = parser.parse(options[0]);
    return new MaxLengthConverter(formatters, AbstractAppender.parseInt(options[1], 100));
}
 
Example #8
Source File: TestFileAuditAppender.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
protected void initTargetAppender() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    // get log file path from existing file appender
    RollingRandomAccessFileAppender mainFile =
            (RollingRandomAccessFileAppender) ctx.getConfiguration().getAppender("mainFile");

    String pathPrefix = mainFile == null
            ? System.getProperty("user.dir") + StringUtils.replace("/target/log", "/", File.separator)
            + File.separator
            : StringUtils.replace(mainFile.getFileName(), "core.log", StringUtils.EMPTY);

    targetAppender = FileAppender.newBuilder().
            setName(getTargetAppenderName()).
            withAppend(true).
            withFileName(pathPrefix + getTargetAppenderName() + ".log").
            setLayout(PatternLayout.newBuilder().
                    withPattern("%d{HH:mm:ss.SSS} %-5level %logger - %msg%n").
                    build()).
            build();
}
 
Example #9
Source File: HighlightConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an instance of the class.
 *
 * @param config The current Configuration.
 * @param options pattern options, may be null. If first element is "short", only the first line of the
 *                throwable will be formatted.
 * @return instance of class.
 */
public static HighlightConverter newInstance(final Configuration config, final String[] options) {
    if (options.length < 1) {
        LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on style");
        return null;
    }
    final PatternParser parser = PatternLayout.createPatternParser(config);
    final List<PatternFormatter> formatters = parser.parse(options[0]);
    final boolean disableAnsi = Arrays.toString(options).contains(PatternParser.DISABLE_ANSI + "=true");
    final boolean noConsoleNoAnsi = Arrays.toString(options).contains(PatternParser.NO_CONSOLE_NO_ANSI + "=true");
    final boolean hideAnsi = disableAnsi || (noConsoleNoAnsi && System.console() == null);
    return new HighlightConverter(formatters, createLevelStyleMap(options), hideAnsi);
}
 
Example #10
Source File: PatternLayoutBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private Layout createLayout(String pattern, final Log4j1Configuration config) {
    if (pattern == null) {
        LOGGER.info("No pattern provided for pattern layout, using default pattern");
        pattern = PatternLayout.DEFAULT_CONVERSION_PATTERN;
    }
    return new LayoutWrapper(PatternLayout.newBuilder()
            .setPattern(pattern
                    // Log4j 2's %x (NDC) is not compatible with Log4j 1's
                    // %x
                    // Log4j 1: "foo bar baz"
                    // Log4j 2: "[foo, bar, baz]"
                    // Use %ndc to get the Log4j 1 format
                    .replace("%x", "%ndc")

                    // Log4j 2's %X (MDC) is not compatible with Log4j 1's
                    // %X
                    // Log4j 1: "{{foo,bar}{hoo,boo}}"
                    // Log4j 2: "{foo=bar,hoo=boo}"
                    // Use %properties to get the Log4j 1 format
                    .replace("%X", "%properties"))
            .setConfiguration(config)
            .build());
}
 
Example #11
Source File: AbstractConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
protected void setToDefault() {
    // LOG4J2-1176 facilitate memory leak investigation
    setName(DefaultConfiguration.DEFAULT_NAME + "@" + Integer.toHexString(hashCode()));
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .setPattern(DefaultConfiguration.DEFAULT_PATTERN)
            .setConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    addAppender(appender);
    final LoggerConfig rootLoggerConfig = getRootLogger();
    rootLoggerConfig.addAppender(appender, null, null);

    final Level defaultLevel = Level.ERROR;
    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL,
            defaultLevel.name());
    final Level level = Level.valueOf(levelName);
    rootLoggerConfig.setLevel(level != null ? level : defaultLevel);
}
 
Example #12
Source File: EqualsReplacementConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an instance of the class.
 *
 * @param config  The current Configuration.
 * @param options pattern options, an array of three elements: pattern, testString, and substitution.
 * @return instance of class.
 */
public static EqualsReplacementConverter newInstance(final Configuration config, final String[] options) {
    if (options.length != 3) {
        LOGGER.error("Incorrect number of options on equals. Expected 3 received " + options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on equals");
        return null;
    }
    if (options[1] == null) {
        LOGGER.error("No test string supplied on equals");
        return null;
    }
    if (options[2] == null) {
        LOGGER.error("No substitution supplied on equals");
        return null;
    }
    final String p = options[1];
    final PatternParser parser = PatternLayout.createPatternParser(config);
    final List<PatternFormatter> formatters = parser.parse(options[0]);
    return new EqualsReplacementConverter(formatters, p, options[2], parser);
}
 
Example #13
Source File: LoggerFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static void initGuiLogging(String logFile) {
  ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
  builder.add(builder.newRootLogger(Level.INFO));
  LoggerContext context = Configurator.initialize(builder.build());

  PatternLayout layout = PatternLayout.newBuilder()
      .withPattern("[%d{ISO8601}] %5p (%F:%L) - %m%n")
      .withCharset(StandardCharsets.UTF_8)
      .build();

  Appender fileAppender = FileAppender.newBuilder()
      .setName("File")
      .setLayout(layout)
      .withFileName(logFile)
      .withAppend(false)
        .build();
  fileAppender.start();

  Appender textAreaAppender = TextAreaAppender.newBuilder()
      .setName("TextArea")
      .setLayout(layout)
      .build();
  textAreaAppender.start();

  context.getRootLogger().addAppender(fileAppender);
  context.getRootLogger().addAppender(textAreaAppender);
  context.updateLoggers();
}
 
Example #14
Source File: DebugFrameImplTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
void loggedCalls() throws Exception {
    final URL url = getClass().getResource("debugFrameImplTest.html");
    final String expectedLog = IOUtils.toString(getClass().getResourceAsStream("debugFrameImplTest.txt"),
            ISO_8859_1);

    final StringWriter stringWriter = new StringWriter();
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg%n").build();

    final WriterAppender writerAppender = WriterAppender.newBuilder().setName("writeLogger").setTarget(stringWriter)
            .setLayout(layout).build();
    writerAppender.start();

    loggerDebugFrameImpl_.addAppender(writerAppender);
    try {
        client_.getPage(url);
    }
    finally {
        loggerDebugFrameImpl_.removeAppender(writerAppender);
    }

    assertEquals(expectedLog, stringWriter.toString());
}
 
Example #15
Source File: TestStreamAppender.java    From samza with Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemProducerAppenderInAM() throws InterruptedException {
  System.setProperty("samza.container.name", "samza-job-coordinator");

  PatternLayout layout = PatternLayout.newBuilder().withPattern("%m").build();
  MockSystemProducerAppender systemProducerAppender = MockSystemProducerAppender.createAppender("testName", null, layout, false, null, null);
  systemProducerAppender.start();
  log.addAppender(systemProducerAppender);
  log.setLevel(Level.INFO);

  log.info("no-received"); // System isn't initialized yet, so this message should be dropped

  systemProducerAppender.setupSystem();
  MockSystemProducerAppender.systemInitialized = true;

  List<String> messages = Lists.newArrayList("testing3", "testing4");
  logAndVerifyMessages(messages);
  systemProducerAppender.stop();
}
 
Example #16
Source File: PatternResolver.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
PatternResolver(
        final EventResolverContext context,
        final TemplateResolverConfig config) {
    final String pattern = config.getString("pattern");
    if (Strings.isBlank(pattern)) {
        throw new IllegalArgumentException("blank pattern: " + config);
    }
    final PatternLayout patternLayout = PatternLayout
            .newBuilder()
            .setConfiguration(context.getConfiguration())
            .setCharset(context.getCharset())
            .setPattern(pattern)
            .build();
    this.emitter = (final StringBuilder stringBuilder, final LogEvent logEvent) ->
            patternLayout.serialize(logEvent, stringBuilder);
}
 
Example #17
Source File: CategoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClassName() {
    final Category category = Category.getInstance("TestCategory");
    final Layout<String> layout = PatternLayout.newBuilder().withPattern("%d %p %C{1.} [%t] %m%n").build();
    final ListAppender appender = new ListAppender("List2", null, layout, false, false);
    appender.start();
    category.setAdditivity(false);
    ((org.apache.logging.log4j.core.Logger) category.getLogger()).addAppender(appender);
    category.error("Test Message");
    final List<String> msgs = appender.getMessages();
    assertTrue("Incorrect number of messages. Expected 1 got " + msgs.size(), msgs.size() == 1);
    final String msg = msgs.get(0);
    appender.clear();
    final String threadName = Thread.currentThread().getName();
    final String expected = "ERROR o.a.l.CategoryTest [" + threadName + "] Test Message" + Strings.LINE_SEPARATOR;
    assertTrue("Incorrect message " + Strings.dquote(msg) + " expected " + Strings.dquote(expected), msg.endsWith(expected));
}
 
Example #18
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRefresh() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	PatternLayout layout = PatternLayout.newBuilder()
	// @formatter:off
			.setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
			.setConfiguration(config)
			.build();
	// @formatter:on
	Appender appender = FileAppender.newBuilder().setFileName("target/test.log").setLayout(layout)
			.setConfiguration(config).setBufferSize(4000).setName("File").build();
	// appender.start();
	config.addAppender(appender);
	AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
	AppenderRef[] refs = new AppenderRef[] { ref };
	LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "testlog4j2refresh", "true", refs,
			null, config, null);
	loggerConfig.addAppender(appender, null, null);
	config.addLogger("testlog4j2refresh", loggerConfig);
	ctx.stop();
	ctx.start(config);

	log.error("Info message");
}
 
Example #19
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEnvironment() throws Exception {
    ctx = Configurator.initialize("-config", null);
    LogManager.getLogger("org.apache.test.TestConfigurator");
    final Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName());
    final Map<String, Appender> map = config.getAppenders();
    assertNotNull("Appenders map should not be null.", map);
    assertThat(map, hasSize(greaterThan(0)));
    assertThat("No ListAppender named List2", map, hasKey("List2"));
    final Appender app = map.get("List2");
    final Layout<? extends Serializable> layout = app.getLayout();
    assertNotNull("Appender List2 does not have a Layout", layout);
    assertThat("Appender List2 is not configured with a PatternLayout", layout, instanceOf(PatternLayout.class));
    final String pattern = ((PatternLayout) layout).getConversionPattern();
    assertNotNull("No conversion pattern for List2 PatternLayout", pattern);
    assertFalse("Environment variable was not substituted", pattern.startsWith("${env:PATH}"));
}
 
Example #20
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testLog() {
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("%d %C %L %m").build();
    final ListAppender appender = new ListAppender("List", null, layout, false, false);
    appender.start();
    final Logger root = Logger.getRootLogger();
    try {
        ((org.apache.logging.log4j.core.Logger) root.getLogger()).addAppender(appender);
        root.setLevel(Level.INFO);
        final MyLogger log = new MyLogger(root);
        log.logInfo("This is a test", null);
        root.log(Priority.INFO, "Test msg2", null);
        root.log(Priority.INFO, "Test msg3");
        final List<String> msgs = appender.getMessages();
        assertTrue("Incorrect number of messages", msgs.size() == 3);
        final String msg = msgs.get(0);
        assertTrue("Message contains incorrect class name: " + msg, msg.contains(LoggerTest.class.getName()));
        appender.stop();
    } finally {
        ((org.apache.logging.log4j.core.Logger) root.getLogger()).removeAppender(appender);
    }
}
 
Example #21
Source File: StyleConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an instance of the class.
 *
 * @param config
 *            The current Configuration.
 * @param options
 *            pattern options, may be null. If first element is "short", only the first line of the throwable will
 *            be formatted.
 * @return instance of class.
 */
public static StyleConverter newInstance(final Configuration config, final String[] options) {
    if (options == null) {
        return null;
    }
    if (options.length < 2) {
        LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied for style converter");
        return null;
    }
    if (options[1] == null) {
        LOGGER.error("No style attributes supplied for style converter");
        return null;
    }
    final PatternParser parser = PatternLayout.createPatternParser(config);
    final List<PatternFormatter> formatters = parser.parse(options[0]);
    final String style = AnsiEscape.createSequence(options[1].split(Patterns.COMMA_SEPARATOR));
    final boolean disableAnsi = Arrays.toString(options).contains(PatternParser.DISABLE_ANSI + "=true");
    final boolean noConsoleNoAnsi = Arrays.toString(options).contains(PatternParser.NO_CONSOLE_NO_ANSI + "=true");
    final boolean hideAnsi = disableAnsi || (noConsoleNoAnsi && System.console() == null);
    return new StyleConverter(formatters, style, hideAnsi);
}
 
Example #22
Source File: TestStreamAppender.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomStreamName() {
  System.setProperty("samza.container.name", "samza-container-1");
  PatternLayout layout = PatternLayout.newBuilder().withPattern("%m").build();
  MockSystemProducerAppender systemProducerAppender = MockSystemProducerAppender.createAppender("testName", null, layout, false, null, "test-stream-name");
  systemProducerAppender.start();
  log.addAppender(systemProducerAppender);
  Assert.assertEquals("test-stream-name", systemProducerAppender.getStreamName());
}
 
Example #23
Source File: TestStreamAppender.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoStreamCreationUponSetupByDefault() {
  System.setProperty("samza.container.name", "samza-container-1");

  PatternLayout layout = PatternLayout.newBuilder().withPattern("%m").build();
  MockSystemProducerAppender systemProducerAppender = MockSystemProducerAppender.createAppender("testName", null, layout, false, null, null);
  systemProducerAppender.start();
  log.addAppender(systemProducerAppender);

  Assert.assertEquals("", MockSystemAdmin.createdStreamName);
}
 
Example #24
Source File: TestStreamAppender.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultStreamName() {
  System.setProperty("samza.container.name", "samza-container-1");
  PatternLayout layout = PatternLayout.newBuilder().withPattern("%m").build();
  MockSystemProducerAppender systemProducerAppender = MockSystemProducerAppender.createAppender("testName", null, layout, false, null, null);
  systemProducerAppender.start();
  log.addAppender(systemProducerAppender);
  Assert.assertEquals("__samza_log4jTest_1_logs", systemProducerAppender.getStreamName());
}
 
Example #25
Source File: WriterAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public WriterAppender build() {
    final StringLayout layout = (StringLayout) getLayout();
    final StringLayout actualLayout = layout != null ? layout : PatternLayout.createDefaultLayout();
    return new WriterAppender(getName(), actualLayout, getFilter(), getManager(target, follow, actualLayout),
            isIgnoreExceptions(), getPropertyArray());
}
 
Example #26
Source File: AbstractCsvLayout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected AbstractCsvLayout(final Configuration config, final Charset charset, final CSVFormat csvFormat,
        final String header, final String footer) {
    super(config, charset, 
            PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(header).build(),
            PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footer).build());
    this.format = csvFormat;
}
 
Example #27
Source File: AbstractStyleNameConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a list of PatternFormatter from the given configuration and options or null if no pattern is supplied.
 *
 * @param config A configuration.
 * @param options pattern options.
 * @return a list of PatternFormatter from the given configuration and options or null if no pattern is supplied.
 */
private static List<PatternFormatter> toPatternFormatterList(final Configuration config, final String[] options) {
    if (options.length == 0 || options[0] == null) {
        LOGGER.error("No pattern supplied on style for config=" + config);
        return null;
    }
    final PatternParser parser = PatternLayout.createPatternParser(config);
    if (parser == null) {
        LOGGER.error("No PatternParser created for config=" + config + ", options=" + Arrays.toString(options));
        return null;
    }
    return parser.parse(options[0]);
}
 
Example #28
Source File: OnStartupTriggeringPolicyTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPolicy() throws Exception {
    //System.setProperty("log4j2.debug", "true");
    //System.setProperty("log4j2.StatusLogger.level", "trace");
    final Configuration configuration = new DefaultConfiguration();
    final Path target = Paths.get(TARGET_FILE);
    target.toFile().getParentFile().mkdirs();
    final long timeStamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
    final String expectedDate = formatter.format(timeStamp);
    final String rolledFileName = ROLLED_FILE_PREFIX + expectedDate + ROLLED_FILE_SUFFIX;
    final Path rolled = Paths.get(rolledFileName);
    final long copied;
    try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes("UTF-8"))) {
        copied = Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
    }
    final long size = Files.size(target);
    assertTrue(size > 0);
    assertEquals(copied, size);

    final FileTime fileTime = FileTime.fromMillis(timeStamp);
    final BasicFileAttributeView attrs = Files.getFileAttributeView(target, BasicFileAttributeView.class);
    attrs.setTimes(fileTime, fileTime, fileTime);
    final PatternLayout layout = PatternLayout.newBuilder().setPattern("%msg").setConfiguration(configuration)
            .build();
    final RolloverStrategy strategy = DefaultRolloverStrategy.newBuilder().setCompressionLevelStr("0")
            .setStopCustomActionsOnError(true).setConfig(configuration).build();
    final OnStartupTriggeringPolicy policy = OnStartupTriggeringPolicy.createPolicy(1);
    try (final RollingFileManager manager = RollingFileManager.getFileManager(TARGET_FILE, TARGET_PATTERN, true,
            false, policy, strategy, null, layout, 8192, true, false, null, null, null, configuration)) {
        manager.initialize();
        final String files = Arrays.toString(new File(TARGET_FOLDER).listFiles());
        assertTrue(target.toString() + ", files = " + files, Files.exists(target));
        assertEquals(target.toString(), 0, Files.size(target));
        assertTrue("Missing: " + rolled.toString() + ", files on disk = " + files, Files.exists(rolled));
        assertEquals(rolled.toString(), size, Files.size(rolled));
    }
}
 
Example #29
Source File: SyslogRewriteAuditAppender.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTargetAppender() {
    targetAppender = SyslogAppender.newSyslogAppenderBuilder().
            setName(getTargetAppenderName()).
            withHost("localhost").
            withPort(514).
            withProtocol(Protocol.UDP).
            setLayout(PatternLayout.newBuilder().withPattern("%d{ISO8601} %-5level %logger - %msg%n").build()).
            setFacility(Facility.LOCAL1).
            build();
}
 
Example #30
Source File: IbisPatternLayout.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
 * @param pattern the pattern to use or DEFAULT when null
 * @param alwaysWriteExceptions defaults to true
 * @param disableAnsi defaults to false
 * @param noConsoleNoAnsi defaults to false
 */
IbisPatternLayout(final Configuration config, final String pattern, final Charset charset, final boolean alwaysWriteExceptions, final boolean disableAnsi, final boolean noConsoleNoAnsi) {
	super(config, charset);

	try {
		final PatternParser parser = PatternLayout.createPatternParser(configuration);
		final List<PatternFormatter> list = parser.parse(pattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi);
		final PatternFormatter[] formatters = list.toArray(new PatternFormatter[0]);
		serializer = new PatternSerializer(formatters);
	} catch (final RuntimeException ex) {
		throw new IllegalArgumentException("Cannot parse pattern '" + pattern + "'", ex);
	}
}