Java 类org.apache.logging.log4j.core.Logger 实例源码

项目:Soot    文件:Nope.java   
/**
 * Make forge not spew "dangerous alternative prefix" messages in this block.
 */
public static void shutupForge(Runnable op) {
    Logger log = (Logger) FMLLog.log;
    try {
        Object privateConfig = ReflectionHelper.findField(Logger.class, "privateConfig").get(log);
        Field intLevelF = ReflectionHelper.findField(privateConfig.getClass(), "intLevel");
        int intLevel = (int) intLevelF.get(privateConfig);
        intLevelF.set(privateConfig, 299); // disable WARN logging

        try {
            op.run();
        } finally {
            intLevelF.set(privateConfig, intLevel);
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
项目:es-log4j2-appender    文件:ElasticSearchRestAppenderTest.java   
/**
 * Integration test that asserts events are sent to the Elastic cluster in bulk.
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void integrationTestAfter5() throws IOException {
    String test = "integration-test-after-5";
    Logger logger = getLogger(test);
    ElasticClient client = new ElasticClient(logger);
    String marker = getUniqueMarker();

    // Should not send until it reaches 5 events
    for (int i = 1; i < 5; i++) {
        logger.error(MarkerManager.getMarker(marker), i + "-" + test);
    }
    JsonNode doc = client.findFirstByMarker(marker);
    assertNull(doc);

    // But after the 5th event it should send all buffered events
    logger.error(MarkerManager.getMarker(marker), "5-" + test);
    JsonNode hits = client.findAllByMarker(marker);
    assertNotNull(hits);
    assertEquals(5, hits.size());
    for (int i = 0; i < 5; i++) {
        assertFieldValue(hits.get(i).get("_source"), "level", "ERROR");
        assertFieldValue(hits.get(i).get("_source"), "message", (i + 1) + "-" + test);
    }
}
项目:monarch    文件:LogServiceIntegrationJUnitTest.java   
@Test
public void removeAndRestoreConsoleAppenderShouldAffectRootLogger() {
  LogService.reconfigure();

  assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
      .isTrue();

  final Logger rootLogger = (Logger) LogService.getRootLogger();

  // assert "Console" is present for ROOT
  Appender appender = rootLogger.getAppenders().get(LogService.STDOUT);
  assertThat(appender).isNotNull();

  LogService.removeConsoleAppender();

  // assert "Console" is not present for ROOT
  appender = rootLogger.getAppenders().get(LogService.STDOUT);
  assertThat(appender).isNull();

  LogService.restoreConsoleAppender();

  // assert "Console" is present for ROOT
  appender = rootLogger.getAppenders().get(LogService.STDOUT);
  assertThat(appender).isNotNull();
}
项目:ColorConsole    文件:ColorConsoleBukkit.java   
@Override
public void onDisable() {
    //restore the old format
    Appender terminalAppender = CommonLogInstaller.getTerminalAppender(TERMINAL_NAME);
    Logger rootLogger = ((Logger) LogManager.getRootLogger());

    ColorPluginAppender colorPluginAppender = null;
    for (Appender value : rootLogger.getAppenders().values()) {
        if (value instanceof ColorPluginAppender) {
            colorPluginAppender = (ColorPluginAppender) value;
            break;
        }
    }

    if (colorPluginAppender != null) {
        rootLogger.removeAppender(terminalAppender);
        rootLogger.addAppender(colorPluginAppender.getOldAppender());
    }

    try {
        CommonLogInstaller.setLayout(oldLayout, terminalAppender);
    } catch (ReflectiveOperationException ex) {
        getLogger().log(Level.WARNING, "Cannot revert log format", ex);
    }
}
项目:Poseidon    文件:Log4JAccessLogTest.java   
@Before
public void setup() throws Exception {
    // Create mock objects
    mockLog4jContextFactory = mock(Log4jContextFactory.class);
    whenNew(Log4jContextFactory.class).withNoArguments().thenReturn(mockLog4jContextFactory);
    mockLoggerContext = mock(LoggerContext.class);
    mockLogger = mock(Logger.class);
    when(mockLog4jContextFactory.getContext(anyString(), any(ClassLoader.class), any(), anyBoolean(), any(URI.class), anyString())).thenReturn(mockLoggerContext);
    when(mockLoggerContext.getRootLogger()).thenReturn(mockLogger);
    mockRequest = mock(Request.class);
    mockResponse = mock(Response.class);
    mockAccessLog = mock(AccessLog.class);
    whenNew(AccessLog.class).withArguments(mockRequest, mockResponse).thenReturn(mockAccessLog);

    // Create actual objects
    enabledSupplier = () -> true;
    disabledSupplier = () -> false;
    failedAccessLog = new TestLog4JAccessLog(NON_EXISTING_FILE_PATH, enabledSupplier);
    String filePath = getClass().getClassLoader().getResource(ACCESS_CONFIG_FILE_PATH).getPath();
    enabledAccessLog = new TestLog4JAccessLog(filePath, enabledSupplier);
    disabledAccessLog = new TestLog4JAccessLog(filePath, disabledSupplier);
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * Creates new logger with given configuration {@code path}.
 *
 * @param path Path to log4j2 configuration XML file.
 * @throws IgniteCheckedException Thrown in case logger can't be created.
 */
public Log4J2Logger(String path) throws IgniteCheckedException {
    if (path == null)
        throw new IgniteCheckedException("Configuration XML file for Log4j2 must be specified.");

    final URL cfgUrl = U.resolveIgniteUrl(path);

    if (cfgUrl == null)
        throw new IgniteCheckedException("Log4j2 configuration path was not found: " + path);

    addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
        @Override public Logger apply(Boolean init) {
            if (init)
                Configurator.initialize(LogManager.ROOT_LOGGER_NAME, cfgUrl.toString());

            return (Logger)LogManager.getRootLogger();
        }
    });

    quiet = quiet0;
    cfg = path;
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * Creates new logger with given configuration {@code cfgFile}.
 *
 * @param cfgFile Log4j configuration XML file.
 * @throws IgniteCheckedException Thrown in case logger can't be created.
 */
public Log4J2Logger(File cfgFile) throws IgniteCheckedException {
    if (cfgFile == null)
        throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");

    if (!cfgFile.exists() || cfgFile.isDirectory())
        throw new IgniteCheckedException("Log4j2 configuration path was not found or is a directory: " + cfgFile);

    final String path = cfgFile.getAbsolutePath();

    addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
        @Override public Logger apply(Boolean init) {
            if (init)
                Configurator.initialize(LogManager.ROOT_LOGGER_NAME, path);

            return (Logger)LogManager.getRootLogger();
        }
    });

    quiet = quiet0;
    cfg = cfgFile.getPath();
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * Creates new logger with given configuration {@code cfgUrl}.
 *
 * @param cfgUrl URL for Log4j configuration XML file.
 * @throws IgniteCheckedException Thrown in case logger can't be created.
 */
public Log4J2Logger(final URL cfgUrl) throws IgniteCheckedException {
    if (cfgUrl == null)
        throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");

    addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
        @Override public Logger apply(Boolean init) {
            if (init)
                Configurator.initialize(LogManager.ROOT_LOGGER_NAME, cfgUrl.toString());

            return (Logger)LogManager.getRootLogger();
        }
    });

    quiet = quiet0;
    cfg = cfgUrl.getPath();
}
项目:ignite    文件:Log4J2Logger.java   
/** {@inheritDoc} */
@Override public void setNodeId(UUID nodeId) {
    A.notNull(nodeId, "nodeId");

    this.nodeId = nodeId;

    // Set nodeId as system variable to be used at configuration.
    System.setProperty(NODE_ID, U.id8(nodeId));

    if (inited) {
        final LoggerContext ctx = impl.getContext();

        synchronized (mux) {
            inited = false;
        }

        addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
            @Override public Logger apply(Boolean init) {
                if (init)
                    ctx.reconfigure();

                return (Logger)LogManager.getRootLogger();
            }
        });
    }
}
项目:mangooio    文件:AdminController.java   
public Response loggerajax(Request request) {
    Map<String, Object> body = request.getBodyAsJsonMap();
    if (body != null && body.size() > 0) {
        String clazz = body.get("class").toString();
        String level = body.get("level").toString();
        if (StringUtils.isNotBlank(clazz) && StringUtils.isNotBlank(level)) {
            LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
            for (Logger logger : loggerContext.getLoggers()) { //NOSONAR
                if (clazz.equals(logger.getName())) {
                    logger.setLevel(Level.getLevel(level));
                    break;
                }
            }
        }
    }

    return Response.withOk().andEmptyBody();
}
项目:ModJam-4    文件:BloodStains.java   
@Mod.EventHandler
   public void preInit(FMLPreInitializationEvent event)
   {
       // logging stuff.
       if (!FMLForgePlugin.RUNTIME_DEOBF) // not runtime deobf = dev env
       {
           String packageName = this.getClass().getPackage().getName();
           Logger baseLogger = (Logger) LogManager.getLogger(packageName);
           ConsoleAppender appender = ConsoleAppender.createAppender(null, null, Target.SYSTEM_OUT.toString(), "console", "true", "false");
           baseLogger.addAppender(appender);
           baseLogger.setLevel(Level.DEBUG);
           appender.start();

           // testing levels..
           for (Level l : Level.values())
           {
               baseLogger.log(l, "TESTING {} on level {}", baseLogger.getName(), l);
               LogManager.getLogger().log(l, "TESTING {} on level {}", this.getClass().getName(), l);
           }
       }

    Configuration c = new Configuration(event.getSuggestedConfigurationFile());
    OUR_SERVER = c.get("main", "globalbloodstain", 1, "Turn on global bloodstains?0=no, 1=yes").getInt() == 0 ? false : true;
    c.save();
}
项目:camel-cdi    文件:LogVerifier.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            appender.start();
            ((Logger) LogManager.getRootLogger()).addAppender(appender);
            try {
                base.evaluate();
                verify();
            } finally {
                ((Logger) LogManager.getRootLogger()).removeAppender(appender);
                appender.stop();
            }
        }
    };
}
项目:log4j2    文件:PatternParserTest.java   
@Test
public void testNestedPattern() {
    final List<PatternFormatter> formatters = parser.parse(nestedPattern);
    assertNotNull(formatters);
    final Throwable t = new Throwable();
    final StackTraceElement[] elements = t.getStackTrace();
    final LogEvent event = new Log4jLogEvent("org.apache.logging.log4j.PatternParserTest", MarkerManager.getMarker("TEST"),
            Logger.class.getName(), Level.INFO, new SimpleMessage("Hello, world"), null, null, null, "Thread1", elements[0],
            System.currentTimeMillis());
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
        formatter.format(event, buf);
    }
    final String str = buf.toString();
    final String expected = String.format("] INFO : Hello, world%s\u001B[m", Constants.LINE_SEP);
    assertTrue(" Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
项目:Bukkit-SSHD    文件:ConsoleShellFactory.java   
public void start(Environment env) throws IOException {

            try {
                consoleReader = new ConsoleReader(in, new FlushyOutputStream(out), new SshTerminal());
                consoleReader.setExpandEvents(true);
                consoleReader.addCompleter(new ConsoleCommandCompleter());

                StreamHandler streamHandler = new FlushyStreamHandler(out, new ConsoleLogFormatter(), consoleReader);
                streamHandlerAppender = new StreamHandlerAppender(streamHandler);

                ((Logger) LogManager.getRootLogger()).addAppender(streamHandlerAppender);

                environment = env;
                thread = new Thread(this, "SSHD ConsoleShell " + env.getEnv().get(Environment.ENV_USER));
                thread.start();
            } catch (Exception e) {
                throw new IOException("Error starting shell", e);
            }
        }
项目:logging-log4j2    文件:CsvJsonParameterLayoutFileAppenderTest.java   
public void testNoNulCharacters(final String message, final String expected) throws IOException {
    @SuppressWarnings("resource")
    final LoggerContext loggerContext = loggerContextRule.getLoggerContext();
    final Logger logger = loggerContext.getLogger("com.example");
    logger.error("log:", message);
    loggerContext.stop();
    final File file = new File(FILE_PATH);
    final byte[] contents = FileUtils.readFileToByteArray(file);
    int count0s = 0;
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < contents.length; i++) {
        final byte b = contents[i];
        if (b == 0) {
            sb.append(i);
            sb.append(", ");
            count0s++;
        }
    }
    Assert.assertEquals("File contains " + count0s + " 0x00 byte at indices " + sb, 0, count0s);
    final List<String> readLines = FileUtils.readLines(file, Charset.defaultCharset());
    final String actual = readLines.get(0);
    // Assert.assertTrue(actual, actual.contains(message));
    Assert.assertEquals(actual, expected, actual);
    Assert.assertEquals(1, readLines.size());
}
项目:logging-log4j2    文件:JeroMqAppenderTest.java   
@Test(timeout = DEFAULT_TIMEOUT_MILLIS)
public void testClientServer() throws Exception {
    final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class);
    final int expectedReceiveCount = 3;
    final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), ENDPOINT, expectedReceiveCount);
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        final Future<List<String>> future = executor.submit(client);
        Thread.sleep(100);
        final Logger logger = ctx.getLogger(getClass().getName());
        appender.resetSendRcs();
        logger.info("Hello");
        logger.info("Again");
        ThreadContext.put("foo", "bar");
        logger.info("World");
        final List<String> list = future.get();
        Assert.assertEquals(expectedReceiveCount, appender.getSendRcTrue());
        Assert.assertEquals(0, appender.getSendRcFalse());
        Assert.assertEquals("Hello", list.get(0));
        Assert.assertEquals("Again", list.get(1));
        Assert.assertEquals("barWorld", list.get(2));
    } finally {
        executor.shutdown();
    }
}
项目:PetBlocks    文件:PetBlockFilter.java   
/**
 * Creates a new logger.
 *
 * @return logger
 */
