org.apache.logging.log4j.core.config.AppenderRef Java Examples

The following examples show how to use org.apache.logging.log4j.core.config.AppenderRef. 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: Log4j2Util.java    From summerframework with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private static void createAppenderAndStart(String loggerName, String fileName, String filePattern) {

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

    String loggerDir = datalogDir + File.separator;

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

    AppenderRef ref = AppenderRef.createAppenderRef(loggerName, Level.INFO, null);
    AppenderRef[] refs = new AppenderRef[] {ref};
    LoggerConfig loggerConfig =
        LoggerConfig.createLogger(false, Level.ALL, loggerName, "true", refs, null, config, null);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger(loggerName, loggerConfig);
    ctx.updateLoggers();
}
 
Example #2
Source File: Main.java    From homework_tester with MIT License 7 votes vote down vote up
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

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

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
 
Example #3
Source File: LoggerUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * This method loads the required properties into log4j for the logger
 * </p>
 * 
 * @param logFileDir
 *            Log file directory
 * @param taskAttemptID
 *            The task attempt id
 * 
 * @throws IOException
 *             If any error occurs
 * @throws URISyntaxException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerException
 */
public static void loadLogger(String logFileDir, String taskAttemptID) throws IOException, URISyntaxException, ParserConfigurationException,
		SAXException, TransformerException {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    ctx.reconfigure();
       Configuration config = ctx.getConfiguration();
       MemoryMappedFileAppender memoryMappedfileAppender = createMemoryMappedFileAppender(config, LOG_APPENDER_NAME + taskAttemptID, logFileDir, taskAttemptID, 0);
       memoryMappedfileAppender.start();
    AppenderRef[] ar = new AppenderRef [1];
       ar[0] = AppenderRef.createAppenderRef(LOG_APPENDER_NAME + taskAttemptID , Level.INFO, null);
       LoggerConfig lgf = LoggerConfig.createLogger("false",Level.INFO , LOG_CATEGORY + taskAttemptID , null, ar, null, config, null);
       config.addLogger(LOG_CATEGORY + taskAttemptID, lgf);
       ctx.getLogger(LOG_CATEGORY + taskAttemptID).addAppender(memoryMappedfileAppender);
       ctx.updateLoggers();
       ctx.start();
	mapReduceLoggers = new ArrayList<Logger>(1);
	mapReduceLoggers.add(LogManager.getLogger(LOG_CATEGORY + taskAttemptID));
	LOG.debug("Finished loading logger");

}
 
Example #4
Source File: ValidatingPluginWithFailoverTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    final PluginManager manager = new PluginManager(Core.CATEGORY_NAME);
    manager.collectPlugins();
    plugin = (PluginType<FailoverAppender>) manager.getPluginType("failover");
    assertNotNull("Rebuild this module to make sure annotation processing kicks in.", plugin);

    AppenderRef appenderRef = AppenderRef.createAppenderRef("List", Level.ALL, null);
    node = new Node(null, "failover", plugin);
    Node failoversNode = new Node(node, "Failovers", manager.getPluginType("Failovers"));
    Node appenderRefNode  = new Node(failoversNode, "appenderRef", manager.getPluginType("appenderRef"));
    appenderRefNode.getAttributes().put("ref", "file");
    appenderRefNode.setObject(appenderRef);
    failoversNode.getChildren().add(appenderRefNode);
    failoversNode.setObject(FailoversPlugin.createFailovers(appenderRef));
    node.getAttributes().put("primary", "CONSOLE");
    node.getAttributes().put("name", "Failover");
    node.getChildren().add(failoversNode);
}
 
