Java Code Examples for org.apache.logging.log4j.core.Layout

The following examples show how to use org.apache.logging.log4j.core.Layout. These examples are extracted from open source projects. 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 Project: logging-log4j2   Source File: CategoryTest.java    License: 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().setPattern("%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 2
Source Project: vividus   Source File: AllureLogAppender.java    License: Apache License 2.0 6 votes vote down vote up
@PluginFactory
public static AllureLogAppender createAppender(@PluginAttribute("name") final String name,
        @PluginElement("Filter") Filter filter, @PluginElement("Layout") Layout<? extends Serializable> layout)
{
    if (name == null)
    {
        LOGGER.error("No name provided for AllureLogAppender");
        instance = null;
    }
    else
    {
        instance = new AllureLogAppender(name, filter, layout);
    }

    return instance;
}
 
Example 3
@SuppressWarnings("unused")
@PluginFactory
public static UIAppender createAppender(@PluginAttribute("name") String name, @PluginAttribute("maxLines") int maxLines,
			@PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
			@PluginElement("Layout") Layout<?> layout, @PluginElement("Filters") Filter filter) {
	if (name == null) {
		LOGGER.error("No name provided for UIAppender");
		return null;
	}

	if (layout == null) {
		layout = JsonLayout.createDefaultLayout();
	}

	return new UIAppender(name, layout, filter, maxLines, ignoreExceptions);
}
 
Example 4
Source Project: logging-log4j2   Source File: SslSocketManager.java    License: Apache License 2.0 6 votes vote down vote up
public static SslSocketManager getSocketManager(final SslConfiguration sslConfig, final String host, int port,
        final int connectTimeoutMillis, int reconnectDelayMillis, final boolean immediateFail,
        final Layout<? extends Serializable> layout, final int bufferSize, final SocketOptions socketOptions) {
    if (Strings.isEmpty(host)) {
        throw new IllegalArgumentException("A host name is required");
    }
    if (port <= 0) {
        port = DEFAULT_PORT;
    }
    if (reconnectDelayMillis == 0) {
        reconnectDelayMillis = DEFAULT_RECONNECTION_DELAY_MILLIS;
    }
    final String name = "TLS:" + host + ':' + port;
    return (SslSocketManager) getManager(name, new SslFactoryData(sslConfig, host, port, connectTimeoutMillis,
            reconnectDelayMillis, immediateFail, layout, bufferSize, socketOptions), FACTORY);
}
 
Example 5
Source Project: rocketmq-read   Source File: RocketmqLog4j2Appender.java    License: Apache License 2.0 6 votes vote down vote up
protected RocketmqLog4j2Appender(String name, Filter filter, Layout<? extends Serializable> layout,
    boolean ignoreExceptions, String nameServerAddress, String producerGroup,
    String topic, String tag) {
    super(name, filter, layout, ignoreExceptions);
    this.producer = producer;
    this.topic = topic;
    this.tag = tag;
    this.nameServerAddress = nameServerAddress;
    this.producerGroup = producerGroup;
    try {
        this.producer = ProducerInstance.getProducerInstance().getInstance(this.nameServerAddress, this.producerGroup);
    } catch (Exception e) {
        ErrorHandler handler = this.getHandler();
        if (handler != null) {
            handler.error("Starting RocketmqLog4j2Appender [" + this.getName()
                + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
        }
    }
}
 
Example 6
Source Project: summerframework   Source File: AdvancedKafkaAppender.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void append(final LogEvent event) {
    try {
        final Layout<? extends Serializable> layout = getLayout();
        byte[] data;
        if (layout != null) {
            if (layout instanceof SerializedLayout) {
                final byte[] header = layout.getHeader();
                final byte[] body = layout.toByteArray(event);
                data = new byte[header.length + body.length];
                System.arraycopy(header, 0, data, 0, header.length);
                System.arraycopy(body, 0, data, header.length, body.length);
            } else {
                data = layout.toByteArray(event);
            }
        } else {
            data = StringEncoder.toBytes(event.getMessage().getFormattedMessage(), StandardCharsets.UTF_8);
        }
        manager.send(topic, data);
    } catch (final Exception e) {
        LOGGER.error("Unable to write to Kafka [{}] for appender [{}].", manager.getName(), getName(), e);
        throw new AppenderLoggingException("Unable to write to Kafka in appender: " + e.getMessage(), e);
    }
}
 
Example 7
private RollingRandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout,
        final Filter filter, final RollingRandomAccessFileManager manager, final String fileName,
        final String filePattern, final boolean ignoreExceptions,
        final boolean immediateFlush, final int bufferSize, final Advertiser advertiser) {
    super(name, layout, filter, ignoreExceptions, immediateFlush, null, manager);
    if (advertiser != null) {
        final Map<String, String> configuration = new HashMap<>(layout.getContentFormat());
        configuration.put("contentType", layout.getContentType());
        configuration.put("name", name);
        advertisement = advertiser.advertise(configuration);
    } else {
        advertisement = null;
    }
    this.fileName = fileName;
    this.filePattern = filePattern;
    this.advertiser = advertiser;
}
 
Example 8
Source Project: logging-log4j2   Source File: Log4j2_2195_Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    logger.info("This is a test.", new Exception("Test exception!"));
    ListAppender listAppender = loggerContextRule.getListAppender("ListAppender");
    Assert.assertNotNull(listAppender);
    List<String> events = listAppender.getMessages();
    Assert.assertNotNull(events);
    Assert.assertEquals(1, events.size());
    String logEvent = events.get(0);
    Assert.assertNotNull(logEvent);
    Assert.assertFalse("\"org.junit\" should not be here", logEvent.contains("org.junit"));
    Assert.assertFalse("\"org.eclipse\" should not be here", logEvent.contains("org.eclipse"));
    //
    Layout<? extends Serializable> layout = listAppender.getLayout();
    PatternLayout pLayout = (PatternLayout) layout;
    Assert.assertNotNull(pLayout);
    Serializer eventSerializer = pLayout.getEventSerializer();
    Assert.assertNotNull(eventSerializer);
    //
    Assert.assertTrue("Missing \"|\"", logEvent.contains("|"));
}
 
