Java 17 Recipes


-8. Logging Events Within Your Application


Download 3.2 Mb.
Pdf ko'rish
bet177/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   173   174   175   176   177   178   179   180   ...   245
Bog'liq
Java 17 Recipes

9-8. Logging Events Within Your Application
 Problem
You want to log events, debug messages, error conditions, and other events within your 
application.
 Solution
Utilize the Java Logging API within your application to implement a logging solution. The 
following example first creates a logger object named recipeLogger. In this example, the 
Java Logger logs an informational message, a warning message, and an error message.
private void loadLoggingConfiguration() {
FileInputStream ins = null;
try {
ins = new FileInputStream(new File("logging.properties"));
LogManager.getLogManager().readConfiguration(ins);
} catch (IOException e) {
e.printStackTrace();
}
}
private void start() {
loadLoggingConfiguration();
Logger logger = Logger.getLogger("recipeLogger");
logger.info("Logging for the first Time!");
Chapter 9 exCeptions and Logging


346
logger.warn("A warning to be had");
logger. severe ("This is an error!");
}
public static void main (String[] args) {
Recipe9_8 recipe = new Recipe9_8();
recipe.start();
}
The following output is defined in the logging.properties file.
dic 02, 2021 10:27:38 PM org.java17recipes.chapter09.recipe09_08 
.Recipe9_8 start
INFO: Logging for the first Time!
dic 02, 2021 10:27:38 PM org.java17recipes.chapter09.recipe09_08 
.Recipe9_8 start
WARNING: A warning to be had
dic 02, 2021 10:27:38 PM org.java17recipes.chapter09.recipe09_08 
.Recipe9_8 start
SEVERE: This is an error!
Use the default properties file of the JDK in the conf folder and copy it in your 
project folder.
The following is the logging.properties file in the main folder of the project.
handlers = java.util.logging.FileHandler
recipeLogger.level=INFO
.level=ALL
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.pattern=LogApplication%g.log
java.util.logging.FileHandler.limit=50000
java.util.logging.FileHandler.count=4
 How It Works
In the example, loadLoggingConfiguration() function opens a stream to the logging 
.properties file and passes it to java.util.logging.LogManager(). Doing so 
configures the java.util.logging framework to use the settings specified in the 
Chapter 9 exCeptions and Logging


347
logging.properties file. Then, within the start method of the solution, the code 
acquires a logger object named recipeLogger. The example proceeds to log messages 
through recipeLogger.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   173   174   175   176   177   178   179   180   ...   245




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