當前位置: 首頁>>代碼示例>>Java>>正文


Java Logger類代碼示例

本文整理匯總了Java中org.apache.logging.log4j.core.Logger的典型用法代碼示例。如果您正苦於以下問題:Java Logger類的具體用法?Java Logger怎麽用?Java Logger使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Logger類屬於org.apache.logging.log4j.core包,在下文中一共展示了Logger類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: shutupForge

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
/**
 * 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();
    }
}
 
開發者ID:DaedalusGame,項目名稱:Soot,代碼行數:21,代碼來源:Nope.java

示例2: integrationTestAfter5

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
/**
 * 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);
	}
}
 
開發者ID:magrossi,項目名稱:es-log4j2-appender,代碼行數:30,代碼來源:ElasticSearchRestAppenderTest.java

示例3: removeAndRestoreConsoleAppenderShouldAffectRootLogger

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
@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();
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:26,代碼來源:LogServiceIntegrationJUnitTest.java

示例4: onDisable

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:games647,項目名稱:ColorConsole,代碼行數:26,代碼來源:ColorConsoleBukkit.java

示例5: setup

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
@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);
}
 
開發者ID:flipkart-incubator,項目名稱:Poseidon,代碼行數:23,代碼來源:Log4JAccessLogTest.java

示例6: Log4J2Logger

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:apache,項目名稱:ignite,代碼行數:28,代碼來源:Log4J2Logger.java

示例7: setNodeId

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
/** {@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();
            }
        });
    }
}
 
開發者ID:apache,項目名稱:ignite,代碼行數:27,代碼來源:Log4J2Logger.java

示例8: loggerajax

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
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();
}
 
開發者ID:svenkubiak,項目名稱:mangooio,代碼行數:19,代碼來源:AdminController.java

示例9: preInit

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
@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();
}
 
開發者ID:Ubiquitous-Spice,項目名稱:ModJam-4,代碼行數:26,代碼來源:BloodStains.java

示例10: apply

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
@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();
            }
        }
    };
}
 
開發者ID:astefanutti,項目名稱:camel-cdi,代碼行數:18,代碼來源:LogVerifier.java

示例11: testNestedPattern

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
@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));
}
 
開發者ID:OuZhencong,項目名稱:log4j2,代碼行數:18,代碼來源:PatternParserTest.java

示例12: start

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
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);
            }
        }
 
開發者ID:rmichela,項目名稱:Bukkit-SSHD,代碼行數:20,代碼來源:ConsoleShellFactory.java

示例13: testSmtpAppender

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
private void testSmtpAppender(Logger logger) {
    ThreadContext.put("MDC1", "mdc1");
    logger.error("the message");
    ctx.getLoggerContext().stop();
    smtpServer.stop();

    assertEquals(1, smtpServer.getReceivedEmailSize());
    final Iterator<SmtpMessage> messages = smtpServer.getReceivedEmail();
    final SmtpMessage email = messages.next();

    assertEquals("[email protected]", email.getHeaderValue("To"));
    assertEquals("[email protected]", email.getHeaderValue("From"));
    assertEquals("[mdc1]", email.getHeaderValue("Subject"));

    String body = email.getBody();
    if (!body.contains("Body:[mdc1]")) {
        fail(body);
    }
}
 
開發者ID:apache,項目名稱:logging-log4j2,代碼行數:20,代碼來源:SmtpAppenderAsyncTest.java

示例14: testNoNulCharacters

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
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());
}
 
開發者ID:apache,項目名稱:logging-log4j2,代碼行數:26,代碼來源:CsvJsonParameterLayoutFileAppenderTest.java

示例15: testClientServer

import org.apache.logging.log4j.core.Logger; //導入依賴的package包/類
@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();
    }
}
 
開發者ID:apache,項目名稱:logging-log4j2,代碼行數:26,代碼來源:JeroMqAppenderTest.java


注:本文中的org.apache.logging.log4j.core.Logger類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。