Example 9
Source Project: logging-log4j2   Source File: LogstashIT.java    License: Apache License 2.0 6 votes vote down vote up
private static SocketAppender createStartedAppender(
        final Layout<?> layout,
        final int port) {
    LOGGER.info("creating the appender");
    final SocketAppender appender = SocketAppender
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setHost(HOST_NAME)
            .setPort(port)
            .setReconnectDelayMillis(100)
            .setName("LogstashItAppender")
            .setBufferedIo(false)
            .setImmediateFail(true)
            .setIgnoreExceptions(false)
            .setLayout(layout)
            .build();
    appender.start();
    return appender;
}
 
Example 10
@Test
public void appenderUsesProvidedLayoutWhenMessageOnlyIsSetToFalse() {

    // given
    Layout layout = PowerMockito.mock(Layout.class);

    ElasticsearchAppender.Builder builder = ElasticsearchAppenderTest.createTestElasticsearchAppenderBuilder();
    builder.withMessageOnly(false);
    builder.withLayout(layout);

    LogEvent logEvent = mock(LogEvent.class);

    ElasticsearchAppender appender = builder.build();

    // when
    appender.append(logEvent);

    // then
    ArgumentCaptor<LogEvent> captor = ArgumentCaptor.forClass(LogEvent.class);
    verify(layout, times(1)).toSerializable(captor.capture());
    assertEquals(logEvent, captor.getValue());
}
 
Example 11
Source Project: logging-log4j2   Source File: TcpSocketManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Obtains a TcpSocketManager.
 * 
 * @param host
 *            The host to connect to.
 * @param port
 *            The port on the host.
 * @param connectTimeoutMillis
 *            the connect timeout in milliseconds
 * @param reconnectDelayMillis
 *            The interval to pause between retries.
 * @param bufferSize
 *            The buffer size.
 * @return A TcpSocketManager.
 */
public static TcpSocketManager getSocketManager(final String host, int port, final int connectTimeoutMillis,
        int reconnectDelayMillis, final boolean immediateFail, final Layout<? extends Serializable> layout,
        final int bufferSize, final SocketOptions socketOptions) {
    if (Strings.isEmpty(host)) {
        throw new IllegalArgumentException("A host name is required");
    }
    if (port <= 0) {
        port = DEFAULT_PORT;
    }
    if (reconnectDelayMillis == 0) {
        reconnectDelayMillis = DEFAULT_RECONNECTION_DELAY_MILLIS;
    }
    return (TcpSocketManager) getManager("TCP:" + host + ':' + port, new FactoryData(host, port,
            connectTimeoutMillis, reconnectDelayMillis, immediateFail, layout, bufferSize, socketOptions), FACTORY);
}
 
