org.apache.logging.log4j.core.appender.FileAppender Java Examples

The following examples show how to use org.apache.logging.log4j.core.appender.FileAppender. 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: 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 #2
Source File: CustomLevelsWithFiltersTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfiguration() {
    final Configuration configuration = context.getConfiguration();
    assertNotNull(configuration);
    final FileAppender appender = configuration.getAppender("info");
    assertNotNull(appender);
    final CompositeFilter compFilter = (CompositeFilter) appender.getFilter();
    assertNotNull(compFilter);
    final Filter[] filters = compFilter.getFiltersArray();
    assertNotNull(filters);
    boolean foundLevel = false;
    for (final Filter filter : filters) {
        final ThresholdFilter tFilter = (ThresholdFilter) filter;
        if (infom1Level.equals(tFilter.getLevel())) {
            foundLevel = true;
            break;
        }
    }
    Assert.assertTrue("Level not found: " + infom1Level, foundLevel);
}
 
Example #3
Source File: Main.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private static void addFileAppender(String logFilename) throws IOException {
  File logFile = new File(logFilename);
  Object ctx = LogManager.getContext(false);
  if (ctx instanceof LoggerContext) {
    try (LoggerContext context = (LoggerContext) ctx) {
      Configuration configuration = context.getConfiguration();
      LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
      FileAppender fileAppender =
          FileAppender.newBuilder()
              .setName("file")
              .setLayout(
                  PatternLayout.newBuilder()
                      .withPattern("[%d][%-5.-5p][%-14.-14c{1}:%4L] %-22.-22M - %m%n")
                      .build())
              .withFileName(logFile.getCanonicalPath())
              .build();
      configuration.addAppender(fileAppender);
      loggerConfig.addAppender(fileAppender, Level.ERROR, null);
      context.updateLoggers();
    }
  }
}
 
Example #4
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 #5
Source File: Log4j2LoggerAdapter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4j2LoggerAdapter() {
    try {
        org.apache.logging.log4j.Logger logger = LogManager.getLogger();
        if (logger != null) {
            Map<String, Appender> appenderMap =
                    ((org.apache.logging.log4j.core.Logger) logger).getAppenders();
            for (Map.Entry<String, Appender> entry : appenderMap.entrySet()) {
                if (entry.getValue() instanceof FileAppender) {
                    String filename = ((FileAppender) entry.getValue()).getFileName();
                    file = new File(filename);
                    break;
                }
            }
        }
    } catch (Throwable t) {
    }
}
 
Example #6
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 #7
Source File: MyServiceUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testProgrammaticConfig() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();

    PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build();

    Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build();
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null);
    AppenderRef[] refs = new AppenderRef[] { ref };

    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null);

    loggerConfig.addAppender(appender, null, null);
    config.addLogger("programmaticLogger", loggerConfig);
    ctx.updateLoggers();

    Logger pLogger = LogManager.getLogger("programmaticLogger");
    pLogger.info("Programmatic Logger Message");
}
 
Example #8
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
private Appender getAppender(LogConfig abyLogConfig, Configuration config, Appender appenderCfg) {
    Appender appender = null;
    if (appenderCfg instanceof RollingFileAppender) {
        RollingFileAppender rollingFileAppender = (RollingFileAppender) appenderCfg;
        appender = RollingFileAppender.newBuilder()
                .setConfiguration(config)
                .withName(appenderCfg.getName().replace(abyLogConfig.getAppenderNameKey(), abyLogConfig.getName()))
                .withFileName(rollingFileAppender.getFileName().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName()))
                .withFilePattern(rollingFileAppender.getFilePattern().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName()))
                .withLayout(rollingFileAppender.getLayout())
                .withFilter(rollingFileAppender.getFilter())
                .withPolicy(rollingFileAppender.getTriggeringPolicy())
                .withStrategy(rollingFileAppender.getManager().getRolloverStrategy())
                .build();
    } else if (appenderCfg instanceof FileAppender) {
        FileAppender fileAppender = (FileAppender) appenderCfg;
        appender = FileAppender.newBuilder()
                .setConfiguration(config)
                .withName(appenderCfg.getName().replace(abyLogConfig.getAppenderNameKey(), abyLogConfig.getName()))
                .withFileName(fileAppender.getFileName().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName()))
                .withLayout(fileAppender.getLayout())
                .withFilter(fileAppender.getFilter())
                .build();
    } else {
        LogManager.getLogger(LogFactory.class).warn("unsupported appender type ,appender type not in(RollingFileAppender,ConsoleAppender,FileAppender)", appenderCfg.getClass());
    }
    if (appender != null) {
        if (!appender.isStarted()) {
            appender.start();
        }
        config.addAppender(appender);
    }
    return appender;
}
 