Example #5
Source File: Log4j2Configuration.java    From summerframework with Apache License 2.0 6 votes vote down vote up
private void createBizLogger() {
    if (env.containsProperty(MonitorConfigSpringApplicationRunListener.LOG_KAFKA_BOOTSTRAPSERVERS)) {
        String appenderName = "AdvancedKafkaAppender";
        LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
        Configuration configuration = loggerContext.getConfiguration();
        AdvancedKafkaAppender kafkaAppender =
            AdvancedKafkaAppender.createAppender(CustomJsonLayout.createDefaultLayout(), null, configuration,
                appenderName, getKafkaTopic(), getBootstrapservers());
        kafkaAppender.start();
        AppenderRef ref = AppenderRef.createAppenderRef(appenderName, null, null);
        AppenderRef[] refs = new AppenderRef[] {ref};
        LoggerConfig loggerConfig =
            LoggerConfig.createLogger(false, Level.INFO, "BizLogger", null, refs, null, configuration, null);
        loggerConfig.addAppender(kafkaAppender, null, null);
        configuration.addLogger("BizLogger", loggerConfig);
    }
}
 
Example #6
Source File: AsyncLoggerConfig.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * @since 3.0
 */
@PluginFactory
public static LoggerConfig createLogger(
        @PluginAttribute final String additivity,
        @PluginAttribute final Level level,
        @PluginAttribute final String includeLocation,
        @PluginElement final AppenderRef[] refs,
        @PluginElement final Property[] properties,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter) {
    final List<AppenderRef> appenderRefs = Arrays.asList(refs);
    final Level actualLevel = level == null ? Level.ERROR : level;
    final boolean additive = Booleans.parseBoolean(additivity, true);
    return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
            properties, config, AsyncLoggerConfig.includeLocation(includeLocation));
}
 
Example #7
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Captures the given logger at the given level so it can be displayed directly by this controller.
 *
 * @param name the name
 * @param level the level
 * @param append the append
 * @return the response entity
 */