Example 12
Source Project: logging-log4j2   Source File: RollingFileManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
  * @since 2.9
  */
 protected RollingFileManager(final LoggerContext loggerContext, final String fileName, final String pattern, final OutputStream os,
         final boolean append, final boolean createOnDemand, final long size, final long initialTime,
         final TriggeringPolicy triggeringPolicy, final RolloverStrategy rolloverStrategy,
         final String advertiseURI, final Layout<? extends Serializable> layout,
         final String filePermissions, final String fileOwner, final String fileGroup,
         final boolean writeHeader, final ByteBuffer buffer) {
     super(loggerContext, fileName != null ? fileName : pattern, os, append, false, createOnDemand,
advertiseURI, layout, filePermissions, fileOwner, fileGroup, writeHeader, buffer);
     this.size = size;
     this.initialTime = initialTime;
     this.triggeringPolicy = triggeringPolicy;
     this.rolloverStrategy = rolloverStrategy;
     this.patternProcessor = new PatternProcessor(pattern);
     this.patternProcessor.setPrevFileTime(initialTime);
     this.fileName = fileName;
     this.directWrite = rolloverStrategy instanceof DirectFileRolloverStrategy;
 }
 
Example 13
Source Project: pulsar   Source File: PulsarAppender.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
@Override
public PulsarAppender build() {
    final Layout<? extends Serializable> layout = getLayout();
    if (layout == null) {
        AbstractLifeCycle.LOGGER.error("No layout provided for PulsarAppender");
        return null;
    }
    PulsarManager manager = new PulsarManager(
        getConfiguration().getLoggerContext(),
        getName(),
        serviceUrl,
        topic,
        syncSend,
        properties,
        key);
    return new PulsarAppender(
        getName(),
        layout,
        getFilter(),
        isIgnoreExceptions(),
        avoidRecursive,
        manager);
}
 
Example 14
Source Project: logging-log4j2   Source File: TestConfigurator.java    License: 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 15
Source Project: logging-log4j2   Source File: MemoryMappedFileManager.java    License: Apache License 2.0 5 votes vote down vote up
protected MemoryMappedFileManager(final RandomAccessFile file, final String fileName, final OutputStream os,
        final boolean immediateFlush, final long position, final int regionLength, final String advertiseURI,
        final Layout<? extends Serializable> layout, final boolean writeHeader) throws IOException {
    super(os, fileName, layout, writeHeader, ByteBuffer.wrap(new byte[0]));
    this.immediateFlush = immediateFlush;
    this.randomAccessFile = Objects.requireNonNull(file, "RandomAccessFile");
    this.regionLength = regionLength;
    this.advertiseURI = advertiseURI;
    this.isEndOfBatch.set(Boolean.FALSE);
    this.mappedBuffer = mmap(randomAccessFile.getChannel(), getFileName(), position, regionLength);
    this.byteBuffer = mappedBuffer;
    this.mappingOffset = position;
}
 
Example 16
Source Project: logging-log4j2   Source File: DemoAppender.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void append(final LogEvent event) {
    final Layout<?> layout = getLayout();
    if (layout instanceof NoGcLayout) {
        layout.encode(event, this);
        drain(byteBuffer);
    } else {
        final byte[] binary = getLayout().toByteArray(event);
        consume(binary, 0, binary.length);
    }
}
 
Example 17
Source Project: logging-log4j2   Source File: ServletAppender.java    License: Apache License 2.0 5 votes vote down vote up
private ServletAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
        final ServletContext servletContext, final boolean ignoreExceptions, final boolean logThrowables,
        Property[] properties) {
    super(name, filter, layout, ignoreExceptions, properties);
    this.servletContext = servletContext;
    this.logThrowables = logThrowables;
}
 
Example 18
Source Project: summerframework   Source File: Log4j2Configuration.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void init() {
    try {
        LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
        if (loggerContext == null)
            return;
        org.apache.logging.log4j.core.Logger logger =
            loggerContext.getLogger("org.apache.kafka.clients.producer.ProducerConfig");
        if (logger != null) {
            logger.setLevel(org.apache.logging.log4j.Level.ERROR);
        }
        createBizLogger();
        Configuration configuration = loggerContext.getConfiguration();
        configuration.getPluginPackages().add("org.apache.skywalking.apm.toolkit.log.log4j.v2.x");
        Map<String, Appender> appenders = configuration.getAppenders();
        for (Appender appender : appenders.values()) {
            Layout<? extends Serializable> layout = appender.getLayout();
            if (layout instanceof PatternLayout) {
                PatternLayout patternLayOut = (PatternLayout)layout;
                Serializer serializer = PatternLayout.createSerializer(configuration, null, getLog4jPattern(),
                    getLog4jPattern(), null, true, true);
                Field field = patternLayOut.getClass().getDeclaredField("eventSerializer");
                Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                field.set(patternLayOut, serializer);
            }
        }
        loggerContext.updateLoggers();
    } catch (Throwable e) {
        logger.warn(e.getMessage());
    }
}
 
