<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆-71  評(píng)論-4  文章-0  trackbacks-0
    1. 概述

    1.1. 背景
       在應(yīng)用程序中添加日志記錄總的來(lái)說(shuō)基于三個(gè)目的:監(jiān)視代碼中變量的變化情況,周期性的記錄到文件中供其他應(yīng)用進(jìn)行統(tǒng)計(jì)分析工作;跟蹤代碼運(yùn)行時(shí)軌跡,作為日后審計(jì)的依據(jù);擔(dān)當(dāng)集成開發(fā)環(huán)境中的調(diào)試器的作用,向文件或控制臺(tái)打印代碼的調(diào)試信息。

       最普通的做法就是在代碼中嵌入許多的打印語(yǔ)句,這些打印語(yǔ)句可以輸出到控制臺(tái)或文件中,比較好的做法就是構(gòu)造一個(gè)日志操作類來(lái)封裝此類操作,而不是讓一系列的打印語(yǔ)句充斥了代碼的主體。

    1.2. Log4j簡(jiǎn)介

      在強(qiáng)調(diào)可重用組件開發(fā)的今天,除了自己從頭到尾開發(fā)一個(gè)可重用的日志操作類外,Apache為我們提供了一個(gè)強(qiáng)有力的日志操作包-Log4j。  Log4j是Apache的一個(gè)開放源代碼項(xiàng)目,通過(guò)使用Log4j,我們可以控制日志信息輸送的目的地是控制臺(tái)、文件、GUI組件、甚至是套接口服務(wù)器、NT的事件記錄器、UNIX Syslog守護(hù)進(jìn)程等;我們也可以控制每一條日志的輸出格式;通過(guò)定義每一條日志信息的級(jí)別,我們能夠更加細(xì)致地控制日志的生成過(guò)程。最令人感興趣的就是,這些可以通過(guò)一個(gè)配置文件來(lái)靈活地進(jìn)行配置,而不需要修改應(yīng)用的代碼。

       此外,通過(guò)Log4j其他語(yǔ)言接口,您可以在C、C++、.Net、PL/SQL程序中使用Log4j,其語(yǔ)法和用法與在Java程序中一樣,使得多語(yǔ)言分布式系統(tǒng)得到一個(gè)統(tǒng)一一致的日志組件模塊。而且,通過(guò)使用各種第三方擴(kuò)展,您可以很方便地將Log4j集成到J2EE、JINI甚至是SNMP應(yīng)用中。

       本文介紹的Log4j版本是1.2.3。作者試圖通過(guò)一個(gè)簡(jiǎn)單的客戶/服務(wù)器Java程序例子對(duì)比使用與不使用Log4j1.2.3的差別,并詳細(xì)講解了在實(shí)踐中最常使用Log4j的方法和步驟。在強(qiáng)調(diào)可重用組件開發(fā)的今天,相信Log4j將會(huì)給廣大的設(shè)計(jì)開發(fā)人員帶來(lái)方便。加入到Log4j的隊(duì)伍來(lái)吧!

    2. 一個(gè)簡(jiǎn)單的例子

       我們先來(lái)看一個(gè)簡(jiǎn)單的例子,它是一個(gè)用Java實(shí)現(xiàn)的客戶/服務(wù)器網(wǎng)絡(luò)程序。剛開始我們不使用Log4j,而是使用了一系列的打印語(yǔ)句,然后我們將使用Log4j來(lái)實(shí)現(xiàn)它的日志功能。這樣,大家就可以清楚地比較出前后兩個(gè)代碼的差別。

    2.1. 不使用Log4j

    2.1.1. 客戶程序

    package log4j ;

    import java.io.* ;
    import java.net.* ;

    /**
     *
     * <p> Client Without Log4j </p>
     * <p> Description: a sample with log4j</p>
     * @version 1.0
     */
    public class ClientWithoutLog4j {

        /**
         *
         * @param args
         */
        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. 服務(wù)器程序

    package log4j ;

    import java.util.* ;
    import java.io.* ;
    import java.net.* ;

    /**
     *
     * <p> Server Without Log4j </p>
     * <p> Description: a sample with log4j</p>
     * @version 1.0
     */
    public class ServerWithoutLog4j {

        final static int SERVER_PORT = 8001 ; // this server's port

        /**
         *
         * @param args
         */
        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 ;

    /**
     *
     * <p> Client With Log4j </p>
     * <p> Description: a sample with log4j</p>
     * @version 1.0
     */
    public class ClientWithLog4j {

        /*
        add for log4j: class Logger is the central class in the log4j package.
        we can do most logging operations by Logger except configuration.
        getLogger(...): retrieve a logger by name, if not then create for it.
        */
        static Logger logger = Logger.getLogger(ClientWithLog4j.class.getName () ) ;

        /**
         *
         * @param args : configuration file name
         */
        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 ;

            /*
            add for log4j: class BasicConfigurator can quickly configure the package.
            print the information to console.
            */
            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. 服務(wù)器程序

    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 ;

    /**
     *
     * <p> Server With Log4j </p>
     * <p> Description: a sample with log4j</p>
     * @version 1.0
     */
    public class ServerWithLog4j {

        final static int SERVER_PORT = 8001 ; // this server's port

        /*
        add for log4j: class Logger is the central class in the log4j package.
        we can do most logging operations by Logger except configuration.
        getLogger(...): retrieve a logger by name, if not then create for it.
        */
        static Logger logger = Logger.getLogger 
    ( ServerWithLog4j.class.getName () ) ;

        /**
         *
         * @param args
         */
        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 ;

            /*
            add for log4j: class BasicConfigurator can quickly configure the package.
            print the information to console.
            */
            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. 服務(wù)器程序配置文件

    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. 比較

       比較這兩個(gè)應(yīng)用可以看出,采用Log4j進(jìn)行日志操作的整個(gè)過(guò)程相當(dāng)簡(jiǎn)單明了,與直接使用System.out.println語(yǔ)句進(jìn)行日志信息輸出的方式相比,基本上沒(méi)有增加代碼量,同時(shí)能夠清楚地理解每一條日志信息的重要程度。通過(guò)控制配置文件,我們還可以靈活地修改日志信息的格式,輸出目的地等等方面,而單純依靠System.out.println語(yǔ)句,顯然需要做更多的工作。

    下面我們將以前面使用Log4j的應(yīng)用作為例子,詳細(xì)講解使用Log4j的主要步驟。

    3. Log4j基本使用方法

        Log4j由三個(gè)重要的組件構(gòu)成:日志信息的優(yōu)先級(jí),日志信息的輸出目的地,日志信息的輸出格式。日志信息的優(yōu)先級(jí)從高到低有ERROR、WARN、INFO、DEBUG,分別用來(lái)指定這條日志信息的重要程度;日志信息的輸出目的地指定了日志將打印到控制臺(tái)還是文件中;而輸出格式則控制了日志信息的顯示內(nèi)容。

    3.1.定義配置文件

        其實(shí)您也可以完全不使用配置文件,而是在代碼中配置Log4j環(huán)境。但是,使用配置文件將使您的應(yīng)用程序更加靈活。Log4j支持兩種配置文件格式,一種是XML格式的文件,一種是Java特性文件(鍵=值)。下面我們介紹使用Java特性文件做為配置文件的方法:

    配置根Logger,其語(yǔ)法為:

    log4j.rootLogger = [ level ] , appenderName, appenderName, …
         其中,level 是日志記錄的優(yōu)先級(jí),分為OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL或者您定義的級(jí)別。Log4j建議只使用四個(gè)級(jí)別,優(yōu)先級(jí)從高到低分別是ERROR、WARN、INFO、DEBUG。通過(guò)在這里定義的級(jí)別,您可以控制到應(yīng)用程序中相應(yīng)級(jí)別的日志信息的開關(guān)。比如在這里定義了INFO級(jí)別,則應(yīng)用程序中所有DEBUG級(jí)別的日志信息將不被打印出來(lái)。appenderName就是指定日志信息輸出到哪個(gè)地方。您可以同時(shí)指定多個(gè)輸出目的地。

    配置日志信息輸出目的地Appender,其語(yǔ)法為

    log4j.appender.appenderName = fully.qualified.name.of.appender.class
    log4j.appender.appenderName.option1 = value1

    log4j.appender.appenderName.option = valueN
    其中,Log4j提供的appender有以下幾種:
    org.apache.log4j.ConsoleAppender(控制臺(tái)),
    org.apache.log4j.FileAppender(文件),
    org.apache.log4j.DailyRollingFileAppender(每天產(chǎn)生一個(gè)日志文件),
    org.apache.log4j.RollingFileAppender(文件大小到達(dá)指定尺寸的時(shí)候產(chǎn)生一個(gè)新的文件),
    org.apache.log4j.WriterAppender(將日志信息以流格式發(fā)送到任意指定的地方)

    配置日志信息的格式(布局),其語(yǔ)法為:

    log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
    log4j.appender.appenderName.layout.option1 = value1

    log4j.appender.appenderName.layout.option = valueN
    其中,Log4j提供的layout有以下幾種:
    org.apache.log4j.HTMLLayout(以HTML表格形式布局),
    org.apache.log4j.PatternLayout(可以靈活地指定布局模式),
    org.apache.log4j.SimpleLayout(包含日志信息的級(jí)別和信息字符串),
    org.apache.log4j.TTCCLayout(包含日志產(chǎn)生的時(shí)間、線程、類別等等信息)

    3.2.在代碼中使用Log4j

    下面將講述在程序代碼中怎樣使用Log4j。

    3.2.1.得到記錄器

    使用Log4j,第一步就是獲取日志記錄器,這個(gè)記錄器將負(fù)責(zé)控制日志信息。其語(yǔ)法為:
    public static Logger getLogger( String name),
    通過(guò)指定的名字獲得記錄器,如果必要的話,則為這個(gè)名字創(chuàng)建一個(gè)新的記錄器。Name一般取本類的名字,比如:
    static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () ) ;
    3.2.2.讀取配置文件

        當(dāng)獲得了日志記錄器之后,第二步將配置Log4j環(huán)境,其語(yǔ)法為:
    BasicConfigurator.configure (): 自動(dòng)快速地使用缺省Log4j環(huán)境。
    PropertyConfigurator.configure ( String configFilename) :讀取使用Java的特性文件編寫的配置文件。
    DOMConfigurator.configure ( String filename ) :讀取XML形式的配置文件。

    3.2.3.插入記錄信息(格式化日志信息)

        當(dāng)上兩個(gè)必要步驟執(zhí)行完畢,您就可以輕松地使用不同優(yōu)先級(jí)別的日志記錄語(yǔ)句插入到您想記錄日志的任何地方,其語(yǔ)法如下:

    Logger.debug ( Object message ) ;
    Logger.info ( Object message ) ;
    Logger.warn ( Object message ) ;
    Logger.error ( Object message ) ;

    4. 參考資料

    如果您想更深入地了解Log4j,請(qǐng)經(jīng)常訪問(wèn)下面提及的相關(guān)鏈接。
    Log4j項(xiàng)目主頁(yè)------------------------------------------------------www.log4j.org
    Log4j FAQ -------------------------------------------------------www.log4j.org/log4j/faq.html

    posted on 2006-01-12 12:40 zjw_albert 閱讀(114) 評(píng)論(0)  編輯  收藏

    只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


    網(wǎng)站導(dǎo)航:
     
    主站蜘蛛池模板: 一个人看的在线免费视频| 亚洲国产精品一区二区第一页免 | 中文字幕日本人妻久久久免费| 2020国产精品亚洲综合网| 亚洲VA中文字幕无码毛片| 亚洲AⅤ无码一区二区三区在线 | 亚洲第一页中文字幕| 日韩亚洲变态另类中文| 国产免费人成在线视频| 亚洲第一成年免费网站| 日本h在线精品免费观看| 在线人成免费视频69国产| 一级毛片免费播放男男| 久久精品熟女亚洲av麻豆| 国产亚洲玖玖玖在线观看| 亚洲国产电影在线观看| 亚洲人成网www| 亚洲AV日韩精品久久久久| 国产亚洲精午夜久久久久久| 国产jizzjizz免费视频| 国产又粗又长又硬免费视频| 成年性午夜免费视频网站不卡| 国产h肉在线视频免费观看| 免费A级毛片无码A∨| 99精品一区二区免费视频| 麻豆精品成人免费国产片| 久久久久久免费一区二区三区| a毛片在线还看免费网站| 日韩av无码免费播放| 四虎影视无码永久免费| 97无码人妻福利免费公开在线视频| yellow视频免费在线观看| 国产日韩AV免费无码一区二区三区| 国产va免费精品| 国产黄在线播放免费观看| 99久久婷婷免费国产综合精品| 精品国产呦系列在线观看免费| 一级特黄录像免费播放肥| 成全在线观看免费观看大全| 久久国产乱子伦精品免费不卡| 91高清免费国产自产拍2021|