Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet180/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   176   177   178   179   180   181   182   183   ...   245
Bog'liq
Java 17 Recipes

9-10. Logging Exceptions
In the previous recipes, you learned how to catch exceptions and log information. This 
recipe put these two recipes together.
 Problem
You want to record exceptions in your log file.
 Solution
Configure your application to use SLF4J. Utilize try/catch blocks to log exceptions 
within the error log. In the following example, an SLF4J Logger logs messages from 
within an exception handler.
Chapter 9 exCeptions and Logging


350
public static void main (String [] args) {
Recipe9_10 recipe = new Recipe9_10();
recipe.start();
}
static Logger rootLogger = Logger.getLogger("");
private void start() {
loadLoggingConfiguration();
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
rootLogger.error("Error in thread "+t+" caused by "+e);
});
int c = 20/0;
}
private void loadLoggingConfiguration() {
FileInputStream ins = null;
try {
ins = new FileInputStream(new File("logging.properties"));
LogManager.getLogManager().readConfiguration(ins);
} catch (IOException e) {
e.printStackTrace();
}
}
 How It Works
The example demonstrates how to use UncaughtExceptionHandler to log exceptions 
to a logging file. When logging an exception, it is good to include the stack trace 
showing where the exception was thrown. In the example, a thread contains 
UncaughtExceptionHandler, which utilizes a lambda expression containing a logger. 
The logger writes any caught exceptions to a log file.
9-11. Summary
This chapter looked at one of the most important phases in application development, 
exception handling. It discussed how to handle single and multiple exceptions and log 
those exceptions.
Chapter 9 exCeptions and Logging


351
© Josh Juneau, Luciano Manelli 2022 
J. Juneau and L. Manelli, Java 17 Recipes
https://doi.org/10.1007/978-1-4842-7963-2_10

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   176   177   178   179   180   181   182   183   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling