Java之Log4j入门 [V512工作室视频]

一.System.out.println的局限性
   
    1.不能在运行时打开或者关闭
   
    2.不能选择包或者类,在运行的时候打开或者关闭
   
    3.输出的信息没有分级
   
    4.只能输出文本信息
   
    5.不能改变输出的位置,只能输出在控制台上.
       
   
二.log4j 基础

    1.官方网址:
        http://logging.apache.org/log4j       
   
    2.log4j的两种配置文件由下面的两个类解析
   
        解析log4j.properties :  PropertyConfigurator.configure( filePath );
       
        解析log4j.xml :  DOMConfigurator.configure( filePath );       

    3.如何得到logger
   
        (1). Logger.getLogger( Test.class );
   
        (2). Logger.getLogger("sql");  --  得到配置文件中设置的sql logger
       
三.例子

    1.一个简单的使用log4j的例子
   
        import org.apache.log4j.*;
       
        public class HelloLog4j{
            private static Logger logger = Logger.getLogger(HelloLog4j.class);
           
            public static void main(String[] args){
                StringBuffer sb = new StringBuffer(); 
                // 记录debug级别的信息
                logger.debug(sb);
                // 记录info级别的信息
                logger.info(sb);
                // 记录warn级别的信息
                logger.warn(sb);
                // 记录error级别的信息
                logger.error(sb);
                // 记录fatal级别的信息
                logger.fatal(sb);
            }
        }
       
        注: 运行这个例子时,需要log4j.properties 或 log4j.xml  --  放在src目录下.

    2.log4j.properties配置文件
   
        log4j.rootLogger=DEBUG,CONSOLE
        #rootLogger: 定义的是默认的logger,如果想自己定义到哪个包下的类的日志,可用log4j.logger.com.gdin...
        #DEBUG: 定义的日志级别是DEBUG,小于DEBUG级别的日志则不会输出
        #CONSOLE: 定义一个Appender, 该appender的具体信息如下

        # 应用于控制台
        log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
        log4j.appender.CONSOLE.Threshold=INFO
        log4j.appender.CONSOLE.Target=System.out
        log4j.appender.CONSOLE.Encoding=GBK
        #log4j.appender.CONSOLE.layout=org.apache.log4j.TTCCLayout
        log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
        log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
        #layout: 定义一个输出样式,有些不用定义它的样式,如TTCCLayout; 有些则需要,如PatternLayout

 

