화요일, 3월 11
Shadow

#017 Java Logging

Lab Exercises

 

Exercise 1: Simple logging

In this exercise, you are going to learn how to use Java logging APIs for doing simple logging.

(1.1) Build and run an application that uses simple logging

0. Start NetBeans IDE if you have not done so yet.
1. Create a new NetBeans project

  • Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
  • Under Choose Project pane, select Java under Categories and Java Application under Projects.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, type in SimpleLoggingExample as project name.
  • For Create Main Class field, type in SimpleLoggingExample.  (Figure-1.10 below)
  • Click Finish.


Figure-1.10: Create a new project

  • Observe that SimpleLoggingExample project appears and IDE generated SimpleLoggingExample.java is displayed in the source editor window of NetBeans IDE.

2. Modify the IDE generated SimpleLoggingExample.java as shown in Code-1.11 below.  Study the code by paying special attention to the bold fonted parts.

import java.util.logging.Level;
import java.util.logging.Logger;

public class SimpleLoggingExample {

// A Logger object is used to log messages for a specific system
// or application component. Loggers are normally named, using a
// hierarchical dot-separated namespace. Logger names can be arbitrary
// strings, but they should normally be based on the package name or
// class name of the logged component. In addition it is possible
// to create “anonymous” Loggers that are not stored in the Logger
// namespace.
private static Logger logger = Logger.getLogger(“loggerdemo”);

public static void main(String[] args) {
// Log a INFO tracing message
logger.info(“doing stuff”);

try{
System.out.println(3/0);
} catch(Exception e){
logger.log(Level.SEVERE,”dividing by 0″);
}

logger.info(“done”);
}

}

Code-1.11: SimpleLoggingExample.java

3. Build and run the project

  • Right click SimpleLoggingExample project and select Run Project.
  • Observe the result in the Output window. (Figure-1.13 below)
Feb 18, 2007 7:24:42 AM SimpleLoggingExample main
INFO: doing stuff
Feb 18, 2007 7:24:42 AM SimpleLoggingExample main
SEVERE: dividing by 0
Feb 18, 2007 7:24:42 AM SimpleLoggingExample main
INFO: done

Figure-1.13: Result of running SimpleLoggingExample application

Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javalogging/samples/SimpleLoggingExample.  You can just open it and run it.

4. For your own exercise, modify SimpleLoggingExample.java as following. Build and run the application.

  • Create another logger called myownlogger as following
    • private static Logger myownlogger = Logger.getLogger(“myownlogger”);
  • Display info level message somewhere in the code using myownlogger object

(1.2) Set logging level

1. Create a new NetBeans project

  • Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
  • Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
  • Under Name and Location pane, for the Project Name field, type in SimpleLoggingExample2 as project name.
  • For Create Main Class field, type in SimpleLoggingExample2.
  • Click Finish.
  • Observe that SimpleLoggingExample2 project appears and IDE generated SimpleLoggingExample2.java is displayed in the source editor window of NetBeans IDE.

2. Modify the IDE generated SimpleLoggingExample2.java as shown in Code-1.21 below.  Study the code by paying special attention to the bold fonted parts.  The change from the code of step 1.1 above is to add a logging level.

import java.util.logging.Level;
import java.util.logging.Logger;

public class SimpleLoggginExample2 {

// A Logger object is used to log messages for a specific system
// or application component. Loggers are normally named, using a
// hierarchical dot-separated namespace. Logger names can be arbitrary
// strings, but they should normally be based on the package name or
// class name of the logged component. In addition it is possible
// to create “anonymous” Loggers that are not stored in the Logger
// namespace.
private static Logger logger = Logger.getLogger(“loggerdemo”);

public static void main(String[] args) {

// Set logging level
logger.setLevel(Level.SEVERE);

// Log a INFO tracing message
logger.info(“doing stuff”);

try{
System.out.println(3/0);
} catch(Exception e){
logger.log(Level.SEVERE,”dividing by 0″);
}

logger.info(“done”);
}

}

Code-1.21: SimpleLoggingExample2.java

3. Build and run the project

  • Right click SimpleLoggingExample2 project and select Run Project.
  • Observe the result in the Output window. (Figure-1.23 below)
Feb 18, 2007 7:37:25 AM SimpleLoggginExample2 main
SEVERE: dividing by 0

Figure-1.23: Result of running SimpleLoggingExample2 application

Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javalogging/samples/SimpleLoggingExample2.  You can just open it and run it.

4. For your own exercise, modify SimpleLoggingExample2.java as following. Build and run the application.

  • Use context sensitive Javadoc on Level.SEVERE and find out all the logging levels.
  • Change the logging level to something else such as FINE.