Example 19
Source Project: log4j2-gelf   Source File: GelfAppender.java    License: Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 20
Source Project: Flashtool   Source File: ConsoleAppender.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Factory method. Log4j will parse the configuration and call this factory 
 * method to construct the appender with
 * the configured attributes.
 *
 * @param name   Name of appender
 * @param layout Log layout of appender
 * @param filter Filter for appender
 * @return The TextAreaAppender
 */
@PluginFactory
public static ConsoleAppender createAppender(
    @PluginAttribute("name") String name,
    @PluginElement("Layout") Layout<? extends Serializable> layout,
    @PluginElement("Filter") final Filter filter) {
  if (name == null) {
    LOGGER.error("No name provided for TextAreaAppender2");
    return null;
  }
  if (layout == null) {
    layout = PatternLayout.createDefaultLayout();
  }
  return new ConsoleAppender(name, filter, layout, true);
}
 
Example 21
Source Project: xian   Source File: GelfLogAppender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a gelfLogAppender with specified layout.
 */
public GelfLogAppender(String name, Filter filter, Layout layout, MdcGelfMessageAssembler gelfMessageAssembler, boolean ignoreExceptions) {
    super(name, filter, layout, ignoreExceptions);
    this.gelfMessageAssembler = gelfMessageAssembler;

    if (ignoreExceptions) {
        errorReporter = ERROR_REPORTER;
    } else {
        errorReporter = PROPAGATING_ERROR_REPORTER;
    }
}
 
Example 22
Source Project: TerminalConsoleAppender   Source File: TerminalConsoleAppender.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a new {@link TerminalConsoleAppender}.
 *
 * @param name The name of the appender
 * @param filter The filter, can be {@code null}
 * @param layout The layout, can be {@code null}
 * @param ignoreExceptions If {@code true} exceptions encountered when
 *     appending events are logged, otherwise they are propagated to the
 *     caller
 * @return The new appender
 */
@PluginFactory
public static TerminalConsoleAppender createAppender(
        @Required(message = "No name provided for TerminalConsoleAppender") @PluginAttribute("name") String name,
        @PluginElement("Filter") Filter filter,
        @PluginElement("Layout") @Nullable Layout<? extends Serializable> layout,
        @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) boolean ignoreExceptions) {

    if (layout == null) {
        layout = PatternLayout.createDefaultLayout();
    }

    return new TerminalConsoleAppender(name, filter, layout, ignoreExceptions);
}
 
Example 23
Source Project: collect-earth   Source File: JSwingAppender.java    License: MIT License 5 votes vote down vote up
@PluginFactory
public static JSwingAppender createAppender(@PluginAttribute("name") String name,
		@PluginElement("Layout") Layout<?> layout, @PluginElement("Filters") Filter filter,
		@PluginAttribute("ignoreExceptions") boolean ignoreExceptions) {

	if (name == null) {
		LoggerFactory.getLogger( JSwingAppender.class ).error("No name provided for JTextAreaAppender");
		return null;
	}

	if (layout == null) {
		layout = PatternLayout.createDefaultLayout();
	}
	return new JSwingAppender(name, filter, layout, ignoreExceptions);
}
 
Example 24
Source Project: logging-log4j2   Source File: LogstashIT.java    License: Apache License 2.0 5 votes vote down vote up
private static <K> Map<K, Object> appendAndCollect(
        final List<LogEvent> logEvents,
        final Layout<?> layout,
        final int port,
        final Function<Map<String, Object>, K> keyMapper,
        final Set<String> excludedKeys) throws IOException {
    try (final RestHighLevelClient client = createClient()) {
        final Appender appender = createStartedAppender(layout, port);
        try {

            // Append the event.
            LOGGER.info("appending events");
            logEvents.forEach(appender::append);
            LOGGER.info("completed appending events");

            // Wait the message to arrive.
            Awaitility
                    .await()
                    .atMost(Duration.ofSeconds(60))
                    .pollDelay(Duration.ofSeconds(2))
                    .until(() -> queryDocumentCount(client) == LOG_EVENT_COUNT);

            // Retrieve the persisted messages.
            return queryDocuments(client)
                    .stream()
                    .collect(Collectors.toMap(
                            keyMapper,
                            (final Map<String, Object> source) -> {
                                excludedKeys.forEach(source::remove);
                                return source;
                            }));

        } finally {
            appender.stop();
        }
    }
}
 