四.log4j核心

    1.Logger  --  Logger完成日志信息的处理
   
        注: Logger可以定义输出的层次和决定信息是否输出
       
            Logger输出的信息有优先级别的:
                ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
               
        注: 定义了哪一个层次,则小于该层次的日志不会输出.   
   
    2.Appender  --  Appender设置日志信息的去向
   
        Appender就是设置日志信息输出到中地方,可以同是指定多个输出目的地.
       
        常用的有以下几个:
            org.apache.log4j.ConsoleAppender (控制台)
           
            org.apache.log4j.FileAppender (文件)
           
            org.apache.log4j.DailyRollingFileAppender (每天产生一个日志文件)
           
            org.apache.log4j.RollingFileAppender (文件大小到达指定尺寸的时候产生一个新的文件)
           
            org.apache.log4j.WriterAppender (将日志信息以串流格式发送到任意指定的地方)
           
            org.apache.log4j.JdbcAppender (将日志信息保存到数据库中)   
   
    3.Layout  --  Layout设置日志信息的输出样式        
             
            org.apache.log4j.HTMLLayout (以HTML表格形式布局)
           
            org.apache.log4j.SimpleLayout (包含日志信息的级别和讯息字符串)
           
            org.apache.log4j..TTCCLayout (包含日志产生的时间,执行者,类别等信息)
           
            org.apache.log4j.PatternLayout (可以灵活地指定布局模式)
           
                样式:
               
                    %p : 输出优先级, 即 DEBUB, INFO, WARN 等  priority
                   
                    %r : 输出自应用启动到输出该日志信息所耗费的毫秒数  runtime
                   
                    %t : 输出产生该日志事件的线程名  thread
                   
                    %f : 输出日志信息所属的类别的类别名 
                   
                    %c : 输出日志信息所属的类的全名  classname
                   
                    %d : 输出日志时间点的日期或时间,指定格式的方式: %d{yyyy-MM-dd HH:mm:ss}  datetime
                   
                    %l : 输出日志事件的发生位置,即输出日志信息的语句排在它所在的类的第几行   line
                    
                    %m : 输出代码中指定的信息,如log(message)中的message   message
                   
                    %n : 输出一个换行符号 (这个一般都要使用,使每个日志信息为一行)     newline
     
    4.配置文件
        log4j.properties
        log4j.xml
       
        (1)log4j.properties配置
            log4j.rootLogger = DEBUG, appender1
            log4j.appender.appender1 = org.apache.log4j.ConsoleAppender
            log4j.appender.appender1.layout = org.apache.log4j.SimpleLayout
           
        (2)RootLogger
        log4j.rootLogger = [lever], appenderName1, appenderName2, ...           
        如果上面的设定将输出等级设为INFO,就表示INFO~FATAL等级的信息将会输出,DEBUG等级的信息就会被忽略
                
        (3)为某个包设定 日志配置           
            log4j.logger.com.gdin = info, appender1
            log4j.logger.com.v512 = debug, appender1, appender2           
           
        (4)设置一个名称的logger
            log4j.logger.myname = debug, appender3           
           
        (5)如果只定义了log4j.logger.com.gdin = info,即定义了它的级别,没有定义它的appender.那么它会使用rootLogger中定义的appender.               
               
        (6).log4j的命名机制
            log4j中定义的命名机制是一棵树的形式,根就是rootLogger名称节点.
            如:Logger.getLogger("com.gdin.uc.TestA"),它会先到配置文档中找名称是com.gdin.uc.TestA的,
                即定义为log4j.logger.com.gdin.uc.TestA的.如果找不到,则找com.gdin.uc的.再找不到就找com.gdin的.再找不到就找com的.再找不到就找rootLogger.
           
            即是说,这棵树就像是java中的包定义一样,所以可以为不再包下的java源文件定义不同的日志机制.
       
五.关于性能影响
   
    1. log4j对程序的运行的性能影响非常小
   
    2. 还可以通过下面的方式,降低性能影响:
        if(logger.isDebugEnabled()){
            logger.debug( "x=" + longTimeRunning() );
        }
   
六.培训 或 视频
   
    1.java软件工程师培训
        http://www.jobedu.com.cn
       
    2.免费视频下载
        http://www.jobedu.com.cn/shipin/video.html
       
        http://www.v512.com
       
    3.论坛答疑
        http://bbs.v512.com

******************************log4j.properties 完整版***********************************