Summary

In this exercise, you have learned how to do simple logging.  You also learned how to set logging level.

Exercise 2: Log to file and multiple handlers

In this exercise, you are going to learn how to log messages to a file. You are also going to learn how to use multiple handlers.

  1. Log to a file
  2. Use multiple handlers

(2.1) Log to a file

1. Create a new NetBeans project

  • Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
  • Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
  • Under Name and Location pane, for the Project Name field, type in LogToFileUsingFileHandler as project name.
  • For Create Main Class field, type in LogToFileUsingFileHandler.
  • Click Finish.
  • Observe that LogToFileUsingFileHandler project appears and IDE generated LogToFileUsingFileHandler.java is displayed in the source editor window of NetBeans IDE.

2. Modify the IDE generated LogToFileUsingFileHandler.java as shown in Code-2.11 below.  Study the code by paying special attention to the bold fonted parts.

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LogToFileUsingFileHandler {

// A Logger object is used to log messages for a specific system
// or application component. Loggers are normally named, using a
// hierarchical dot-separated namespace. Logger names can be arbitrary
// strings, but they should normally be based on the package name or
// class name of the logged component. In addition it is possible
// to create “anonymous” Loggers that are not stored in the Logger
// namespace.
private static Logger logger = Logger.getLogger(“loggerdemo”);

public static void main(String[] args) throws Exception {

// Log to a file
logger.addHandler(new FileHandler(“MyOwnLog.xml”));

// Log a INFO tracing message
logger.info(“doing stuff”);

try{
System.out.println(3/0);
} catch(Exception e){
logger.log(Level.SEVERE,”dividing by 0″);
}

logger.info(“done”);
}

}

Code-2.11: LogToFileUsingFileHandler.java

3. Build and run the project

  • Right click LogToFileUsingFileHandler project and select Run Project.
  • Observe the result in the Output window. (Figure-2.13 below)
Feb 18, 2007 7:49:29 AM LogToFileUsingFileHandler main
INFO: doing stuff
Feb 18, 2007 7:49:29 AM LogToFileUsingFileHandler main
SEVERE: dividing by 0
Feb 18, 2007 7:49:29 AM LogToFileUsingFileHandler main
INFO: done

Figure-2.13: Result of running LogToFileUsingFileHandler application

  • Observe that MyOwnLog.xml file contains the logging messages. (Figure-2.14 below)  If you are using NetBeans, this file is located in the same directory you have created your NetBeans project.
<?xml version=”1.0″ encoding=”windows-1252″ standalone=”no”?>
<!DOCTYPE log SYSTEM “logger.dtd”>
<log>
<record>
<date>2007-02-18T07:49:29</date>
<millis>1171802969296</millis>
<sequence>0</sequence>
<logger>loggerdemo</logger>
<level>INFO</level>
<class>LogToFileUsingFileHandler</class>
<method>main</method>
<thread>10</thread>
<message>doing stuff</message>
</record>
<record>
<date>2007-02-18T07:49:29</date>
<millis>1171802969328</millis>
<sequence>1</sequence>
<logger>loggerdemo</logger>
<level>SEVERE</level>
<class>LogToFileUsingFileHandler</class>
<method>main</method>
<thread>10</thread>
<message>dividing by 0</message>
</record>
<record>
<date>2007-02-18T07:49:29</date>
<millis>1171802969328</millis>
<sequence>2</sequence>
<logger>loggerdemo</logger>
<level>INFO</level>
<class>LogToFileUsingFileHandler</class>
<method>main</method>
<thread>10</thread>
<message>done</message>
</record>
</log>

Figure-2.14: MyOwnLog.xml

Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javalogging/samples/LogToFileUsingFileHandler.  You can just open it and run it.

4. For your own exercise, modify LogToFileUsingFileHandler.java as following. Build and run the application.

  • Use your own file called MyReallyOwnLog.xml to do the logging

(2.2) Use multiple handlers

In this step, you are going to log using multiple handlers, FileHandler and ConsoleHandler.

1. Create a new NetBeans project

  • Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
  • Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
  • Under Name and Location pane, for the Project Name field, type in UseMultipleHandlers as project name.
  • For Create Main Class field, type in UseMultipleHandlers.
  • Click Finish.
  • Observe that UseMultipleHandlers project appears and IDE generated UseMultipleHandlers.java is displayed in the source editor window of NetBeans IDE.

2. Modify the IDE generated UseMultipleHandlers.java as shown in Code-2.21 below.  Study the code by paying special attention to the bold fonted parts.

