下面列出了org.apache.logging.log4j.Logger#fatal ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @reason Warn the player (configurable to crash or log too) instead of only logging a
* message a scheduled task throws an exception. The default vanilla behaviour is dangerous
* as things will fail silently, making future bugs much harder to solve. In fact, it may
* actually be a vanilla bug that the client doesn't crash, since they are using the "fatal"
* log level, which is otherwise used only for problems which crash the game.
*/
@Overwrite
@Nullable
// TODO: Utils shouldn't depend on minecraft, redirect individual calls to runTask instead
public static <V> V runTask(FutureTask<V> task, Logger logger) {
task.run();
try {
return task.get();
} catch (InterruptedException | ExecutionException e) {
ModConfig.ProblemAction action = ModConfig.crashes.scheduledTaskAction;
if (action == ModConfig.ProblemAction.CRASH) {
CrashUtils.crash(new CrashReport("Error executing task", e));
} else if (action == ModConfig.ProblemAction.WARNING_SCREEN) {
CrashUtils.warn(new CrashReport("Error executing task", e));
} else if (action == ModConfig.ProblemAction.NOTIFICATION) {
CrashUtils.notify(new CrashReport("Error executing task", e));
} else if (action == ModConfig.ProblemAction.LOG) {
logger.fatal("Error executing task", e);
}
return null;
}
}
@Test
void log4j2LevelMetrics() {
new Log4j2Metrics().bindTo(registry);
assertThat(registry.get("log4j2.events").counter().count()).isEqualTo(0.0);
Logger logger = LogManager.getLogger(Log4j2MetricsTest.class);
Configurator.setLevel(Log4j2MetricsTest.class.getName(), Level.INFO);
logger.info("info");
logger.warn("warn");
logger.fatal("fatal");
logger.error("error");
logger.debug("debug"); // shouldn't record a metric as per log level config
logger.trace("trace"); // shouldn't record a metric as per log level config
assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "warn").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "fatal").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "debug").counter().count()).isEqualTo(0.0);
assertThat(registry.get("log4j2.events").tags("level", "trace").counter().count()).isEqualTo(0.0);
}
@Test
public void testAppender() throws Exception {
final Logger logger = loggerContextRule.getLogger();
for (int i = 0; i < 10; ++i) {
// 30 chars per message: each message triggers a rollover
logger.fatal("This is a test message number " + i); // 30 chars:
}
Thread.sleep(100); // Allow time for rollover to complete
final File dir = new File(DIR);
assertTrue("Dir " + DIR + " should exist", dir.exists());
assertTrue("Dir " + DIR + " should contain files", dir.listFiles().length == 6);
final File[] files = dir.listFiles();
final List<String> expected = Arrays.asList("rollingtest.log", "test-001.log", "test-002.log", "test-003.log", "test-004.log", "test-005.log");
assertEquals("Unexpected number of files", expected.size(), files.length);
for (final File file : files) {
if (!expected.contains(file.getName())) {
fail("unexpected file" + file);
}
}
}
public void test(final String[] args) {
System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
// System.out.println(System.getProperty("java.class.path"));
final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
: args[0];
try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
logger.fatal("Fatal message.");
logger.error("Error message.");
logger.warn("Warning message.");
logger.info("Information message.");
logger.debug("Debug message.");
logger.trace("Trace message.");
logger.error("Error message.", new IOException("test"));
}
}
public static void main(String[] args) {
final Logger logger = LogManager.getLogger(StartSECC.class.getSimpleName());
MiscUtils.loadProperties(GlobalValues.SECC_CONFIG_PROPERTIES_PATH.toString());
UDPServer udpServer = UDPServer.getInstance();
TCPServer tcpServer = TCPServer.getInstance();
TLSServer tlsServer = TLSServer.getInstance();
if (!udpServer.initialize() || !tlsServer.initialize() || !tcpServer.initialize()) {
logger.fatal("Unable to start SECC because UDP, TCP or TLS server could not be initialized");
} else {
Thread udpServerThread = new Thread(udpServer);
udpServerThread.setName("UDPServerThread");
Thread tcpServerThread = new Thread(tcpServer);
tcpServerThread.setName("TCPServerThread");
Thread tlsServerThread = new Thread(tlsServer);
tlsServerThread.setName("TLSServerThread");
// All transport layer threads need to be initialized before initializing the SECC session handler.
new V2GCommunicationSessionHandlerSECC();
/*
* To avoid possible race conditions, the transport layer threads need to be started AFTER the SECC
* session handler has been initialized. Otherwise the situation might occur that the UDPServer is
* receiving a UDP client packet and tries to access the MessageHandler object before this object has
* been created by the SECC session handler.
*/
udpServerThread.start();
tcpServerThread.start();
tlsServerThread.start();
}
}
@Test
public void givenLoggerWithConsoleConfig_whenLogToConsoleInColors_thanOK() throws Exception {
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
Exception e = new RuntimeException("This is only a test!");
logger.trace("This is a colored message at TRACE level.");
logger.debug("This is a colored message at DEBUG level. " + "This is the minimum visible level.");
logger.info("This is a colored message at INFO level.");
logger.warn("This is a colored message at WARN level.");
logger.error("This is a colored message at ERROR level.", e);
logger.fatal("This is a colored message at FATAL level.");
}
@Test
public void givenLoggerWithFailoverConfig_whenLog_thanOK() throws Exception {
Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER");
Exception e = new RuntimeException("This is only a test!");
logger.trace("This is a syslog message at TRACE level.");
logger.debug("This is a syslog message at DEBUG level.");
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
logger.warn("This is a syslog message at WARN level.");
logger.error("This is a syslog message at ERROR level.", e);
logger.fatal("This is a syslog message at FATAL level.");
}
@Test
public void testMethodLogger() throws Exception {
final ListAppender app = context.getListAppender("Method").clear();
final Logger logger = context.getLogger("MethodLogger");
logger.info("More messages.");
logger.warn("CATASTROPHE INCOMING!");
logger.error("ZOMBIES!!!");
logger.fatal("brains~~~");
logger.info("Itchy. Tasty.");
final List<String> messages = app.getMessages();
assertEquals("Incorrect number of messages.", 5, messages.size());
for (final String message : messages) {
assertEquals("Incorrect caller method name.", "testMethodLogger", message);
}
}
@Test
public void testRouter() throws Exception {
final Logger logger = LogManager.getLogger(AsyncAppenderQueueFullPolicyTest.class);
assertEquals(4, asyncAppender.getQueueCapacity());
logger.error("event 1 - gets taken off the queue");
logger.warn("event 2");
logger.info("event 3");
logger.info("event 4");
while (asyncAppender.getQueueRemainingCapacity() == 0) {
Thread.yield(); // wait until background thread takes one element off the queue
}
logger.info("event 5 - now the queue is full");
assertEquals("queue remaining capacity", 0, asyncAppender.getQueueRemainingCapacity());
assertEquals("EventRouter invocations", 0, policy.queueFull.get());
final Thread release = new Thread("AsyncAppenderReleaser") {
@Override
public void run() {
while (policy.queueFull.get() == 0) {
try {
Thread.sleep(10L);
} catch (final InterruptedException ignored) {
//ignored
}
}
blockingAppender.running = false;
}
};
release.setDaemon(true);
release.start();
logger.fatal("this blocks until queue space available");
assertEquals(1, policy.queueFull.get());
}
@Test
public void test() throws Exception {
try (Connection connection = jdbcRule.getConnection()) {
final Error exception = new Error("This is a test.");
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (final PrintWriter writer = new PrintWriter(outputStream)) {
exception.printStackTrace(writer);
}
final String stackTrace = outputStream.toString();
final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig");
logger.trace("Data source logged message 01.");
logger.fatal("Error from data source 02.", exception);
Thread.sleep(1000);
try (final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT * FROM dsMappingLogEntry ORDER BY id")) {
assertTrue("There should be at least one row.", resultSet.next());
assertEquals("The level column is not correct (1).", "FATAL", resultSet.getNString("level"));
assertEquals("The logger column is not correct (1).", logger.getName(), resultSet.getNString("logger"));
assertEquals("The message column is not correct (1).", "Hello World!", resultSet.getString("message"));
assertEquals("The exception column is not correct (1).", stackTrace,
IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1));
assertFalse("There should not be two rows.", resultSet.next());
}
}
}
@Test
public void testDataSourceConfig() throws Exception {
try (final Connection connection = jdbcRule.getConnectionSource().getConnection()) {
final Error exception = new Error("Final error massage is fatal!");
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (final PrintWriter writer = new PrintWriter(outputStream)) {
exception.printStackTrace(writer);
}
final String stackTrace = outputStream.toString();
final long millis = System.currentTimeMillis();
final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig");
logger.trace("Data source logged message 01.");
logger.fatal("Error from data source 02.", exception);
try (final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT * FROM dsLogEntry ORDER BY id")) {
assertTrue("There should be at least one row.", resultSet.next());
final long date = resultSet.getTimestamp("eventDate").getTime();
assertTrue("The date should be later than pre-logging (1).", date >= millis);
assertTrue("The date should be earlier than now (1).", date <= System.currentTimeMillis());
assertEquals("The literal column is not correct (1).", "Literal Value of Data Source",
resultSet.getString("literalColumn"));
assertEquals("The level column is not correct (1).", "FATAL", resultSet.getNString("level"));
assertEquals("The logger column is not correct (1).", logger.getName(), resultSet.getNString("logger"));
assertEquals("The message column is not correct (1).", "Error from data source 02.",
resultSet.getString("message"));
assertEquals("The exception column is not correct (1).", stackTrace,
IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1));
assertFalse("There should not be two rows.", resultSet.next());
}
}
}
@Test
public void test() throws Exception {
try (Connection connection = jdbcRule.getConnection()) {
final Error exception = new Error("This is a test.");
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (final PrintWriter writer = new PrintWriter(outputStream)) {
exception.printStackTrace(writer);
}
final String stackTrace = outputStream.toString();
final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig");
logger.trace("Data source logged message 01.");
logger.fatal("Error from data source 02.", exception);
Thread.sleep(1000);
try (final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT * FROM dsMappingLogEntry ORDER BY id")) {
assertTrue("There should be at least one row.", resultSet.next());
assertEquals("The level column is not correct (1).", "FATAL", resultSet.getNString("level"));
assertEquals("The logger column is not correct (1).", logger.getName(), resultSet.getNString("logger"));
assertEquals("The message column is not correct (1).", "Error from data source 02.",
resultSet.getString("message"));
assertEquals("The exception column is not correct (1).", stackTrace,
IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1));
assertFalse("There should not be two rows.", resultSet.next());
}
}
}
@Test
public void testBasicJpaEntityAppender() throws SQLException {
try {
this.setUp("log4j2-" + this.databaseType + "-jpa-basic.xml");
final Error exception = new Error("Goodbye, cruel world!");
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final PrintWriter writer = new PrintWriter(outputStream);
exception.printStackTrace(writer);
writer.close();
final String stackTrace = outputStream.toString().replace("\r\n", "\n");
final long millis = System.currentTimeMillis();
final Logger logger1 = LogManager.getLogger(this.getClass().getName() + ".testBasicJpaEntityAppender");
final Logger logger2 = LogManager.getLogger(this.getClass().getName() + ".testBasicJpaEntityAppenderAgain");
logger1.debug("Test my debug 01.");
logger1.warn("This is another warning 02.", exception);
logger2.fatal("A fatal warning has been issued.");
final Statement statement = this.connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT * FROM jpaBasicLogEntry ORDER BY id");
assertTrue("There should be at least one row.", resultSet.next());
long date = resultSet.getLong("timemillis");
assertTrue("The date should be later than pre-logging (1).", date >= millis);
assertTrue("The date should be earlier than now (1).", date <= System.currentTimeMillis());
assertEquals("The level column is not correct (1).", "DEBUG", resultSet.getString("level"));
assertEquals("The logger column is not correct (1).", logger1.getName(), resultSet.getString("loggerName"));
assertEquals("The message column is not correct (1).", "Test my debug 01.",
resultSet.getString("message"));
assertNull("The exception column is not correct (1).", resultSet.getString("thrown"));
assertTrue("There should be at least two rows.", resultSet.next());
date = resultSet.getLong("timemillis");
assertTrue("The date should be later than pre-logging (2).", date >= millis);
assertTrue("The date should be earlier than now (2).", date <= System.currentTimeMillis());
assertEquals("The level column is not correct (2).", "WARN", resultSet.getString("level"));
assertEquals("The logger column is not correct (2).", logger1.getName(), resultSet.getString("loggerName"));
assertEquals("The message column is not correct (2).", "This is another warning 02.",
resultSet.getString("message"));
assertEquals("The exception column is not correct (2).", stackTrace, resultSet.getString("thrown"));
assertTrue("There should be three rows.", resultSet.next());
date = resultSet.getLong("timemillis");
assertTrue("The date should be later than pre-logging (3).", date >= millis);
assertTrue("The date should be earlier than now (3).", date <= System.currentTimeMillis());
assertEquals("The level column is not correct (3).", "FATAL", resultSet.getString("level"));
assertEquals("The logger column is not correct (3).", logger2.getName(), resultSet.getString("loggerName"));
assertEquals("The message column is not correct (3).", "A fatal warning has been issued.",
resultSet.getString("message"));
assertNull("The exception column is not correct (3).", resultSet.getString("thrown"));
assertFalse("There should not be four rows.", resultSet.next());
} finally {
this.tearDown();
}
}