Example #9
Source File: CompositeConfigurationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void compositeLogger() {
    final LoggerContextRule lcr = new LoggerContextRule("classpath:log4j-comp-logger.xml,log4j-comp-logger.json");
    final Statement test = new Statement() {
        @Override
        public void evaluate() throws Throwable {
            final CompositeConfiguration config = (CompositeConfiguration) lcr.getConfiguration();
            Map<String, Appender> appendersMap = config.getLogger("cat1").getAppenders();
            assertEquals("Expected 2 Appender references for cat1 but got " + appendersMap.size(), 2,
                    appendersMap.size());
            assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender);

            Filter loggerFilter = config.getLogger("cat1").getFilter();
            assertTrue(loggerFilter instanceof RegexFilter);
            assertEquals(loggerFilter.getOnMatch(), Filter.Result.DENY);

            appendersMap = config.getLogger("cat2").getAppenders();
            assertEquals("Expected 1 Appender reference for cat2 but got " + appendersMap.size(), 1,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);

            appendersMap = config.getLogger("cat3").getAppenders();
            assertEquals("Expected 1 Appender reference for cat3 but got " + appendersMap.size(), 1,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);

            appendersMap = config.getRootLogger().getAppenders();
            assertEquals("Expected 2 Appender references for the root logger but got " + appendersMap.size(), 2,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);
            assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender);

            assertEquals("Expected COMPOSITE_SOURCE for composite configuration but got " + config.getConfigurationSource(),
                    config.getConfigurationSource(), ConfigurationSource.COMPOSITE_SOURCE);
        }
    };
    runTest(lcr, test);
}
 
Example #10
Source File: WebLookupTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLookup2() throws Exception {
    ContextAnchor.THREAD_CONTEXT.remove();
    final ServletContext servletContext = new MockServletContext();
    ((MockServletContext) servletContext).setContextPath("/");
    servletContext.setAttribute("TestAttr", "AttrValue");
    servletContext.setInitParameter("myapp.logdir", "target");
    servletContext.setAttribute("Name1", "Ben");
    servletContext.setInitParameter("Name2", "Jerry");
    servletContext.setInitParameter("log4jConfiguration", "WEB-INF/classes/log4j-webvar.xml");
    final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);
    initializer.start();
    initializer.setLoggerContext();
    final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
    assertNotNull("No LoggerContext", ctx);
    assertNotNull("No ServletContext", ctx.getExternalContext());
    final Configuration config = ctx.getConfiguration();
    assertNotNull("No Configuration", config);
    final Map<String, Appender> appenders = config.getAppenders();
    for (final Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("file")) {
            final FileAppender fa = (FileAppender) entry.getValue();
            assertEquals("target/myapp.log", fa.getFileName());
        }
    }
    final StrSubstitutor substitutor = config.getStrSubstitutor();
    String value = substitutor.replace("${web:contextPathName:-default}");
    assertNotNull("No value for context name", value);
    assertEquals("Incorrect value for context name", "default", value);
    initializer.stop();
    ContextAnchor.THREAD_CONTEXT.remove();
}
 
