您的位置:首页 > 其它

log4j的简单的例子~以及使用log4j和不使用log4j的对比

2013-11-13 17:47 260 查看
我们先来看一个简单的例子,它是一个用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: