log4j的簡單的例子~以及使用log4j和不使用log4j的對比

    我們先來看一個簡單的例子,它是一個用Java實現的客戶/服務器網絡程序。剛開始我們不使用Log4j,而是使用了一系列的打印語句,然後我們將使用Log4j來實現它的日誌功能。這樣,大家就可以清楚地比較出前後兩個代碼的差別。 
   
  2.1. 不使用Log4j 
   
  2.1.1. 客戶程序 
  
   package log4j ; 
   
  import java.io.* ; 
  import java.net.* ; 
    
  public class ClientWithoutLog4j { 
   
      public static void main ( String args [] ) { 
   
      String welcome = null; 
      String response = null; 
      BufferedReader reader = null; 
      PrintWriter writer = null; 
      InputStream in = null; 
      OutputStream out = null; 
      Socket client = null; 
   
      try { 
        client = new Socket ( "localhost", 8001 ) ; 
        System.out.println ( "info: Client socket: " + client ) ; 
        in = client.getInputStream () ; 
        out = client.getOutputStream () ; 
      } catch ( IOException e ) { 
        System.out.println ( "error: IOException : " + e ) ; 
        System.exit ( 0 ) ; 
      } 
   
      try{ 
        reader = new BufferedReader( new InputStreamReader ( in ) ) ; 
        writer = new PrintWriter ( new OutputStreamWriter ( out ), true ) ; 
   
        welcome = reader.readLine () ; 
        System.out.println ( "debug: Server says: '" + welcome + "'" ) ; 
   
        System.out.println ( "debug: HELLO" ) ; 
        writer.println ( "HELLO" ) ; 
        response = reader.readLine () ; 
        System.out.println ( "debug: Server responds: '" + response + "'") ; 
   
        System.out.println ( "debug: HELP" ) ; 
        writer.println ( "HELP" ) ; 
        response = reader.readLine () ; 
        System.out.println ( "debug: Server responds: '" + response + "'" ) ; 
   
        System.out.println ( "debug: QUIT" ) ; 
        writer.println ( "QUIT" ) ; 
      } catch ( IOException e ) { 
        System.out.println ( "warn: IOException in client.in.readln()" ) ; 
        System.out.println ( e ) ; 
      } 
      try{ 
        Thread.sleep ( 2000 ) ; 
      } catch ( Exception ignored ) {} 
    } 
  } 


   
  2.1.2. 服務器程序 
  
    package log4j ; 
   
  import java.util.* ; 
  import java.io.* ; 
  import java.net.* ; 
   
   
  public class ServerWithoutLog4j { 
   
    final static int SERVER_PORT = 8001 ; // this server's port 
   
     
    public static void main ( String args [] ) { 
      String clientRequest = null; 
      BufferedReader reader = null; 
      PrintWriter writer = null; 
      ServerSocket server = null; 
      Socket socket = null; 
      InputStream in = null; 
      OutputStream out = null; 
   
      try { 
        server = new ServerSocket ( SERVER_PORT ) ; 
        System.out.println ( "info: ServerSocket before accept: " + server ) ; 
        System.out.println ( "info: Java server without log4j, on-line!" ) ; 
   
        // wait for client's connection 
        socket = server.accept () ; 
        System.out.println ( "info: ServerSocket after accept: " + server ) ; 
   
        in = socket.getInputStream () ; 
        out = socket.getOutputStream () ; 
   
      } catch ( IOException e ) { 
        System.out.println( "error: Server constructor IOException: " + e ) ; 
        System.exit ( 0 ) ; 
      } 
      reader = new BufferedReader ( new InputStreamReader ( in ) ) ; 
      writer = new PrintWriter ( new OutputStreamWriter ( out ) , true ) ; 
   
      // send welcome string to client 
      writer.println ( "Java server without log4j, " + new Date () ) ; 
   
      while ( true ) { 
        try { 
          // read from client 
          clientRequest = reader.readLine () ; 
          System.out.println ( "debug: Client says: " + clientRequest ) ; 
          if ( clientRequest.startsWith ( "HELP" ) ) { 
            System.out.println ( "debug: OK!" ) ; 
            writer.println ( "Vocabulary: HELP QUIT" ) ; 
          } 
          else { 
            if ( clientRequest.startsWith ( "QUIT" ) ) { 
              System.out.println ( "debug: OK!" ) ; 
              System.exit ( 0 ) ; 
            } 
            else{ 
              System.out.println ( "warn: Command '" + clientRequest + "' not understood." ) ; 
              writer.println ( "Command '" + clientRequest + "' not understood." ) ; 
            } 
          } 
        } catch ( IOException e ) { 
          System.out.println ( "error: IOException in Server " + e ) ; 
          System.exit ( 0 ) ; 
        } 
      } 
    } 
  } 


   
  2.2. 遷移到Log4j 
   
  2.2.1. 客戶程序 
   
  
    package log4j ; 
   
  import java.io.* ; 
  import java.net.* ; 
   
  // add for log4j: import some package 
  import org.apache.log4j.PropertyConfigurator ; 
  import org.apache.log4j.Logger ; 
  import org.apache.log4j.Level ; 
   
   
  public class ClientWithLog4j { 
   
     
    static Logger logger = Logger.getLogger 
   ( ClientWithLog4j.class.getName () ) ; 
   
     
    public static void main ( String args [] ) { 
   
      String welcome = null ; 
      String response = null ; 
      BufferedReader reader = null ; 
      PrintWriter writer = null ; 
      InputStream in = null ; 
      OutputStream out = null ; 
      Socket client = null ; 
   
       
      PropertyConfigurator.configure ( "ClientWithLog4j.properties" ) ; 
   
      // add for log4j: set the level 
  //    logger.setLevel ( ( Level ) Level.DEBUG ) ; 
   
      try{ 
        client = new Socket( "localhost" , 8001 ) ; 
   
        // add for log4j: log a message with the info level 
        logger.info ( "Client socket: " + client ) ; 
   
        in = client.getInputStream () ; 
        out = client.getOutputStream () ; 
      } catch ( IOException e ) { 
   
        // add for log4j: log a message with the error level 
        logger.error ( "IOException : " + e ) ; 
   
        System.exit ( 0 ) ; 
      } 
   
      try{ 
        reader = new BufferedReader ( new InputStreamReader ( in ) ) ; 
        writer = new PrintWriter ( new OutputStreamWriter ( out ), true ) ; 
   
        welcome = reader.readLine () ; 
   
        // add for log4j: log a message with the debug level 
        logger.debug ( "Server says: '" + welcome + "'" ) ; 
   
        // add for log4j: log a message with the debug level 
        logger.debug ( "HELLO" ) ; 
   
        writer.println ( "HELLO" ) ; 
        response = reader.readLine () ; 
   
        // add for log4j: log a message with the debug level 
        logger.debug ( "Server responds: '" + response + "'" ) ; 
   
        // add for log4j: log a message with the debug level 
        logger.debug ( "HELP" ) ; 
   
        writer.println ( "HELP" ) ; 
        response = reader.readLine () ; 
   
        // add for log4j: log a message with the debug level 
        logger.debug ( "Server responds: '" + response + "'") ; 
   
        // add for log4j: log a message with the debug level 
        logger.debug ( "QUIT" ) ; 
   
        writer.println ( "QUIT" ) ; 
      } catch ( IOException e ) { 
   
        // add for log4j: log a message with the warn level 
        logger.warn ( "IOException in client.in.readln()" ) ; 
   
        System.out.println ( e ) ; 
      } 
      try { 
        Thread.sleep ( 2000 ) ; 
      } catch ( Exception ignored ) {} 
    } 
  } 


   
  2.2.2. 服務器程序 
   
  
    package log4j; 
   
  import java.util.* ; 
  import java.io.* ; 
  import java.net.* ; 
   
  // add for log4j: import some package 
  import org.apache.log4j.PropertyConfigurator ; 
  import org.apache.log4j.Logger ; 
  import org.apache.log4j.Level ; 
   
   
  public class ServerWithLog4j { 
   
    final static int SERVER_PORT = 8001 ; // this server's port 
   
     
    static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName()) ; 
   
     
    public static void main ( String args[]) { 
      String clientRequest = null ; 
      BufferedReader reader = null ; 
      PrintWriter writer = null ; 
      ServerSocket server = null ; 
      Socket socket = null ; 
   
      InputStream in = null ; 
      OutputStream out = null ; 
   
       
      PropertyConfigurator.configure ( "ServerWithLog4j.properties" ) ; 
   
      // add for log4j: set the level 
  //    logger.setLevel ( ( Level ) Level.DEBUG ) ; 
   
      try{ 
        server = new ServerSocket ( SERVER_PORT ) ; 
   
        // add for log4j: log a message with the info level 
        logger.info ( "ServerSocket before accept: " + server ) ; 
   
        // add for log4j: log a message with the info level 
        logger.info ( "Java server with log4j, on-line!" ) ; 
   
        // wait for client's connection 
        socket = server.accept() ; 
   
        // add for log4j: log a message with the info level 
        logger.info ( "ServerSocket after accept: " + server ) ; 
   
        in = socket.getInputStream() ; 
        out = socket.getOutputStream() ; 
   
      } catch ( IOException e ) { 
   
        // add for log4j: log a message with the error level 
        logger.error ( "Server constructor IOException: " + e ) ; 
        System.exit ( 0 ) ; 
      } 
      reader = new BufferedReader ( new InputStreamReader ( in ) ) ; 
      writer = new PrintWriter ( new OutputStreamWriter ( out ), true ) ; 
   
      // send welcome string to client 
      writer.println ( "Java server with log4j, " + new Date () ) ; 
   
      while ( true ) { 
        try { 
          // read from client 
          clientRequest = reader.readLine () ; 
   
          // add for log4j: log a message with the debug level 
          logger.debug ( "Client says: " + clientRequest ) ; 
   
          if ( clientRequest.startsWith ( "HELP" ) ) { 
   
            // add for log4j: log a message with the debug level 
            logger.debug ( "OK!" ) ; 
   
            writer.println ( "Vocabulary: HELP QUIT" ) ; 
          } 
          else { 
            if ( clientRequest.startsWith ( "QUIT" ) ) { 
   
              // add for log4j: log a message with the debug level 
              logger.debug ( "OK!" ) ; 
   
              System.exit ( 0 ) ; 
            } 
            else { 
   
              // add for log4j: log a message with the warn level 
              logger.warn ( "Command '"  + clientRequest + "' not understood." ) ; 
   
              writer.println ( "Command '" + clientRequest + "' not understood." ) ; 
            } 
          } 
        } catch ( IOException e ) { 
   
          // add for log4j: log a message with the error level 
          logger.error( "IOException in Server " + e ) ; 
   
          System.exit ( 0 ) ; 
        } 
      } 
    } 
  } 


   
  2.2.3. 配置文件 
   
  2.2.3.1. 客戶程序配置文件 
   
  
    log4j.rootLogger=INFO, A1 
   
  log4j.appender.A1=org.apache.log4j.ConsoleAppender 
   
  log4j.appender.A1.layout=org.apache.log4j.PatternLayout 
   
  log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n 
   


  2.2.3.2. 服務器程序配置文件 
   
  
    log4j.rootLogger=INFO, A1 
   
  log4j.appender.A1=org.apache.log4j.ConsoleAppender 
   
  log4j.appender.A1.layout=org.apache.log4j.PatternLayout 
   
  log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n 


   
  2.3. 比較 
   

   比較這兩個應用可以看出,採用Log4j進行日誌操作的整個過程相當簡單明瞭,與直接使用System.out.println語句進行日誌信息輸出的 方式相比,基本上沒有增加代碼量,同時能夠清楚地理解每一條日誌信息的重要程度。通過控制配置文件,我們還可以靈活地修改日誌信息的格式,輸出目的地等等方面,而單純依靠System.out.println語句,顯然需要做更多的工作。 



參考:http://wenku.baidu.com/view/83f294e69b89680203d82569.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章