public static PetBlockFilter create() {
    final PetBlockFilter petBlockFilter = new PetBlockFilter();
    petBlockFilter.start();
    ((org.apache.logging.log4j.core.Logger) LogManager.getRootLogger()).addFilter(petBlockFilter);
    return petBlockFilter;
}
项目:sumo    文件:TestLog4j2.java   
public static void main(String [] args){
    try{
        System.out.println(logger1.isDebugEnabled());
        System.out.println(logger1.isErrorEnabled());
        System.out.println(logger1.isInfoEnabled());

        System.out.println(logger2.isDebugEnabled());
        System.out.println(logger2.isErrorEnabled());
        System.out.println(logger2.isInfoEnabled());

        System.out.println(logger3.isDebugEnabled());
        System.out.println(logger3.isErrorEnabled());
        System.out.println(logger3.isInfoEnabled());

        System.out.println(logger4.isDebugEnabled());
        System.out.println(logger4.isErrorEnabled());
        System.out.println(logger4.isInfoEnabled());

        org.apache.logging.log4j.spi.LoggerContext context=LogManager.getContext();
        Logger logger = (Logger) LogManager.getLogger();
        LoggerConfig config=logger.get();
        Map<Property, Boolean> properties=config.getProperties();
        System.out.println(config.getName());
        LoggerContext ctx=LoggerContext.getContext();
        Object appenders=ctx.getConfiguration().getAppenders();
        System.out.println(appenders.toString());
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        System.exit(0);
    }


}
项目:es-log4j2-appender    文件:ElasticSearchRestAppenderTest.java   
public ElasticClient(Logger logger) {
    Map<String,Appender> appenders = logger.getAppenders();
    ElasticSearchRestAppender appender = (ElasticSearchRestAppender)appenders.get(appenders.keySet().iterator().next());
    client = RestClient.builder(new HttpHost("localhost", 9200)).build();
    index = appender.getIndex();
    type = appender.getType();
}
项目:es-log4j2-appender    文件:ElasticSearchRestAppenderTest.java   
/**
 * Gets the test logger and assign the appender to it 
 *
 * @param appender the name of the appender
 * @return the logger
 */