import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UseMultipleHandlers {

// A Logger object is used to log messages for a specific system
// or application component. Loggers are normally named, using a
// hierarchical dot-separated namespace. Logger names can be arbitrary
// strings, but they should normally be based on the package name or
// class name of the logged component. In addition it is possible
// to create “anonymous” Loggers that are not stored in the Logger
// namespace.
private static Logger logger = Logger.getLogger(“loggerdemo”);

public static void main(String[] args) throws Exception {

// Add File handler and Console handler
logger.addHandler(new FileHandler(“MultipleHandlers.xml”));
logger.addHandler(new ConsoleHandler());

// Log a INFO tracing message
logger.info(“doing stuff”);

try{
System.out.println(3/0);
} catch(Exception e){
logger.log(Level.SEVERE,”dividing by 0″);
}

logger.info(“done”);
}

}

Code-2.21: UseMultipleHandlers.java

3. Build and run the project

  • Right click UseMultipleHandlers project and select Run Project.
  • Observe the result in the Output window. (Figure-2.23 below)  Note that since the ConsoleHandler is configured as a default, adding ConsoleHandler results in two ConsoleHandlers performing logging operation.
Feb 18, 2007 8:00:05 AM UseMultipleHandlers main
INFO: doing stuff
Feb 18, 2007 8:00:05 AM UseMultipleHandlers main
INFO: doing stuff
Feb 18, 2007 8:00:05 AM UseMultipleHandlers main
SEVERE: dividing by 0
Feb 18, 2007 8:00:05 AM UseMultipleHandlers main
SEVERE: dividing by 0
Feb 18, 2007 8:00:05 AM UseMultipleHandlers main
INFO: done
Feb 18, 2007 8:00:05 AM UseMultipleHandlers main
INFO: done

Figure-2.23: Result of running UseMultipleHandlers application

  • Observe that MultipleHandlers.xml file contains the logging messages. (Figure-2.24 below) If you are using NetBeans, this file is located in the same directory you have created your NetBeans project.
<?xml version=”1.0″ encoding=”windows-1252″ standalone=”no”?>
<!DOCTYPE log SYSTEM “logger.dtd”>
<log>
<record>
<date>2007-02-18T07:49:29</date>
<millis>1171802969296</millis>
<sequence>0</sequence>
<logger>loggerdemo</logger>
<level>INFO</level>
<class>LogToFileUsingFileHandler</class>
<method>main</method>
<thread>10</thread>
<message>doing stuff</message>
</record>
<record>
<date>2007-02-18T07:49:29</date>
<millis>1171802969328</millis>
<sequence>1</sequence>
<logger>loggerdemo</logger>
<level>SEVERE</level>
<class>LogToFileUsingFileHandler</class>
<method>main</method>
<thread>10</thread>
<message>dividing by 0</message>
</record>
<record>
<date>2007-02-18T07:49:29</date>
<millis>1171802969328</millis>
<sequence>2</sequence>
<logger>loggerdemo</logger>
<level>INFO</level>
<class>LogToFileUsingFileHandler</class>
<method>main</method>
<thread>10</thread>
<message>done</message>
</record>
</log>

Figure-2.24: MultipleHandlers.xml

Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javalogging/samples/UseMultipleHandlers.  You can just open it and run it.

4. For your own exercise, modify UseMultipleHandlers.java as following. Build and run the application.

  • Add another FileHandler instance using myown.xml as a file.
  • After running the application, check if the myown.xml file contains logging information.

Summary

In this exercise,  you have learned how to log to a file.  You also learned how to use multiple handlers.

Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)

 

1. The homework is to modify LogToFileUsingFileHandler project above as following.  (You might want to create a new project by copying the LogToFileUsingFileHandler project.  You can name the homework project in any way you want but here I am going to call it MyLogToFileUsingFileHandler.)
  • Add another file handler with a  file of your own.
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javalogging.
  • Zip file of the the MyLogToFileUsingFileHandler NetBeans project.  (Someone else should be able to open and run it as a NetBeans project.)  You can use your favorite zip utility or you can use “jar” utility that comes with JDK as following.
    • cd <parent directory that contains MyLogToFileUsingFileHandler directory> (assuming you named your project as MyLogToFileUsingFileHandler)
    • jar cvf MyLogToFileUsingFileHandler.zip MyLogToFileUsingFileHandler (MyLogToFileUsingFileHandler should contain nbproject directory)
  • Captured output screen  – name it as JavaIntro-javalogging.gif orJavaIntro-javalogging.jpg (or JavaIntro-javalogging.<whatver graphics format>)
    • Any screen capture (just one of them) that shows that your program is working is good enough.  No cosmetic polishment is required.
  • If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project.

 

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

This site uses Akismet to reduce spam. Learn how your comment data is processed.