@RequestMapping(value = "capture/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> capture(@PathVariable("name")
final String name, @PathVariable("level")
final Level level, @RequestParam(value = "append", defaultValue = "false") boolean append) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        if (inMemoryAppenderImpl != null) {
            final Configuration config = ctx.getConfiguration();
            //
            if (name.equalsIgnoreCase(config.getLoggerConfig(name).getName())) {
                config.removeLogger(name);
            }
            //
            AppenderRef ref = AppenderRef.createAppenderRef("InMemoryAppenderImplAppenderRef", level, null);
            AppenderRef[] refs = new AppenderRef[] {ref};
            LoggerConfig loggerConfig = LoggerConfig.createLogger(append, level, name, "true", refs, null, config, null);
            loggerConfig.addAppender(inMemoryAppenderImpl, null, null);
            config.addLogger(name, loggerConfig);
            ctx.updateLoggers();
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example #8
Source File: DeobfuscatingRewritePolicy.java    From VanillaFix with MIT License 6 votes vote down vote up
/** Modifies the log4j config to add the policy **/
public static void install() {
    Logger rootLogger = (Logger) LogManager.getRootLogger();
    LoggerConfig loggerConfig = rootLogger.get();

    // Remove appender refs from config
    List<AppenderRef> appenderRefs = new ArrayList<>(loggerConfig.getAppenderRefs());
    for (AppenderRef appenderRef : appenderRefs) {
        loggerConfig.removeAppender(appenderRef.getRef());
    }

    // Create the RewriteAppender, which wraps the appenders
    RewriteAppender rewriteAppender = RewriteAppender.createAppender(
            "VanillaFixDeobfuscatingAppender",
            "true",
            appenderRefs.toArray(new AppenderRef[0]),
            rootLogger.getContext().getConfiguration(),
            new DeobfuscatingRewritePolicy(),
            null
    );
    rewriteAppender.start();

    // Add the new appender
    loggerConfig.addAppender(rewriteAppender, null, null);
}
 
Example #9
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 #10
Source File: AsyncAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private <T extends Log4j1Configuration> Appender createAppender(String name, String level,
        String[] appenderRefs, boolean blocking, int bufferSize, boolean includeLocation,
        T configuration) {
    org.apache.logging.log4j.Level logLevel = OptionConverter.convertLevel(level,
            org.apache.logging.log4j.Level.TRACE);
    AppenderRef[] refs = new AppenderRef[appenderRefs.length];
    int index = 0;
    for (String appenderRef : appenderRefs) {
        refs[index++] = AppenderRef.createAppenderRef(appenderRef, logLevel, null);
    }
    return new AppenderWrapper(AsyncAppender.newBuilder()
            .setName(name)
            .setAppenderRefs(refs)
            .setBlocking(blocking)
            .setBufferSize(bufferSize)
            .setIncludeLocation(includeLocation)
            .setConfiguration(configuration)
            .build());
}
 
Example #11
Source File: Main.java    From homework_tester with MIT License 6 votes vote down vote up
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

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

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
 
Example #12
Source File: RewriteAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private <T extends Log4j1Configuration> Appender createAppender(String name, String level,
        String[] appenderRefs, RewritePolicy policy, Filter filter, T configuration) {
    org.apache.logging.log4j.Level logLevel = OptionConverter.convertLevel(level,
            org.apache.logging.log4j.Level.TRACE);
    AppenderRef[] refs = new AppenderRef[appenderRefs.length];
    int index = 0;
    for (String appenderRef : appenderRefs) {
        refs[index++] = AppenderRef.createAppenderRef(appenderRef, logLevel, null);
    }
    org.apache.logging.log4j.core.Filter rewriteFilter = buildFilters(level, filter);
    org.apache.logging.log4j.core.appender.rewrite.RewritePolicy rewritePolicy;
    if (policy instanceof RewritePolicyWrapper) {
        rewritePolicy = ((RewritePolicyWrapper) policy).getPolicy();
    } else {
        rewritePolicy = new RewritePolicyAdapter(policy);
    }
    return new AppenderWrapper(RewriteAppender.createAppender(name, true, refs, configuration,
            rewritePolicy, rewriteFilter));
}
 
Example #13
Source File: Log4JLogConfigInitializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Configures rolling file loggers.
 *
 * @param filename the filename to output logging to.
 * @param loggers the logger names.
 */
private void configureLoggers( String filename, List<String> loggers )
{
    String file = getLogFile( filename );

    RollingFileAppender appender = getRollingFileAppender( file );

    getLogConfiguration().addAppender( appender );

    AppenderRef[] refs = createAppenderRef( "Ref_" + filename );

    for ( String loggerName : loggers )
    {
        LoggerConfig loggerConfig = LoggerConfig.createLogger( true, Level.INFO, loggerName, "true", refs, null,
            getLogConfiguration(), null );

        loggerConfig.addAppender(appender, null, null);

        getLogConfiguration().addLogger(loggerName, loggerConfig);

        log.info( "Added logger: " + loggerName + " using file: " + file );
    }
}
 
Example #14
Source File: RewriteAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    for (final AppenderRef ref : appenderRefs) {
        final String name = ref.getRef();
        final Appender appender = config.getAppender(name);
        if (appender != null) {
            final Filter filter = appender instanceof AbstractAppender ?
                ((AbstractAppender) appender).getFilter() : null;
            appenders.put(name, new AppenderControl(appender, ref.getLevel(), filter));
        } else {
            LOGGER.error("Appender " + ref + " cannot be located. Reference ignored");
        }
    }
    super.start();
}
 
Example #15
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 #16
Source File: LoggerConfigAdmin.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getAppenderRefs() {
    final List<AppenderRef> refs = loggerConfig.getAppenderRefs();
    final String[] result = new String[refs.size()];
    for (int i = 0; i < result.length; i++) {
        result[i] = refs.get(i).getRef();
    }
    return result;
}
 
