log4j详解.docx

上传人:b****8 文档编号:9958325 上传时间:2023-02-07 格式:DOCX 页数:24 大小:25.42KB
下载 相关 举报
log4j详解.docx_第1页
第1页 / 共24页
log4j详解.docx_第2页
第2页 / 共24页
log4j详解.docx_第3页
第3页 / 共24页
log4j详解.docx_第4页
第4页 / 共24页
log4j详解.docx_第5页
第5页 / 共24页
点击查看更多>>
下载资源
资源描述

log4j详解.docx

《log4j详解.docx》由会员分享,可在线阅读,更多相关《log4j详解.docx(24页珍藏版)》请在冰豆网上搜索。

log4j详解.docx

log4j详解

log4j详解

       根据网络资料整理       

>>>>1.概述<<<<

  1.1.背景

  

  在应用程序中添加日志记录总的来说基于三个目的:

监视代码中变量的变化情况,周期性的记录到文件中供其他应用进行统计分析工作;跟踪代码运行时轨迹,作为日后审计的依据;担当集成开发环境中的调试器的作用,向文件或控制台打印代码的调试信息。

  

  最普通的做法就是在代码中嵌入许多的打印语句,这些打印语句可以输出到控制台或文件中,比较好的做法就是构造一个日志操作类来封装此类操作,而不是让一系列的打印语句充斥了代码的主体。

  

  1.2.Log4j简介

  

  在强调可重用组件开发的今天,除了自己从头到尾开发一个可重用的日志操作类外,Apache为我们提供了一个强有力的日志操作包-Log4j。

  

  Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服务器、NT的事件记录器、UNIXSyslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。

最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

  

  此外,通过Log4j其他语言接口,您可以在C、C++、.Net、PL/SQL程序中使用Log4j,其语法和用法与在Java程序中一样,使得多语言分布式系统得到一个统一一致的日志组件模块。

而且,通过使用各种第三方扩展,您可以很方便地将Log4j集成到J2EE、JINI甚至是SNMP应用中。

  

  本文介绍的Log4j版本是1.2.3。

作者试图通过一个简单的客户/服务器Java程序例子对比使用与不使用Log4j1.2.3的差别,并详细讲解了在实践中最常使用Log4j的方法和步骤。

在强调可重用组件开发的今天,相信Log4j将会给广大的设计开发人员带来方便。

加入到Log4j的队伍来吧!

  

>>>>2.一个简单的例子<<<<

  我们先来看一个简单的例子,它是一个用Java实现的客户/服务器网络程序。

刚开始我们不使用Log4j,而是使用了一系列的打印语句,然后我们将使用Log4j来实现它的日志功能。