Example #11
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 #12
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 #13
Source File: FileAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Appender createAppender(final String name, final Log4j1Configuration configuration, final Layout layout,
        final Filter filter, final String fileName, String level, boolean immediateFlush, final boolean append,
        final boolean bufferedIo, final int bufferSize) {
    org.apache.logging.log4j.core.Layout<?> fileLayout = null;
    if (bufferedIo) {
        immediateFlush = true;
    }
    if (layout instanceof LayoutWrapper) {
        fileLayout = ((LayoutWrapper) layout).getLayout();
    } else if (layout != null) {
        fileLayout = new LayoutAdapter(layout);
    }
    org.apache.logging.log4j.core.Filter fileFilter = buildFilters(level, filter);
    if (fileName == null) {
        LOGGER.warn("Unable to create File Appender, no file name provided");
        return null;
    }
    return new AppenderWrapper(FileAppender.newBuilder()
            .setName(name)
            .setConfiguration(configuration)
            .setLayout(fileLayout)
            .setFilter(fileFilter)
            .setFileName(fileName)
            .setImmediateFlush(immediateFlush)
            .setAppend(append)
            .setBufferedIo(bufferedIo)
            .setBufferSize(bufferSize)
            .build());
}
 
Example #14
Source File: AgentLogManagerLog4j2Impl.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param context the log4j2 logger context
 */
public AgentLogManagerLog4j2Impl(final LoggerContext context) {
    final FileAppender logFileAppender = context.getConfiguration().getAppender(AGENT_LOG_FILE_APPENDER_NAME);
    final String filename = logFileAppender.getFileName();
    if (StringUtils.isBlank(filename)) {
        throw new IllegalStateException("Could not determine location of agent log file");
    }
    this.logFilePath.set(Paths.get(filename));
    ConsoleLog.getLogger().info("Agent (temporarily) logging to: {}", filename);
}
 
Example #15
Source File: MyXMLConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected void doConfigure() {
    super.doConfigure();
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig("com");
    final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null);
    Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config);
    loggerConfig.addAppender(appender, Level.DEBUG, null);
    addAppender(appender);
}
 
Example #16
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 #17
Source File: LogUtil.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
public static void appendFileLogger(Level level, String name, Path filePath) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout("%d{HH:mm} [%-5p] %msg%n", null, config, null, null, true, false, null, null);

    Appender appender = FileAppender.createAppender(filePath.toFile().getAbsolutePath(), "true", "false", name, "true",
            "false", "false", "8192", layout, null, "false", null, config);
    appender.start();

    config.getRootLogger().addAppender(appender, level, null);
    ctx.updateLoggers();
}
 
Example #18
Source File: TestFileRewriteAuditAppender.java    From syncope with Apache License 2.0 5 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 = 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 #19
Source File: Log4J2Logger.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Nullable @Override public String fileName() {
    for (Logger log = impl; log != null; log = log.getParent()) {
        for (Appender a : log.getAppenders().values()) {
            if (a instanceof FileAppender)
                return ((FileAppender)a).getFileName();

            if (a instanceof RollingFileAppender)
                return ((RollingFileAppender)a).getFileName();

            if (a instanceof RoutingAppender) {
                try {
                    RoutingAppender routing = (RoutingAppender)a;

                    Field appsFiled = routing.getClass().getDeclaredField("appenders");

                    appsFiled.setAccessible(true);

                    Map<String, AppenderControl> appenders = (Map<String, AppenderControl>)appsFiled.get(routing);

                    for (AppenderControl control : appenders.values()) {
                        Appender innerApp = control.getAppender();

                        if (innerApp instanceof FileAppender)
                            return normalize(((FileAppender)innerApp).getFileName());

                        if (innerApp instanceof RollingFileAppender)
                            return normalize(((RollingFileAppender)innerApp).getFileName());
                    }
                }
                catch (IllegalAccessException | NoSuchFieldException e) {
                    error("Failed to get file name (was the implementation of log4j2 changed?).", e);
                }
            }
        }
    }

    return null;
}
 
