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

The following examples show how to use org.apache.logging.log4j.core.Layout. 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: SslSocketManager.java    From logging-log4j2 with 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 #2
Source File: RollingFileManager.java    From logging-log4j2 with 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 #3
Source File: AdvancedKafkaAppender.java    From summerframework with 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 #4
Source File: Log4j2_2195_Test.java    From logging-log4j2 with 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 #5
Source File: PulsarAppender.java    From pulsar with 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 #6
Source File: RollingRandomAccessFileAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: RocketmqLog4j2Appender.java    From rocketmq-read with 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 #8
Source File: LogstashIT.java    From logging-log4j2 with 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 #9
Source File: ElasticsearchAppenderTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@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 #10
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 #11
Source File: TcpSocketManager.java    From logging-log4j2 with 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 File: UIAppender.java    From patchwork-patcher with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #13
Source File: AllureLogAppender.java    From vividus with 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 #14
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().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 #15
Source File: Log4j2Configuration.java    From summerframework with 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 #16
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testFile(final String configResource) throws Exception {
	final Configuration configuration = getConfiguration(configResource);
	final FileAppender appender = configuration.getAppender("File");
	assertNotNull(appender);
	assertEquals("target/mylog.txt", appender.getFileName());
	//
	final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
	assertNotNull(loggerConfig);
	assertEquals(Level.DEBUG, loggerConfig.getLevel());
	configuration.start();
	configuration.stop();
	return appender.getLayout();
}
 
Example #17
Source File: DemoAppender.java    From logging-log4j2 with 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 #18
Source File: ConsoleAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public ConsoleAppender build() {
    if (follow && direct) {
        throw new IllegalArgumentException("Cannot use both follow and direct on ConsoleAppender '" + getName() + "'");
    }
    final Layout<? extends Serializable> layout = getOrCreateLayout(target.getDefaultCharset());
    return new ConsoleAppender(getName(), layout, getFilter(), getManager(target, follow, direct, layout),
            isIgnoreExceptions(), target, getPropertyArray());
}
 
Example #19
Source File: StreamAppender.java    From samza with Apache License 2.0 5 votes vote down vote up
@PluginFactory
public static StreamAppender createAppender(
    @PluginAttribute("name") final String name,
    @PluginElement("Filter") final Filter filter,
    @PluginElement("Layout") Layout layout,
    @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) final boolean ignoreExceptions,
    @PluginAttribute("streamName") String streamName) {
  return new StreamAppender(name, filter, layout, ignoreExceptions, streamName);
}
 
Example #20
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with 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 #21
Source File: JeroMqAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private JeroMqAppender(final String name, final Filter filter, final Layout<? extends Serializable> layout,
        final boolean ignoreExceptions, final List<String> endpoints, final long affinity, final long backlog,
        final boolean delayAttachOnConnect, final byte[] identity, final boolean ipv4Only, final long linger,
        final long maxMsgSize, final long rcvHwm, final long receiveBufferSize, final int receiveTimeOut,
        final long reconnectIVL, final long reconnectIVLMax, final long sendBufferSize, final int sendTimeOut,
        final long sndHWM, final int tcpKeepAlive, final long tcpKeepAliveCount, final long tcpKeepAliveIdle,
        final long tcpKeepAliveInterval, final boolean xpubVerbose, Property[] properties) {
    super(name, filter, layout, ignoreExceptions, properties);
    this.manager = JeroMqManager.getJeroMqManager(name, affinity, backlog, delayAttachOnConnect, identity, ipv4Only,
        linger, maxMsgSize, rcvHwm, receiveBufferSize, receiveTimeOut, reconnectIVL, reconnectIVLMax,
        sendBufferSize, sendTimeOut, sndHWM, tcpKeepAlive, tcpKeepAliveCount, tcpKeepAliveIdle,
        tcpKeepAliveInterval, xpubVerbose, endpoints);
    this.endpoints = endpoints;
}
 
Example #22
Source File: RollingRandomAccessFileManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static RollingRandomAccessFileManager getRollingRandomAccessFileManager(final String fileName,
        final String filePattern, final boolean isAppend, final boolean immediateFlush, final int bufferSize,
        final TriggeringPolicy policy, final RolloverStrategy strategy, final String advertiseURI,
        final Layout<? extends Serializable> layout, final String filePermissions, final String fileOwner, final String fileGroup,
        final Configuration configuration) {
    if (strategy instanceof DirectWriteRolloverStrategy && fileName != null) {
        LOGGER.error("The fileName attribute must not be specified with the DirectWriteRolloverStrategy");
        return null;
    }
    final String name = fileName == null ? filePattern : fileName;
    return narrow(RollingRandomAccessFileManager.class, getManager(name, new FactoryData(fileName, filePattern, isAppend,
            immediateFlush, bufferSize, policy, strategy, advertiseURI, layout,
            filePermissions, fileOwner, fileGroup, configuration), FACTORY));
}
 
Example #23
Source File: TerminalConsoleAppender.java    From TerminalConsoleAppender with 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 #24
Source File: JSwingAppender.java    From collect-earth with 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 #25
Source File: LogstashIT.java    From logging-log4j2 with 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 #26
Source File: TextAreaAppender.java    From ModPackDownloader with 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);
}
 
Example #27
Source File: KafkaAppender.java    From logging-log4j2 with 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 #28
Source File: RandomAccessFileManager.java    From logging-log4j2 with 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 #29
Source File: BaseService.java    From support-diagnostics with 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 #30
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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();
}