这样,大家就可以清楚地比较出前后两个代码的差别。

  

  2.1.不使用Log4j

  

  2.1.1.客户程序

  packagelog4j;

  

  importjava.io.*;

  import.*;

  

  /**

  *

  *

ClientWithoutLog4j

  *

Description:

asamplewithlog4j

  *@version1.0

  */

  publicclassClientWithoutLog4j{

  

    /**

    *

    *@paramargs

    */

    publicstaticvoidmain(Stringargs[]){

  

      Stringwelcome=null;

      Stringresponse=null;

      BufferedReaderreader=null;

      PrintWriterwriter=null;

      InputStreamin=null;

      OutputStreamout=null;

      Socketclient=null;

  

      try{

        client=newSocket("localhost",8001);

        System.out.println("info:

Clientsocket:

"+client);

        in=client.getInputStream();

        out=client.getOutputStream();

      }catch(IOExceptione){

        System.out.println("error:

IOException:

"+e);

        System.exit(0);

      }

  

      try{

        reader=newBufferedReader(newInputStreamReader(in));

        writer=newPrintWriter(newOutputStreamWriter(out),true);

  

        welcome=reader.readLine();

        System.out.println("debug:

Serversays:

'"+welcome+"'");

  

        System.out.println("debug:

HELLO");

        writer.println("HELLO");

        response=reader.readLine();

        System.out.println("debug:

Serverresponds:

'"+response+"'");

  

        System.out.println("debug:

HELP");

        writer.println("HELP");

        response=reader.readLine();

        System.out.println("debug:

Serverresponds:

'"+response+"'");

  

        System.out.println("debug:

QUIT");

        writer.println("QUIT");

      }catch(IOExceptione){

        System.out.println("warn:

IOExceptioninclient.in.readln()");

        System.out.println(e);

      }

      try{

        Thread.sleep(2000);

      }catch(Exceptionignored){}

    }

  }

  

  2.1.2.服务器程序

  packagelog4j;

  

  importjava.util.*;

  importjava.io.*;

  import.*;

  

  /**

  *

  *

ServerWithoutLog4j

  *

Description:

asamplewithlog4j

  *@version1.0

  */

  publicclassServerWithoutLog4j{

  

    finalstaticintSERVER_PORT=8001;//thisserver'sport

  

    /**

    *

    *@paramargs

    */

    publicstaticvoidmain(Stringargs[]){

      StringclientRequest=null;

      BufferedReaderreader=null;

      PrintWriterwriter=null;

      ServerSocketserver=null;

      Socketsocket=null;

      InputStreamin=null;

      OutputStreamout=null;

  

      try{

        server=newServerSocket(SERVER_PORT);

        System.out.println("info:

ServerSocketbeforeaccept:

"+server);

        System.out.println("info:

Javaserverwithoutlog4j,on-line!

");

  

        //waitforclient'sconnection

        socket=server.accept();

        System.out.println("info:

ServerSocketafteraccept:

"+server) ;

  

        in=socket.getInputStream();

        out=socket.getOutputStream();

  

      }catch(IOExceptione){

        System.out.println("error:

ServerconstructorIOException:

"+e);

        System.exit(0);

      }

      reader=newBufferedReader(newInputStreamReader(in));

      writer=newPrintWriter(newOutputStreamWriter(out),true);

  

      //sendwelcomestringtoclient

      writer.println("Javaserverwithoutlog4j,"+newDate());

  

      while(true){

        try{

          //readfromclient

          clientRequest=reader.readLine();

          System.out.println("debug:

Clientsays:

"+clientRequest);

          if(clientRequest.startsWith("HELP")){

            System.out.println("debug:

OK!

");

            writer.println("Vocabulary:

HELPQUIT");

          }

          else{

            if(clientRequest.startsWith("QUIT")){

              System.out.println("debug:

OK!

");

              System.exit(0);

            }

            else{

              System.out.println("warn:

Command'"+

  clientRequest+"'notunderstood.");

              writer.println("Command'"+clientRequest

  +"'notunderstood.");

            }

          }

        }catch(IOExceptione){

          System.out.println("error:

IOExceptioninServer"+e);

          System.exit(0);

        }

      }

    }

  }

  

  2.2.迁移到Log4j

  

  2.2.1.客户程序

  

  packagelog4j;

  

  importjava.io.*;

  import.*;

  

  //addforlog4j:

importsomepackage

  importorg.apache.log4j.PropertyConfigurator;

  importorg.apache.log4j.Logger;

  importorg.apache.log4j.Level;

  

  /**

  *

  *

ClientWithLog4j

  *

Description:

asamplewithlog4j

  *@version1.0

  */

  publicclassClientWithLog4j{

  

    /*

    addforlog4j:

classLoggeristhecentralclassinthelog4jpackage.

    wecandomostloggingoperationsbyLoggerexceptconfiguration.

    getLogger(...):

retrievealoggerbyname,ifnotthencreateforit.

    */

    staticLoggerlogger=Logger.getLogger

  (ClientWithLog4j.class.getName());

  

    /**

    *

    *@paramargs:

configurationfilename

    */

    publicstaticvoidmain(Stringargs[]){

  

      Stringwelcome=null;

      Stringresponse=null;

      BufferedReaderreader=null;

      PrintWriterwriter=null;

      InputStreamin=null;

      OutputStreamout=null;

      Socketclient=null;

  

      /*

      addforlog4j:

classBasicConfiguratorcanquicklyconfigurethepackage.

      printtheinformationtoconsole.

      */

      PropertyConfigurator.configure("ClientWithLog4j.properties");

  

      //addforlog4j:

setthelevel

  //    logger.setLevel((Level)Level.DEBUG);

  

      try{

        client=newSocket("localhost",8001);

  

        //addforlog4j:

logamessagewiththeinfolevel

        logger.info("Clientsocket:

"+client);

  

        in=client.getInputStream();

        out=client.getOutputStream();

      }catch(IOExceptione){

  

        //addforlog4j:

logamessagewiththeerrorlevel

        logger.error("IOException:

"+e);

  

        System.exit(0);

      }

  

      try{

        reader=newBufferedReader(newInputStreamReader(in));

        writer=newPrintWriter(newOutputStreamWriter(out),true);

  

        welcome=reader.readLine();

  

        //addforlog4j:

logamessagewiththedebuglevel

        logger.debug("Serversays:

'"+welcome+"'");

  

        //addforlog4j:

logamessagewiththedebuglevel

        logger.debug("HELLO");

  

        writer.println("HELLO");

        response=reader.readLine();

  

        //addforlog4j:

logamessagewiththedebuglevel

        logger.debug("Serverresponds:

'"+response+"'");

  

        //addforlog4j:

logamessagewiththedebuglevel

        logger.debug("HELP");

  

        writer.println("HELP");

        response=reader.readLine();

  

        //addforlog4j:

logamessagewiththedebuglevel

        logger.debug("Serverresponds:

'"+response+"'");

  

        //addforlog4j:

logamessagewiththedebuglevel

        logger.debug("QUIT");

  

        writer.println("QUIT");

      }catch(IOExceptione){

  

        //addforlog4j:

logamessagewiththewarnlevel

        logger.warn("IOExceptioninclient.in.readln()");

  

        System.out.println(e);

      }

      try{

        Thread.sleep(2000);

      }catch(Exceptionignored){}

    }

  }

  

  2.2.2.服务器程序

  

  packagelog4j;

  

  importjava.util.*;

  importjava.io.*;

  import.*;

  

  //addforlog4j:

importsomepackage

  importorg.apache.log4j.PropertyConfigurator;

  importorg.apache.log4j.Logger;

  importorg.apache.log4j.Level;

  

  /**

  *

  *

ServerWithLog4j

  *

Description:

asamplewithlog4j

  *@version1.0

  */

  publicclassServerWithLog4j{

  

    finalstaticintSERVER_PORT=8001;//thisserver'sport

  

    /*

    addforlog4j:

classLoggeristhecentralclassinthelog4jpackage.

    wecandomostloggingoperationsbyLoggerexceptconfiguration.

    getLogger(...):

retrievealoggerbyname,ifnotthencreateforit.

    */

    staticLoggerlogger=Logger.getLogger

  (ServerWithLog4j.class.getName());

  

    /**

    *

    *@paramargs

    */

    publicstaticvoidmain(Stringargs[]){

      StringclientRequest=null;

      BufferedReaderreader=null;

      PrintWriterwriter=null;

      ServerSocketserver=null;

      Socketsocket

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 农林牧渔 > 林学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1