Example 25
Source Project: logging-log4j2   Source File: RandomAccessFileManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param append Append status.
 * @param bufferSize size of the buffer
 * @param configuration The configuration.
 */
public FactoryData(final boolean append, final boolean immediateFlush, final int bufferSize,
        final String advertiseURI, final Layout<? extends Serializable> layout, final Configuration configuration) {
    super(configuration);
    this.append = append;
    this.immediateFlush = immediateFlush;
    this.bufferSize = bufferSize;
    this.advertiseURI = advertiseURI;
    this.layout = layout;
}
 
Example 26
private Layout<?> testConsole(final String configResource) throws Exception {
    final Configuration configuration = getConfiguration(configResource);
    final String name = "Console";
    final ConsoleAppender appender = configuration.getAppender(name);
    assertNotNull("Missing appender '" + name + "' in configuration " + configResource + " → " + configuration,
            appender);
    assertEquals(Target.SYSTEM_ERR, appender.getTarget());
    //
    final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
    assertNotNull(loggerConfig);
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    configuration.start();
    configuration.stop();
    return appender.getLayout();
}
 
Example 27
Source Project: logging-log4j2   Source File: JsonTemplateLayoutTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void usingSerializedLogEventAccessor(
        final Layout<String> layout,
        final LogEvent logEvent,
        final Consumer<MapAccessor> accessorConsumer) {
    final String serializedLogEventJson = layout.toSerializable(logEvent);
    @SuppressWarnings("unchecked")
    final Map<String, Object> serializedLogEvent =
            (Map<String, Object>) readJson(serializedLogEventJson);
    final MapAccessor serializedLogEventAccessor = new MapAccessor(serializedLogEvent);
    accessorConsumer.accept(serializedLogEventAccessor);
}
 
Example 28
Source Project: support-diagnostics   Source File: BaseService.java    License: Apache License 2.0 5 votes vote down vote up
protected void createFileAppender(String logDir, String logFile) {

        logPath = logDir + SystemProperties.fileSeparator + logFile;

        Layout layout = PatternLayout.newBuilder()
                .withConfiguration(logConfig)
                .withPattern("%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n")
                .build();

        FileAppender.Builder builder = FileAppender.newBuilder();
        builder.setConfiguration(logConfig);
        builder.withFileName(logPath);
        builder.withAppend(false);
        builder.withLocking(false);
        builder.setName("packaged");
        builder.setIgnoreExceptions(false);
        builder.withImmediateFlush(true);
        builder.withBufferedIo(false);
        builder.withBufferSize(0);
        builder.setLayout(layout);
        Appender diagAppender = builder.build();

        Appender oldAppender = logConfig.getAppender("packaged");
        if(oldAppender != null && oldAppender.isStarted()){
            oldAppender.stop();
            logConfig.getRootLogger().removeAppender("packaged");
        }

        diagAppender.start();
        logConfig.addAppender(diagAppender);
        AppenderRef.createAppenderRef("packaged", null, null);
        logConfig.getRootLogger().addAppender(diagAppender, null, null);
        loggerContext.updateLoggers();
        logger.info(Constants.CONSOLE, "Diagnostic logger reconfigured for inclusion into archive");

    }
 
Example 29
Source Project: logging-log4j2   Source File: KafkaAppender.java    License: Apache License 2.0 5 votes vote down vote up
private void tryAppend(final LogEvent event) throws ExecutionException, InterruptedException, TimeoutException {
    final Layout<? extends Serializable> layout = getLayout();
    byte[] data;
    Long eventTimestamp;

    data = layout.toByteArray(event);
    eventTimestamp = event.getTimeMillis();
    manager.send(data, eventTimestamp);
}
 
Example 30
Source Project: ModPackDownloader   Source File: TextAreaAppender.java    License: MIT License 5 votes vote down vote up
/**
 * Factory method. Log4j will parse the configuration and call this factory
 * method to construct the appender with
 * the configured attributes.
 *
 * @param name   Name of appender
 * @param layout Log layout of appender
 * @param filter Filter for appender
 * @return The TextAreaAppender
 */
@PluginFactory
public static TextAreaAppender createAppender(
		@PluginAttribute("name") String name,
		@PluginElement("Layout") Layout<? extends Serializable> layout,
		@PluginElement("Filter") final Filter filter) {
	if (name == null) {
		LOGGER.error("No name provided for TextAreaAppender");
		return null;
	}
	if (layout == null) {
		layout = PatternLayout.createDefaultLayout();
	}
	return new TextAreaAppender(name, filter, layout, true);
}