Example #17
Source File: AsyncAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private AsyncAppender(final String name, final Filter filter, final AppenderRef[] appenderRefs,
        final String errorRef, final int queueSize, final boolean blocking, final boolean ignoreExceptions,
        final long shutdownTimeout, final Configuration config, final boolean includeLocation,
        final BlockingQueueFactory<LogEvent> blockingQueueFactory, Property[] properties) {
    super(name, filter, null, ignoreExceptions, properties);
    this.queue = blockingQueueFactory.create(queueSize);
    this.queueSize = queueSize;
    this.blocking = blocking;
    this.shutdownTimeout = shutdownTimeout;
    this.config = config;
    this.appenderRefs = appenderRefs;
    this.errorRef = errorRef;
    this.includeLocation = includeLocation;
}
 
Example #18
Source File: RewriteAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private RewriteAppender(final String name, final Filter filter, final boolean ignoreExceptions,
                        final AppenderRef[] appenderRefs, final RewritePolicy rewritePolicy,
                        final Configuration config, Property[] properties) {
    super(name, filter, null, ignoreExceptions, properties);
    this.config = config;
    this.rewritePolicy = rewritePolicy;
    this.appenderRefs = appenderRefs;
}
 
Example #19
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
public void start(LogConfig abyLogConfig) {
    //为false时,返回多个LoggerContext对象, true:返回唯一的单例LoggerContext
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    org.apache.logging.log4j.core.Logger cfgLogger = (org.apache.logging.log4j.core.Logger) LogManager.getLogger(abyLogConfig.getCfgLogName());
    if (cfgLogger == null) {
        LogManager.getLogger(LogFactory.class).error("not found {} logger (please define in log4j2.xml)", abyLogConfig.getCfgLogName());
        return;
    }

    List<AppenderRef> appenderRefs = new ArrayList<>();
    Map<String, Appender> appenderMap = cfgLogger.getAppenders();
    List<Appender> appenders = new ArrayList<>();
    appenderMap.forEach((key, appenderCfg) -> {
        Appender appender;
        if (appenderCfg instanceof ConsoleAppender) {
            appender = appenderCfg;
        } else {
            appender = getAppender(abyLogConfig, config, appenderCfg);
        }

        if (appender != null) {
            AppenderRef ref = AppenderRef.createAppenderRef(appender.getName(), Level.ALL, null);
            appenderRefs.add(ref);
            appenders.add(appender);
        }
    });
    if (CollectionUtils.isEmpty(appenders)) {
        return;
    }
    AppenderRef[] refs = new AppenderRef[appenderRefs.size()];
    refs = appenderRefs.toArray(refs);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, cfgLogger.getLevel(), abyLogConfig.getName(),
            "true", refs, null, config, null);
    appenders.stream().forEach(e ->
            loggerConfig.addAppender(e, Level.ALL, null)
    );
    config.addLogger(abyLogConfig.getName(), loggerConfig);
    ctx.updateLoggers(config);
}
 
Example #20
Source File: FailoversPlugin.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the appender references.
 * @param refs The references to return.
 * @return The appender references.
 */
@PluginFactory
public static String[] createFailovers(@PluginElement("AppenderRef") final AppenderRef... refs) {

    if (refs == null) {
        LOGGER.error("failovers must contain an appender reference");
        return null;
    }
    final String[] arr = new String[refs.length];
    for (int i = 0; i < refs.length; ++i) {
        arr[i] = refs[i].getRef();
    }
    return arr;
}
 
Example #21
Source File: AsyncLoggerConfig.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected AsyncLoggerConfig(final String name,
        final List<AppenderRef> appenders, final Filter filter,
        final Level level, final boolean additive,
        final Property[] properties, final Configuration config,
        final boolean includeLocation) {
    super(name, appenders, filter, level, additive, properties, config,
            includeLocation);
    delegate = config.getAsyncLoggerConfigDelegate();
    delegate.setLogEventFactory(getLogEventFactory());
}
 
