如何封装log4j示例代码

 

log.java 封装log4j,在日志中加入调用类名和事件ID/

package com.abcd.monitor.log;
import org.apache.log4j.Logger;
import com.ccae.monitor.log.Log;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.InetAddress;


//import org.apache.log4j.PropertyConfigurator;
/*
 * 实现日志文件的生成和定制
 * @Author 
 */
public class Log {
  
   
 protected Logger loger;
    //将Log类封装成单实例的模式,独立于其他类。以后要用到日志的地方只要获得Log的实例就可以方便使用  
    private static Log log;  
    //构造函数,用于初始化Logger配置需要的属性  
    private Log(Logger log4jLogger)  
    {  
        //获得当前目录路径  
        //String filePath=this.getClass().getResource("/").getPath();  
        //找到log4j.properties配置文件所在的目录(已经创建好)  
        //filePath=filePath.substring(1).replace("bin", "src");  
        //获得日志类logger的实例  
        //loger=Logger.getLogger(this.getClass());
        loger = log4jLogger;
       
        //logger所需的配置文件路径  
       // PropertyConfigurator.configure(filePath+"log4j.xml");//"log4j.properties");  

    }  
   
  /*  public static Log getLoger()  
    {  
        if(log!=null)  
            return log;  
        else 
            return new Log();  
    }   */
   
  
   
   
   /* *//**
     * 构造方法,初始化Log4j的日志对象
     *//*
    private Logger(org.apache.log4j.Logger log4jLogger) {
        logger = log4jLogger;
    }
*/
    /**
     * 获取构造器,根据类初始化Logger对象
     *
     * @param Class Class对象
     * @return Logger对象
     */
    public static Log getLogger(Class classObject) {
     if(log!=null)  
            return log;  
        else 
            return new Log(org.apache.log4j.Logger.getLogger(classObject));
       // return new Log(org.apache.log4j.Logger.getLogger(classObject));
    }

    /**
     * 获取构造器,根据类名初始化Logger对象
     *
     * @param String 类名字符串
     * @return Logger对象
     */
   /* public static Logger getLogger(String loggerName) {
        return new Logger(org.apache.log4j.Logger.getLogger(loggerName));
    }*/

  
   
    //
   
    /*
     * 该事件ID包含当前时间和主机IP,是标示日志时间的唯一符
     * @see com.ccae.monitor.log.ILogInfor#eventID()
     * @

     */
     protected String eventID() {
      // 获取当前时间
      //如果不需要格式,可直接用dt,dt就是当前系统时间
      Date dt=new Date();
      //设置显示格式,24小时制
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String nowTime= df.format(dt);//用DateFormat的format()方法在dt中获取并以yyyy/MM/dd HH:mm:ss格式显示
      
      //获取当前IP
                 //String nowIP=OSUtil.getLocalIP();
            String nowIP;
            try{
             InetAddress addr = InetAddress.getLocalHost();
             nowIP = addr.getHostAddress();
             //System.out.println(nowIP);
            }
            catch(Exception ex){
             nowIP = "";
            }        
                nowTime=nowTime.replaceAll("/","");
                nowTime=nowTime.replaceAll(" ","");
                nowTime=nowTime.replaceAll(":","");
                nowIP=nowIP.replace(".","");
                String nowID=nowTime+nowIP;
                return nowID;
     }

     

     public void setDebug(String source,String UserName,String KeyWord,String Content) {
      // TODO Auto-generated method stub
     // Log log=Log.getLoger(this.getClass()); 
      
      //ILogInfor o=new LogInfor();
      String message=" "+source+" "+KeyWord+" "+Content+" "+eventID()+" ";
      
      //DOMConfigurator.configure("xmllog4jconfig_normal.xml");
      loger.debug(message);
      
      
     }

     

     public void setFatal(String source,String UserName,String KeyWord,String Content) {
      // TODO Auto-generated method stub
     // Log log=Log.getLoger(this.getClass()); 
      
      //ILogInfor o=new LogInfor();
      String message1=" "+source+" "+KeyWord+" "+Content+" "+eventID()+" ";
      
      /*String ls=System.getProperty("line.separator");
      String message2=ls+"<source>"+source+"</source>"+ls+"<ClassName>"+nowClass+"</ClassName>"+ls+"<KeyWord>"+KeyWord+"</KeyWord>"+ls+"<content>"+Content+"</content>"+ls+"<EventID>"+eventID()+"<EventID>"+ls;
      */
      //DOMConfigurator.configure("xmllog4jconfig_normal.xml");
      loger.fatal(message1);
      /*DOMConfigurator.configure("xmllog4jconfig_error.xml");
      loger.fatal(message2);*/
      
     }