Example #20
Source File: LogConfiguration.java    From wekaDeeplearning4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Apply the logging configuration.
 */
public void apply() {
  LoggerContext context = getLoggerContext();
  Configuration config = context.getConfiguration();
  ConfigurationSource configSource = config.getConfigurationSource();
  String packageHomeDir = WekaPackageManager.getPackageHome().getPath();
  if (ConfigurationSource.NULL_SOURCE.equals(configSource)) {
    // Use log4j2.xml shipped with the package ...
    URI uri = Paths.get(packageHomeDir, "wekaDeeplearning4j", "src", "main", "resources",
        "log4j2.xml").toUri();
    context.setConfigLocation(uri);
    log.info("Logging configuration loaded from source: {}", uri.toString());
  }

  String fileAppenderName = "fileAppender";
  if (!context.getRootLogger().getAppenders().containsKey(fileAppenderName)) {
    // Get console appender layout
    Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console");
    Layout<? extends Serializable> layout = consoleAppender.getLayout();

    // Add file appender
    String filePath = resolveLogFilePath();
    FileAppender.Builder appenderBuilder = new FileAppender.Builder();
    appenderBuilder.withFileName(filePath);
    appenderBuilder.withAppend(append);
    appenderBuilder.withName(fileAppenderName);
    appenderBuilder.withLayout(layout);
    FileAppender appender = appenderBuilder.build();
    appender.start();
    context.getRootLogger().addAppender(appender);
  }
}
 
Example #21
Source File: LogConfiguration.java    From wekaDeeplearning4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Apply the logging configuration.
 */
public void apply() {
  LoggerContext context = getLoggerContext();
  Configuration config = context.getConfiguration();
  ConfigurationSource configSource = config.getConfigurationSource();
  String packageHomeDir = WekaPackageManager.getPackageHome().getPath();
  if (ConfigurationSource.NULL_SOURCE.equals(configSource)) {
    // Use log4j2.xml shipped with the package ...
    URI uri = Paths.get(packageHomeDir, "wekaDeeplearning4j", "src", "main", "resources",
        "log4j2.xml").toUri();
    context.setConfigLocation(uri);
    log.info("Logging configuration loaded from source: {}", uri.toString());
  }

  String fileAppenderName = "fileAppender";
  if (!context.getRootLogger().getAppenders().containsKey(fileAppenderName)) {
    // Get console appender layout
    Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console");
    Layout<? extends Serializable> layout = consoleAppender.getLayout();

    // Add file appender
    String filePath = resolveLogFilePath();
    FileAppender.Builder appenderBuilder = new FileAppender.Builder();
    appenderBuilder.withFileName(filePath);
    appenderBuilder.withAppend(append);
    appenderBuilder.withName(fileAppenderName);
    appenderBuilder.withLayout(layout);
    FileAppender appender = appenderBuilder.build();
    appender.start();
    context.getRootLogger().addAppender(appender);
  }
}
 
Example #22
Source File: Log4j2Helper.java    From arthas with Apache License 2.0 5 votes vote down vote up
private static List<Map<String, Object>> doGetLoggerAppenders(LoggerConfig loggerConfig) {
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    Map<String, Appender> appenders = loggerConfig.getAppenders();

    for (Entry<String, Appender> entry : appenders.entrySet()) {
        Map<String, Object> info = new HashMap<String, Object>();
        Appender appender = entry.getValue();
        info.put(LoggerHelper.name, appender.getName());
        info.put(LoggerHelper.clazz, appender.getClass());

        result.add(info);
        if (appender instanceof FileAppender) {
            info.put(LoggerHelper.file, ((FileAppender) appender).getFileName());
        } else if (appender instanceof ConsoleAppender) {
            info.put(LoggerHelper.target, ((ConsoleAppender) appender).getTarget());
        } else if (appender instanceof AsyncAppender) {

            AsyncAppender asyncAppender = ((AsyncAppender) appender);
            String[] appenderRefStrings = asyncAppender.getAppenderRefStrings();

            info.put(LoggerHelper.blocking, asyncAppender.isBlocking());
            info.put(LoggerHelper.appenderRef, Arrays.asList(appenderRefStrings));
        }
    }
    return result;
}
 