private Logger getLogger(String appender) {
    final LoggerContext loggerContext = Configurator.initialize(getUniqueMarker(), CONFIG_LOCATION);
    Logger logger = loggerContext.getLogger(appender);
    logger.getAppenders().clear();
    logger.addAppender(loggerContext.getConfiguration().getAppenders().get(appender));
    return logger;
}
项目:es-log4j2-appender    文件:ElasticSearchRestAppenderTest.java   
/**
 * Integration test that asserts events are sent to the Elastic cluster.
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void integrationTest() throws IOException {
    String test = "integration-test";
    Logger logger = getLogger(test);
    ElasticClient client = new ElasticClient(logger);
    String marker = getUniqueMarker();
    logger.error(MarkerManager.getMarker(marker), "Test Message");
    JsonNode doc = client.findFirstByMarker(marker);
    assertNotNull(doc);
    assertFieldValue(doc, "level", "ERROR");
    assertFieldValue(doc, "message", "Test Message");
}
项目:logging-log4j-boot    文件:Log4jLoggingSystem.java   
@Override
public void setLogLevel(final String loggerName, final LogLevel logLevel) {
    if (loggerContext != null) {
        final Logger logger = loggerContext.getLogger(loggerName);
        final LoggerConfig config = logger.get();
        final Level level = convert(logLevel);
        if (config.getLevel() != level) {
            config.setLevel(level);
        }
    }
}
项目:monarch    文件:LogServiceIntegrationJUnitTest.java   
@Test
public void defaultConfigShouldIncludeStdout() {
  LogService.reconfigure();
  final Logger rootLogger = (Logger) LogService.getRootLogger();

  assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
      .isTrue();
  assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNotNull();
}
项目:monarch    文件:LogServiceIntegrationJUnitTest.java   
@Test
public void removeConsoleAppenderShouldRemoveStdout() {
  LogService.reconfigure();
  final Logger rootLogger = (Logger) LogService.getRootLogger();

  LogService.removeConsoleAppender();

  assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNull();
}
项目:monarch    文件:PersistentColocatedPartitionedRegionDUnitTest.java   
public Object call() throws Exception {
  // Setup for capturing logger messages
  Appender mockAppender = mock(Appender.class);
  when(mockAppender.getName()).thenReturn("MockAppender");
  when(mockAppender.isStarted()).thenReturn(true);
  when(mockAppender.isStopped()).thenReturn(false);
  Logger logger = (Logger) LogManager.getLogger(ColocationLogger.class);
  logger.addAppender(mockAppender);
  logger.setLevel(Level.WARN);
  loggingEventCaptor = ArgumentCaptor.forClass(LogEvent.class);

  // Logger interval may have been hooked by the test, so adjust test delays here
  int logInterval = ColocationLogger.getLogInterval();
  List<LogEvent> logEvents = Collections.emptyList();

  AtomicBoolean isDone = new AtomicBoolean(false);
  try {
    createPR(PR_REGION_NAME, true);
    // Let this thread continue running long enough for the missing region to be logged a
    // couple times.
    // Child regions do not get created by this thread.
    await().atMost(MAX_WAIT, TimeUnit.MILLISECONDS).until(() -> {
      verify(mockAppender, times(numExpectedLogMessages))
          .append(loggingEventCaptor.capture());
    });
    // createPR("region2", PR_REGION_NAME, true); // This child region is never created
  } finally {
    logEvents = loggingEventCaptor.getAllValues();
    assertEquals(String.format("Expected %d messages to be logged, got %d.",
        numExpectedLogMessages, logEvents.size()), numExpectedLogMessages,
        logEvents.size());
    String logMsg = logEvents.get(0).getMessage().getFormattedMessage();
    logger.removeAppender(mockAppender);
    numExpectedLogMessages = 1;
    return logMsg;
  }
}
项目:monarch    文件:PersistentColocatedPartitionedRegionDUnitTest.java   
public Object call() throws Exception {
  // Setup for capturing logger messages
  Appender mockAppender = mock(Appender.class);
  when(mockAppender.getName()).thenReturn("MockAppender");
  when(mockAppender.isStarted()).thenReturn(true);
  when(mockAppender.isStopped()).thenReturn(false);
  Logger logger = (Logger) LogManager.getLogger(ColocationLogger.class);
  logger.addAppender(mockAppender);
  logger.setLevel(Level.WARN);
  loggingEventCaptor = ArgumentCaptor.forClass(LogEvent.class);

  // Logger interval may have been hooked by the test, so adjust test delays here
  int logInterval = ColocationLogger.getLogInterval();
  List<LogEvent> logEvents = Collections.emptyList();

  try {
    createPR(PR_REGION_NAME, true);
    createPR("region2", PR_REGION_NAME, true); // This child region is never created
    // Let this thread continue running long enough for the missing region to be logged a
    // couple times.
    // Grandchild region does not get created by this thread. (1.5*logInterval < delay <
    // 2*logInterval)
    await().atMost((int) (1.75 * logInterval), TimeUnit.MILLISECONDS).until(() -> {
      verify(mockAppender, times(numExpectedLogMessages))
          .append(loggingEventCaptor.capture());
    });
    // createPR("region3", PR_REGION_NAME, true); // This child region is never created
  } finally {
    logEvents = loggingEventCaptor.getAllValues();
    assertEquals(String.format("Expected %d messages to be logged, got %d.",
        numExpectedLogMessages, logEvents.size()), numExpectedLogMessages,
        logEvents.size());
    String logMsg = logEvents.get(0).getMessage().getFormattedMessage();
    logger.removeAppender(mockAppender);
    numExpectedLogMessages = 1;
    return logMsg;
  }
}
项目:ColorConsole    文件:CommonLogInstaller.java   
public static void installAppender(Appender colorAppender, String terminalName) {
    Logger rootLogger = (Logger) LogManager.getRootLogger();

    colorAppender.start();

    rootLogger.removeAppender(getTerminalAppender(terminalName));
    rootLogger.addAppender(colorAppender);
}
项目:onedrive-java-client    文件:LogUtils.java   
public static String addFileLogger(String logFile) {

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration config = ctx.getConfiguration();

        // Default log layout
        Layout<? extends Serializable> layout =
                PatternLayout.createLayout("%d %p [%t] %m%n", null, null, null, true, true, null, null);

        // Create a new file appender for the given filename
        FileAppender appender = FileAppender.createAppender(
                logFile,
                "false",
                "false",
                "FileAppender",
                "false",
                "true",
                "true",
                null,
                layout,
                null,
                null,
                null,
                config);

        appender.start();
        ((Logger) LogManager.getRootLogger()).addAppender(appender);

        return appender.getFileName();
    }
项目:EnderCore    文件:TextureErrorRemover.java   
public static void beginIntercepting() {
  EnderCore.logger.info("Attempting to initialize texture error message interceptor.");
  try {
    Field f = ReflectionHelper.findField(TextureMap.class, "logger", "field_147635_d", "d");
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
    f.setAccessible(true);
    INSTANCE = new TextureErrorRemover((Logger) f.get(null));
    f.set(null, INSTANCE);
  } catch (Exception e) {
    EnderCore.logger.error("Failed to initialize texture error interceptor!", e);
  }
}
项目:WorldDownloader-Serverside-Companion    文件:LoggingHandler.java   
/**
 * Attempt to add WDL-specific logging.
 * 
 * @param mode
 *            The mode to use, from the config key 'wdl.logMode'.
 */