Example #22
Source File: AsyncLoggerConfig.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method to create a LoggerConfig.
 *
 * @param additivity True if additive, false otherwise.
 * @param level The Level to be associated with the Logger.
 * @param loggerName The name of the Logger.
 * @param includeLocation "true" if location should be passed downstream
 * @param refs An array of Appender names.
 * @param properties Properties to pass to the Logger.
 * @param config The Configuration.
 * @param filter A Filter.
 * @return A new LoggerConfig.
 * @since 3.0
 */
@PluginFactory
public static LoggerConfig createLogger(
        @PluginAttribute(defaultBoolean = true) final boolean additivity,
        @PluginAttribute final Level level,
        @Required(message = "Loggers cannot be configured without a name") @PluginAttribute("name") final String loggerName,
        @PluginAttribute final String includeLocation,
        @PluginElement final AppenderRef[] refs,
        @PluginElement final Property[] properties,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter) {
    final String name = loggerName.equals(ROOT) ? Strings.EMPTY : loggerName;
    return new AsyncLoggerConfig(name, Arrays.asList(refs), filter, level, additivity, properties, config,
            includeLocation(includeLocation));
}
 
Example #23
Source File: AsyncLoggerConfigTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
   public void testIncludeLocationDefaultsToFalse() {
   	final LoggerConfig rootLoggerConfig =
   			AsyncLoggerConfig.RootLogger.createLogger(
   					null, Level.INFO, null, new AppenderRef[0], null, new DefaultConfiguration(), null);
assertFalse("Include location should default to false for async loggers",
   			    rootLoggerConfig.isIncludeLocation());

   	final LoggerConfig loggerConfig =
   	        AsyncLoggerConfig.createLogger(
   	                false, Level.INFO, "com.foo.Bar", null, new AppenderRef[0], null, new DefaultConfiguration(),
   	        		null);
assertFalse("Include location should default to false for async loggers",
   			    loggerConfig.isIncludeLocation());
   }
 
Example #24
Source File: TestLoggerResource.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
	loggingEvents = new ConcurrentLinkedQueue<>();

	Appender testAppender = new AbstractAppender("test-appender", null, null, false) {
		@Override
		public void append(LogEvent event) {
			loggingEvents.add(event.getMessage().getFormattedMessage());
		}
	};
	testAppender.start();

	AppenderRef appenderRef = AppenderRef.createAppenderRef(testAppender.getName(), null, null);
	LoggerConfig logger = LoggerConfig.createLogger(
		false,
		Level.getLevel(level.name()),
		"test",
		null,
		new AppenderRef[]{appenderRef},
		null,
		LOGGER_CONTEXT.getConfiguration(),
		null);
	logger.addAppender(testAppender, null, null);

	LOGGER_CONTEXT.getConfiguration().addLogger(loggerName, logger);
	LOGGER_CONTEXT.updateLoggers();
}
 
Example #25
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
public void start(Logger cfgLogger, String clKey) {
    //为false时,返回多个LoggerContext对象, true:返回唯一的单例LoggerContext
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    List<AppenderRef> appenderRefs = new ArrayList<>();
    Map<String, Appender> appenderMap = ((org.apache.logging.log4j.core.Logger) cfgLogger).getAppenders();
    List<Appender> appenders = new ArrayList<>();
    appenderMap.forEach((key, appenderCfg) -> {
        Appender appender;
        if (appenderCfg instanceof ConsoleAppender) {
            appender = appenderCfg;
        } else {
            appender = getAppender(clKey, config, appenderCfg);
        }
        if (appender != null && appender.isStopped()) {
            appender.start();
        }
        if (appender != null) {
            AppenderRef ref = AppenderRef.createAppenderRef(appender.getName(), Level.ALL, null);
            appenderRefs.add(ref);
            appenders.add(appender);
        }
    });
    if (CollectionUtils.isEmpty(appenders)) {
        return;
    }
    AppenderRef[] refs = new AppenderRef[appenderRefs.size()];
    refs = appenderRefs.toArray(refs);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, cfgLogger.getLevel(), clKey, "true", refs, null, config, null);
    appenders.stream().forEach(e ->
            loggerConfig.addAppender(e, Level.ALL, null)
    );
    config.addLogger(clKey, loggerConfig);
    ctx.updateLoggers(config);
}
 