一.log4j.properties 完整版
   
    转载自: http://blog.csdn.net/alex197963/archive/2008/11/07/3244912.aspx
   
        log4j.rootLogger=DEBUG,CONSOLE,DATABASE,FILE
        log4j.addivity.org.apache=true

        # 应用于控制台
        log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
        log4j.appender.CONSOLE.Threshold=INFO
        log4j.appender.CONSOLE.Target=System.out
        log4j.appender.CONSOLE.Encoding=GBK
        log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
        log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

        # 用于数据库
        log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
        log4j.appender.DATABASE.URL=jdbc:oracle:thin:@192.168.0.103:1521:ORCL
        log4j.appender.DATABASE.driver=oracle.jdbc.driver.OracleDriver
        log4j.appender.DATABASE.user=Nation
        log4j.appender.DATABASE.password=1
        log4j.appender.CONSOLE.Threshold=WARN
        log4j.appender.DATABASE.sql=INSERT INTO LOG4J(stamp,thread, infolevel,class,messages)
            VALUES ('%d{yyyy-MM-dd HH:mm:ss}', '%t', '%p', '%l', '%m')
        # INSERT INTO LOG4J (Message) VALUES ('[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n')
        # 写入数据库中的表LOG4J的Message字段中,内容%d(日期)%c: 日志信息所在地(类名)%p:
            日志信息级别%m: 产生的日志具体信息 %n: 输出日志信息换行
        log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
        log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

        # 每天新建日志
        log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
        log4j.appender.A1.File=C:/log4j/log
        log4j.appender.A1.Encoding=GBK
        log4j.appender.A1.Threshold=DEBUG
        log4j.appender.A1.DatePattern='.'yyyy-MM-dd
        log4j.appender.A1.layout=org.apache.log4j.PatternLayout
        log4j.appender.A1.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L : %m%n

        #应用于文件
        log4j.appender.FILE=org.apache.log4j.FileAppender
        log4j.appender.FILE.File=C:/log4j/file.log
        log4j.appender.FILE.Append=false
        log4j.appender.FILE.Encoding=GBK
        log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
        log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

        # 应用于文件回滚
        log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
        log4j.appender.ROLLING_FILE.Threshold=ERROR
        log4j.appender.ROLLING_FILE.File=rolling.log
        log4j.appender.ROLLING_FILE.Append=true
        log4j.appender.CONSOLE_FILE.Encoding=GBK
        log4j.appender.ROLLING_FILE.MaxFileSize=10KB
        log4j.appender.ROLLING_FILE.MaxBackupIndex=1
        log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
        log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

        #自定义Appender
        log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
        log4j.appender.im.host = mail.cybercorlin.net
        log4j.appender.im.username = username
        log4j.appender.im.password = password
        log4j.appender.im.recipient = yyflyons@163.com
        log4j.appender.im.layout=org.apache.log4j.PatternLayout
        log4j.appender.im.layout.ConversionPattern =[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

        #应用于socket
        log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender
        log4j.appender.SOCKET.RemoteHost=localhost
        log4j.appender.SOCKET.Port=5001
        log4j.appender.SOCKET.LocationInfo=true
        # Set up for Log Facter 5
        log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout
        log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t
            [THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n
        # Log Factor 5 Appender
        log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
        log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000

        # 发送日志给邮件
        log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
        log4j.appender.MAIL.Threshold=FATAL
        log4j.appender.MAIL.BufferSize=10
        log4j.appender.MAIL.From=yyflyons@163.com
        log4j.appender.MAIL.SMTPHost=www.wusetu.com
        log4j.appender.MAIL.Subject=Log4J Message
        log4j.appender.MAIL.To=yyflyons@126.com
        log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
        log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

 

******************************log4j.xml配置**********************************

一.log4j.xml

    转载自: http://jan87215.javaeye.com/blog/630518
   
        <?xml version="1.0" encoding="GBK"?>
        <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
        <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
            <!--输出方式是:每天一个日志文件--> 
            <!--设置通道名称是:file,输出方式DailyRollingFileAppender-->
            <appender name="myFile" class="org.apache.log4j.DailyRollingFileAppender"> 

                <!--日志文件路径和文件名称 --> 
                <!--加../在logs,加/在C盘,不加在bin目录 -->
                <!--如果在加载时设置了变量System.setProperty("WebApp", appRoot),可在此取出来${WebApp} -->
                <param name="File" value="../logs/mylog.log"/> 
               
                <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 --> 
                <param name="Append" value="true"/> 
             
                <!-- Rollover at midnight each day --> 
                <!-- e.g. mylog.log.2009-11-25.log -->
                <param name="DatePattern" value="'.'yyyy-MM-dd'.log'"/> 

                <!-- Rollover at the top of each hour  
                <param name="DatePattern" value="'.'yyyy-MM-dd-HH'.log'"/> 
                --> 

                <layout class="org.apache.log4j.PatternLayout"> 
                    <!-- The default pattern: Date Priority [Category] Message\n --> 
                    <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
             
                    <!-- The full pattern: Date MS Priority [Category] (Thread:NDC) Message\n -->
                    <!-- <param name="ConversionPattern" value="%d %-5r %-5p [%c] (%t:%x) %m%n"/> --> 
                </layout>      
            </appender>
         
            <appender name="ERROR_LOG" class="org.apache.log4j.DailyRollingFileAppender"> 
                <errorHandler class="org.apache.log4j.helpers.OnlyOnceErrorHandler"/> 
                <param name="File" value="error.log"/> 
                <param name="Append" value="true"/> 
                <!-- 指定日志输出级别 -->
                <param name="Threshold" value="INFO"/> 
                <param name="DatePattern" value="'.'yyyy-MM-dd'.log'"/> 
                <layout class="org.apache.log4j.PatternLayout"> 
                <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/> 
                </layout> 
            </appender>
           
            <!-- level:是日记记录的优先级,优先级由高到低分为   
                 OFF ,FATAL ,ERROR ,WARN ,INFO ,DEBUG ,ALL。  
                 Log4j建议只使用FATAL ,ERROR ,WARN ,INFO ,DEBUG这四个级别。--> 

            <!-- 指定logger的设置,additivity指示是否叠加输出log,如果是false,
                在DsErrorLog logger中日志不会被其它logger满足条件的logger(比如root)输出 -->  
               
            <!-- 将名称为DSErrorLog的logger,输出到“EEROR_LOG”的appender  
                 所谓logger的名字也就是,在定义Logger时,构造函数的参数  
                  Logger log = Logger.getLogger("DSErrorLog");  --> 
            <logger name="DSErrorLog" additivity="false"> 
                <level class="org.apache.log4j.Level" value="DEBUG"/> 
                <appender-ref ref="ERROR_LOG"/> 
            </logger> 
                  
            <!--输出指定类包中的日志,比如想输出  
                Hibernate运行中生成的SQL语句,可作如下设置 --> 
            <category name="org.hibernate.SQL"> 
                <priority value="DEBUG"/> 
                <!-- 如果指定一个appender,这些log将被输出到指定的appender  
                    如:<appender-ref ref="myFile"/>否则将作用于所有的appender --> 
           </category> 
                      
            <!--根默认会自动构建一个 root,输出INFO级别的日志到控制台,供logger继承 -->      
            <root>      
                <priority value ="DEBUG"/>      
                <appender-ref ref="myConsole"/>      
                <appender-ref ref="myFile"/>         
            </root>         
        </log4j:configuration> 


****************************************一个比较有用的log4j应用 ***************************************8

一.log4j.xml配置实现

    转载自: http://flying3615.blog.163.com/blog/static/2830344720098119265985/

    1.先写一个Servlet的listener,用来监听服务启动,并自动解析log4j.xml文件

        代码如下:

            import javax.servlet.ServletContextEvent;
            import javax.servlet.ServletContextListener;

            import org.apache.log4j.LogManager;
            import org.apache.log4j.PropertyConfigurator;
            import org.apache.log4j.xml.DOMConfigurator;

            public class Log4jConfigListener implements ServletContextListener{
            
                public static final String CONFIG_LOCATION_PARAM = "log4jConfigLocation";
                public static final String XML_FILE_EXTENSION = ".xml";

                public void contextDestroyed(ServletContextEvent event) {
                    LogManager.shutdown();
                }

                public void contextInitialized(ServletContextEvent event) {
                    String location = event.getServletContext().getInitParameter(CONFIG_LOCATION_PARAM);
                    if (location != null) {
                        if (!location.startsWith("/")) {
                            location = "/" + location;
                        }
                        location = event.getServletContext().getRealPath(location);

                        //如果是xml结尾就用DOM解析,否则就用properties解析
                        if (location.toLowerCase().endsWith(XML_FILE_EXTENSION)) {
                            DOMConfigurator.configure(location);
                        }else {
                            PropertyConfigurator.configure(location);
                        }
                    }
                }
            }


        2.再写个util类,用来生成所要的不同类型的日志

            代码如下:

                package com.zhaopin.util;

                import org.apache.log4j.Logger;

                public class Log4jUtil {
                
                 public static Logger getSQLLogger(){
                  return Logger.getLogger("sql");
                 }
                
                 public static Logger getBusinessLogger(){
                  return Logger.getLogger("business");
                 }
                
                 public static Logger getSimpleErrorLogger(){
                  return Logger.getLogger("simpleError");
                 }
                
                 public static Logger getNormalErrorLogger(){
                  return Logger.getLogger("normalError");
                 }

                }

 
        3.下面开始写配置文件,先要在web.xml下添加信息:

            <context-param>
                <param-name>log4jConfigLocation</param-name>
                <param-value>/WEB-INF/Log4j.xml</param-value>
            </context-param>
            
            <!-- 加载log4j配置文件 -->
            <listener>
                <listener-class>Log4jConfigListener</listener-class>
            </listener>

 

        4.最重要的log4j.xml的配置信息如下:

            <?xml version="1.0" encoding="GBK"?>
            <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
            <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
            
                <!-- 控制台输出 -->
                <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
                    <param name="target" value="System.out"/>
                    <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c] (%C:%L) - %m%n"/>
                    </layout>
                </appender>

                <!-- SQL类日志 -->
                <appender name="sql" class="org.apache.log4j.DailyRollingFileAppender">
                    <param name="File" value="/usr/local/tomcat/logs/testlog4j.sql.log"/>
                    <param name="Append" value="true"/>
                   
                    <!-- name="DatePattern", 配置这条信息是让日志每天自动生成,名字尾部追加日期格式,
                        第一天生成的日志需第二天才能看到log可以通过更改系统时间来看日志的输出
                    -->
                    <param   name="DatePattern"   value="'.'yyyy-MM-dd"/>
                    <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c] (%C:%L) - %m%n"/>
                    </layout>
                </appender>
                
                <!-- 业务类日志 -->
                <appender name="business" class="org.apache.log4j.DailyRollingFileAppender">
                    <param name="File" value="/usr/local/tomcat/logs/testlog4j.business.log"/>
                    <param name="Append" value="true"/>
                    <param   name="DatePattern"   value="'.'yyyy-MM-dd"/>
                    <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c] (%C:%L) - %m%n"/>
                    </layout>
                </appender>
                
                <!-- 不带执行轨迹错误日志 -->
                <appender name="simpleError" class="org.apache.log4j.DailyRollingFileAppender">
                    <param name="File" value="/usr/local/tomcat/logs/testlog4j.error.simple.log"/>
                    <param name="Append" value="true"/>
                    <param   name="DatePattern"   value="'.'yyyy-MM-dd"/>
                    <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c] (%C:%L) - %m%n"/>
                    </layout>
                </appender>
                
                <!-- 带执行轨迹错误日志 -->
                <appender name="normalError" class="org.apache.log4j.DailyRollingFileAppender">
                    <param name="File" value="/usr/local/tomcat/logs/testlog4j.error.normal.log"/>
                    <param name="Append" value="true"/>
                    <param   name="DatePattern"   value="'.'yyyy-MM-dd"/>
                    <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c] (%C:%L) - %m%n"/>
                    </layout>
                </appender>
                    
                <!-- 下面定义logger -->
                <logger name="sql" additivity="true">
                    <priority value="info"/>
                    <appender-ref ref="sql"/>
                </logger>
               
                <logger name="business" additivity="true">
                    <priority value="info"/>
                    <appender-ref ref="simpleError"/>
                </logger>
               
                <logger name="simpleError" additivity="true">
                    <priority value="info"/>
                    <appender-ref ref="simpleError"/>
                </logger>
               
                <logger name="normalError" additivity="true">
                    <priority value="info"/>
                    <appender-ref ref="normalError"/>
                </logger>
               
                <root>   
                    <appender-ref ref="STDOUT"/>  
                    <priority value="info"/>
                </root> 
            </log4j:configuration>


        5.在程序中应用时需要编写如下代码:

            Log4jUtil.getBusinessLogger().info("message!");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值