public static void setupLogging(String mode) throws Exception {
    if (mode == null || mode.equalsIgnoreCase("none")) {
        return;
    }

    Logger logger = (Logger) LogManager.getRootLogger();
    if (logger.getAppenders().containsKey(APPENDER_NAME)) {
        // Already initalized
        return;
    }

    Field privateConfigField;
    boolean isNewLog4j;
    // Handle (and use) the field name change between log4j versions
    try {
        privateConfigField = Logger.class.getDeclaredField("privateConfig");
        isNewLog4j = true;
    } catch (NoSuchFieldException ex) {
        privateConfigField = Logger.class.getDeclaredField("config");
        isNewLog4j = false;
    }
    privateConfigField.setAccessible(true);
    Object privateConfig = privateConfigField.get(logger);

    Field configField = privateConfig.getClass().getDeclaredField("config");
    configField.setAccessible(true);

    Configuration config = (Configuration) configField.get(privateConfig);

    if (isNewLog4j) {
        handleNewLog4j(config, logger, mode);
    } else {
        handleOldLog4j(config, logger, mode);
    }
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * Creates new logger with given implementation.
 *
 * @param impl Log4j implementation to use.
 */
private Log4J2Logger(final Logger impl, String path) {
    assert impl != null;

    addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
        @Override public Logger apply(Boolean init) {
            return impl;
        }
    });

    quiet = quiet0;
    cfg = path;
}
项目:ignite    文件:Log4J2Logger.java   
/** {@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;
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * Creates console appender with some reasonable default logging settings.
 *
 * @return Logger with auto configured console appender.
 */