Example #23
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
private Appender getAppender(String clKey, Configuration config, Appender appenderCfg) {
    Appender appender = null;
    if (appenderCfg instanceof RollingFileAppender) {
        RollingFileAppender rollingFileAppender = (RollingFileAppender) appenderCfg;
        appender = RollingFileAppender.newBuilder()
                .setConfiguration(config)
                .withName(clKey)
                .withFileName(rollingFileAppender.getFileName())
                .withFilePattern(rollingFileAppender.getFilePattern())
                .withLayout(rollingFileAppender.getLayout())
                .withFilter(rollingFileAppender.getFilter())
                .withPolicy(rollingFileAppender.getTriggeringPolicy())
                .withStrategy(rollingFileAppender.getManager().getRolloverStrategy())
                .build();
    } else if (appenderCfg instanceof FileAppender) {
        FileAppender fileAppender = (FileAppender) appenderCfg;
        appender = FileAppender.newBuilder()
                .setConfiguration(config)
                .withName(appenderCfg.getName())
                .withFileName(fileAppender.getFileName())
                .withLayout(fileAppender.getLayout())
                .withFilter(fileAppender.getFilter())
                .build();
    } else {
        LogManager.getLogger(LogFactory.class).warn("unsupported appender type ,appender type not in(RollingFileAppender,ConsoleAppender,FileAppender)", appenderCfg.getClass());
    }
    if (appender != null) {
        config.addAppender(appender);
    }
    return appender;
}
 
Example #24
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void buildFileAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, FileAppender.PLUGIN_NAME);
    buildFileAppender(appenderName, appenderBuilder);
    builder.add(appenderBuilder);
}
 
Example #25
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void buildFileAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, FileAppender.PLUGIN_NAME);
    buildFileAppender(appenderName, appenderBuilder);
    builder.add(appenderBuilder);
}
 
Example #26
Source File: Log4j2HookProxy.java    From uavstack with Apache License 2.0 4 votes vote down vote up
private LogProfileInfo getAppenderInfo(Appender appender, String appid) {
    
    if(appender == null) {
        return null;
    }
    
    String fileName;
    if (appender instanceof FileAppender) {
        fileName = ((FileAppender) appender).getFileName();
    }
    else if (appender instanceof RollingFileAppender) {
        fileName = ((RollingFileAppender) appender).getFileName();
    }
    else if (appender instanceof RollingRandomAccessFileAppender) {
        fileName = ((RollingRandomAccessFileAppender) appender).getFileName();
    }
    else if (appender instanceof RandomAccessFileAppender) {
        fileName = ((RandomAccessFileAppender) appender).getFileName();
    }
    else if (appender instanceof MemoryMappedFileAppender) {
        fileName = ((MemoryMappedFileAppender) appender).getFileName();
    }
    else {
        return null;
    }

    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put(LogProfileInfo.ENGINE, "log4j2");
    Layout<?> layout = appender.getLayout();
    if (null != layout) {
        if (layout instanceof PatternLayout) {
            attributes.put(LogProfileInfo.PATTERN, ((PatternLayout) layout).getConversionPattern());
        }
        else {
            attributes.put(LogProfileInfo.PATTERN, layout.getClass().getSimpleName());
        }
    }

    LogProfileInfo logProfileInfo = new LogProfileInfo();
    logProfileInfo.setAppId(appid);
    logProfileInfo.setFilePath(fileName);
    logProfileInfo.setAttributes(attributes);
    logProfileInfo.setLogType(LogProfileInfo.LogType.Log4j);

    return logProfileInfo;
}
 