Example #26
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
private LogResponse listLoggers(final LoggerContext ctx) {
    LogResponse logResponse = new LogResponse();
    List<LogSpecification> result = new ArrayList<>();
    logResponse.setSpecs(result);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        config.getLoggers().forEach(
            (name, configuration) -> result.add(new LogSpecification(StringUtils.hasText(name) ? name : "Root", configuration.getLevel().name(),
                configuration.getAppenderRefs().stream().map(AppenderRef::getRef).collect(Collectors.toList()))));
    }
    return logResponse;

}
 
Example #27
Source File: AppenderRefFailoverPolicyTest.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static  FailoverPolicy<String> createTestFailoverPolicy(String testAppenderRef, Configuration configuration) {
    AppenderRefFailoverPolicy.Builder builder = AppenderRefFailoverPolicy.newBuilder();
    builder.withAppenderRef(AppenderRef.createAppenderRef(
            testAppenderRef, Level.ALL, null));
    builder.withConfiguration(configuration);
    return builder.build();
}
 
Example #28
Source File: LogUtil.java    From fix-orchestra with Apache License 2.0 5 votes vote down vote up
public static Logger initializeDefaultLogger(Level level, Class<?> clazz) {
  final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  final Configuration config = ctx.getConfiguration();
  final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("Console").build();
  config.addAppender(appender);
  final AppenderRef ref = AppenderRef.createAppenderRef("Console", level, null);
  final AppenderRef[] refs = new AppenderRef[] {ref};
  final LoggerConfig loggerConfig =
      LoggerConfig.createLogger(true, level, clazz.getName(), null, refs, null, config, null);
  config.addLogger(clazz.getName(), loggerConfig);
  ctx.updateLoggers();
  return LogManager.getLogger(clazz);
}
 
Example #29
Source File: ActorLogger.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
private ActorLogger() {
	loggerContext = (LoggerContext) LogManager.getContext(LogManager.class.getClassLoader(), false);
	Configuration config = loggerContext.getConfiguration();

	Appender systemConsoleAppender = ConsoleAppender.newBuilder()
		.setName(SYSTEM_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_SYSTEM).build())
		.setConfiguration(config)
		.build();
	systemConsoleAppender.start();
    AppenderRef[] systemAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(SYSTEM_CONSOLE_APPENDER_NAME, null, null)};
    systemLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, SYSTEM_LOGGER_NAME, "true", systemAppenderRefs, null, config, null);
    systemLoggerConfig.addAppender(systemConsoleAppender, null, null);
    
    Appender userConsoleAppender = ConsoleAppender.newBuilder()
		.setName(USER_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_USER).build())
		.setConfiguration(config)
		.build();
	userConsoleAppender.start();
	AppenderRef[] userAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(USER_CONSOLE_APPENDER_NAME, null, null)};
	userLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, USER_LOGGER_NAME, "true", userAppenderRefs, null, config, null);
	userLoggerConfig.addAppender(userConsoleAppender, null, null);

    config.addAppender(systemConsoleAppender);
    config.addAppender(userConsoleAppender);
    config.addLogger(SYSTEM_LOGGER_NAME, systemLoggerConfig);
    config.addLogger(USER_LOGGER_NAME, userLoggerConfig);
	loggerContext.updateLoggers(config);
}
 
Example #30
Source File: DefaultRewriteAuditAppender.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void init(final String domain) {
    super.init(domain);

    rewriteAppender = RewriteAppender.createAppender(
            getTargetAppenderName() + "_rewrite",
            "true",
            new AppenderRef[] { AppenderRef.createAppenderRef(getTargetAppenderName(), Level.DEBUG, null) },
            ((LoggerContext) LogManager.getContext(false)).getConfiguration(), getRewritePolicy(), null);
}