public Logger createConsoleLogger() {
    // from http://logging.apache.org/log4j/2.x/manual/customconfig.html
    final LoggerContext ctx = impl.getContext();

    final Configuration cfg = ctx.getConfiguration();

    PatternLayout.Builder builder = PatternLayout.newBuilder()
        .withPattern("%d{ISO8601}][%-5p][%t][%c{1}] %m%n")
        .withCharset(Charset.defaultCharset())
        .withAlwaysWriteExceptions(false)
        .withNoConsoleNoAnsi(false);

    PatternLayout layout = builder.build();

    ConsoleAppender.Builder consoleAppenderBuilder = ConsoleAppender.newBuilder()
        .withName(CONSOLE_APPENDER)
        .withLayout(layout);

    ConsoleAppender consoleApp = consoleAppenderBuilder.build();

    consoleApp.start();

    cfg.addAppender(consoleApp);
    cfg.getRootLogger().addAppender(consoleApp, Level.TRACE, null);

    ctx.updateLoggers(cfg);

    return ctx.getRootLogger();
}
项目:modules-main    文件:MySQLDatabase.java   
@Inject
public MySQLDatabase(Reflector reflector, ModuleManager mm, FileManager fm, LogFactory logFactory)
{
    this.mm = mm;
    this.mm.registerBinding(Database.class, this);
    File pluginFolder = mm.getBasePath();

    // Disable HikariPool Debug ConsoleSpam
    ((Logger)LogManager.getLogger(HikariPool.class)).setLevel(Level.INFO);
    ((Logger)LogManager.getLogger("com.zaxxer.hikari.pool.PoolBase")).setLevel(Level.INFO); // really? now pkg-private
    ((Logger)LogManager.getLogger(HikariConfig.class)).setLevel(Level.INFO);

    // Setting up Logger...
    this.logger = mm.getLoggerFor(Database.class);
    AsyncFileTarget target =
            new AsyncFileTarget.Builder(LoggingUtil.getLogFile(fm, "Database").toPath(),
                    LoggingUtil.getFileFormat(true, false)
            ).setAppend(true).setCycler(LoggingUtil.getCycler()).setThreadFactory(threadFactory).build();

    target.setLevel(LogLevel.DEBUG);
    logger.addTarget(target);


    LogTarget parentTarget = logger.addDelegate(logFactory.getLog(LogFactory.class));
    parentTarget.appendFilter(new PrefixFilter("[DB] "));
    parentTarget.setLevel(LogLevel.INFO);


    this.config = reflector.load(MySQLDatabaseConfiguration.class, new File(pluginFolder, "database.yml"));


}
项目:BetterRCon    文件:BetterRCon.java   
private boolean loadLogAppender()
{
    Logger log = (Logger)LogManager.getRootLogger();
    for(Appender appender : log.getAppenders().values())
    {
        if(appender instanceof RConsoleAppender)
            log.removeAppender(appender);
    }

    mAppender = new RConsoleAppender(new DefaultConfiguration());
    mAppender.start();
    log.addAppender(mAppender);

    return true;
}
项目:log4j2    文件:FlumeAppenderTest.java   
@Before
public void setUp() throws Exception {
    eventSource = new AvroSource();
    channel = new MemoryChannel();

    Configurables.configure(channel, new Context());

    avroLogger = (Logger) LogManager.getLogger("avrologger");
    /*
     * Clear out all other appenders associated with this logger to ensure
     * we're only hitting the Avro appender.
     */
    removeAppenders(avroLogger);
    final Context context = new Context();
    testPort = String.valueOf(testServerPort);
    context.put("port", testPort);
    context.put("bind", "0.0.0.0");
    Configurables.configure(eventSource, context);

    final List<Channel> channels = new ArrayList<Channel>();
    channels.add(channel);

    final ChannelSelector cs = new ReplicatingChannelSelector();
    cs.setChannels(channels);

    eventSource.setChannelProcessor(new ChannelProcessor(cs));

    eventSource.start();

    Assert.assertTrue("Reached start or error", LifecycleController
            .waitForOneOf(eventSource, LifecycleState.START_OR_ERROR));
    Assert.assertEquals("Server is started", LifecycleState.START,
            eventSource.getLifecycleState());
}
项目:log4j2    文件:FlumeAppenderTest.java   
@Test
public void testStructured() throws InterruptedException, IOException {
    final Agent[] agents = new Agent[] { Agent.createAgent("localhost",
            testPort) };
    final FlumeAppender avroAppender = FlumeAppender.createAppender(agents,
            null, "false", "Avro", null, "1000", "1000", "1", "1000",
            "avro", "false", null, null, null, "ReqCtx_", null, "true",
            "1", null, null, null, null);
    avroAppender.start();
    final Logger eventLogger = (Logger) LogManager.getLogger("EventLogger");
    Assert.assertNotNull(eventLogger);
    eventLogger.addAppender(avroAppender);
    eventLogger.setLevel(Level.ALL);

    final StructuredDataMessage msg = new StructuredDataMessage("Transfer",
            "Success", "Audit");
    msg.put("memo", "This is a memo");
    msg.put("acct", "12345");
    msg.put("amount", "100.00");
    ThreadContext.put("id", UUID.randomUUID().toString());
    ThreadContext.put("memo", null);
    ThreadContext.put("test", "123");

    EventLogger.logEvent(msg);

    final Transaction transaction = channel.getTransaction();
    transaction.begin();

    final Event event = channel.take();
    Assert.assertNotNull(event);
    Assert.assertTrue("Channel contained event, but not expected message",
            getBody(event).endsWith("Success"));
    transaction.commit();
    transaction.close();

    eventSource.stop();
    eventLogger.removeAppender(avroAppender);
    avroAppender.stop();
}
项目:log4j2    文件:FlumeAppenderTest.java   
private void removeAppenders(final Logger logger) {
    final Map<String, Appender> map = logger.getAppenders();
    for (final Map.Entry<String, Appender> entry : map.entrySet()) {
        final Appender app = entry.getValue();
        avroLogger.removeAppender(app);
        app.stop();
    }
}
项目:log4j2    文件:RegexFilter.java   
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
                     final Throwable t) {
    if (msg == null) {
        return onMismatch;
    }
    return filter(msg.toString());
}