Example #27
Source File: CustomConfigurationTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testConfig() {
    // don't bother using "error" since that's the default; try another level
    final LoggerContext ctx = this.init.getLoggerContext();
    ctx.reconfigure();
    final Configuration config = ctx.getConfiguration();
    assertThat(config, instanceOf(XmlConfiguration.class));
    for (final StatusListener listener : StatusLogger.getLogger().getListeners()) {
        if (listener instanceof StatusConsoleListener) {
            assertSame(listener.getStatusLevel(), Level.INFO);
            break;
        }
    }
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
        .setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
        .setConfiguration(config)
        .build();
    // @formatter:off
    final FileAppender appender = FileAppender.newBuilder()
        .setFileName(LOG_FILE)
        .setAppend(false)
        .setName("File")
        .setIgnoreExceptions(false)
        .setBufferSize(4000)
        .setBufferedIo(false)
        .setLayout(layout)
        .build();
    // @formatter:on
    appender.start();
    config.addAppender(appender);
    final AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
    final AppenderRef[] refs = new AppenderRef[] {ref};

    final LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "org.apache.logging.log4j",
        "true", refs, null, config, null );
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("org.apache.logging.log4j", loggerConfig);
    ctx.updateLoggers();
    final Logger logger = ctx.getLogger(CustomConfigurationTest.class.getName());
    logger.info("This is a test");
    final File file = new File(LOG_FILE);
    assertThat(file, exists());
    assertThat(file, hasLength(greaterThan(0L)));
}
 
Example #28
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testRefreshDeprecatedApis() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	PatternLayout layout = PatternLayout.newBuilder()
	        .setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
	        .setPatternSelector(null)
	        .setConfiguration(config)
	        .setRegexReplacement(null)
	        .setCharset(null)
	        .setAlwaysWriteExceptions(false)
	        .setNoConsoleNoAnsi(false)
	        .setHeader(null)
	        .setFooter(null)
	        .build();
	// @formatter:off
	Appender appender = FileAppender.newBuilder()
	        .setFileName("target/test.log")
	        .setAppend(false)
	        .setLocking(false)
	        .setName("File")
	        .setImmediateFlush(true)
	        .setIgnoreExceptions(false)
	        .setBufferedIo(false)
	        .setBufferSize(4000)
	        .setLayout(layout)
	        .setAdvertise(false)
	        .setConfiguration(config)
	        .build();
       // @formatter:on
	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 #29
Source File: ExecutorLoggerFactory.java    From liteflow with Apache License 2.0 4 votes vote down vote up
/**
 * 创建并启动一个的logger
 */
private static void start(String loggerName, String logPath) {
    /**
     * 设置layout
     */
    Layout layout = PatternLayout
            .newBuilder()
            .withConfiguration(config)
            .withPattern(LAYOUT_TEMPLATE)
            .build();

    String fileName = logPath;
    /**
     * 设置appender
     */
    FileAppender fileAppender = FileAppender.newBuilder()
            .withName(loggerName)
            .withFileName(fileName)
            .withLayout(layout)
            .build();

    AppenderRef appenderRef = AppenderRef.createAppenderRef(APPRENDER_REF, APPRENDER_LEVEL, APPRENDER_FILTER);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(
            LOGGER_ADDITIVITY,
            Level.ALL,
            loggerName,
            LOGGER_INCLUDE_LOCATIOIN,
            new AppenderRef[] {appenderRef},
            LOGGER_PROPERTY,
            config,
            APPRENDER_FILTER
    );
    loggerConfig.addAppender(fileAppender, APPRENDER_LEVEL, APPRENDER_FILTER);
    /**
     * 添加appender
     */
    config.addLogger(loggerName, loggerConfig);
    ctx.updateLoggers();
    LOG.info("create logger {}, path is {}", loggerName, logPath);
    /**
     * start
     */
    loggerConfig.start();
}
 
Example #30
Source File: LoggerDateTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
    fileApp = context.getRequiredAppender("File", FileAppender.class);
}