     public void setInfo(String source,String UserName,String KeyWord,String Content) {
      // TODO Auto-generated method stub
     // Log log=Log.getLoger(this.getClass()); 
      
      //ILogInfor o=new LogInfor();
      String message=" "+source+" "+KeyWord+" "+Content+" "+eventID()+" ";
      
      //DOMConfigurator.configure("xmllog4jconfig_normal.xml");
      loger.info(message);
     }

     public void setWarn(String source,String UserName,String KeyWord,String Content) {
      // TODO Auto-generated method stub
     // Log log=Log.getLoger(this.getClass()); 
      
      //ILogInfor o=new LogInfor();
      String message=" "+source+" "+KeyWord+" "+Content+" "+eventID()+" ";
      
      //DOMConfigurator.configure("xmllog4jconfig_normal.xml");
      loger.warn(message);
     }

/*
 * @params: String source,String UserName,String KeyWord,String Content
 */

     public void setError(String source,String UserName,String KeyWord,String Content) {
      // TODO Auto-generated method stub
    //  Log log=Log.getLoger(this.getClass()); 
      //String ls=System.getProperty("line.separator");
      
      //ILogInfor o=new LogInfor();
      String message1=" "+source+" "+KeyWord+" "+Content+" "+eventID()+" ";
      
      /*String ls=System.getProperty("line.separator");
      String message2=ls+"<source>"+source+"</source>"+ls+"<ClassName>"+nowClass+"</ClassName>"+ls+"<KeyWord>"+KeyWord+"</KeyWord>"+ls+"<content>"+Content+"</content>"+ls+"<EventID>"+eventID()+"<EventID>"+ls;
      */
      //DOMConfigurator.configure("xmllog4jconfig_normal.xml");
      //loger.info(message1);
      loger.error(message1);
      /*DOMConfigurator.configure("xmllog4jconfig_error.xml");
      loger.error(message2);*/
      
      
     }

}

 

 

测试类///

 

package com.abcd.monitor.log;
//import org.apache.log4j.Logger;
//import org.apache.log4j.PropertyConfigurator;
import com.abcd.monitor.log.Log;

/*
 * 日志测试类
 * @Author */
public class Main {
 public static void main(String args[])   throws Exception
    {  
  
        Log log=Log.getLogger(Main.class); //write once,use everywhere :) 
       /* LogConfiginitialization lct=new LogConfiginitialization();
        lct.init();*/
  //ILogInfor mylog=new LogInfor();
       
      
        try 
        {  
            //引发异常  
            int a=2/0;  
        }catch(Exception e)  
        {  
            //控制台打印异常信息  
           // e.printStackTrace();  
            //写入到日志文件  
          //  log.loger.error("此处加入您自定义的错误信息内容", e);
        // log.loger.error("error error error,是不是XML格式?");
         
          //以XML方式读配置文件。
            /*DOMConfigurator.configure("xmllog4jconfig_normal.xml");*/
           // log.loger.error("您可以定义自己的日志信息",e);
            //系统编号不+名字+日志关键字
           /* log.loger .error("002"+"administrator"+"日志关键字",e);
           
            DOMConfigurator.configure("xmllog4jconfig_error.xml");
            log.loger.error("002"+"administrator"+"日志关键字"+,e);
            */
         
           
         /*DOMConfigurator.configure("xmllog4jconfig.xml");
            log.loger.error("error error error",e);*/
           
           
           
            //以XML方式读到配置文件。
            /*DOMConfigurator.configure("xmllog4jconfig_normal.xml");
            log.loger.warn("warn ",e);*/
          /*  DOMConfigurator.configure("xmllog4jconfig_normal.xml");
            log.loger.info("a test ,just a test ");*/
           
         /*String message="002"+"administrator"+"keyword"+e;
         mylog.SetError(message);//"002"+"administrator"+"keyword"+e);
*/         
         //System.out.println(log.getClass().toString());
         
         
         //String source,String UserName,String KeyWord,String Content
         /*//log.setError("002",Main.class.toString(), "adminstrator", "您任意定制的关键字", e.toString());
*/         
         log.setError("002", "adminstrator", "您任意定制的关键字", e.toString());

//其实就这么一行~~~~~舍不得删注释,是因为那是我的"代码进化"过程:)
        }  
       
      
       
       
       /* private static final Logger log = Logger.getLogger(TestLog.class);

        log.error("出错.");
          log.warn("AudioConcat.main(): WARNING: AudioFormats don't match");*/

    }  

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值