正确 配置和使用 的 log4j.properties的 方法

http://plane.javaeye.com/blog/288886

 

Java代码 复制代码
  1.      
  2. # Set log levels #   
  3. log4j.rootLogger = DEBUG, Console, LogFile, ErrorFile   
  4.   
  5. # Output the log info to the Java Console #   
  6. log4j.appender.Console = org.apache.log4j.ConsoleAppender   
  7. log4j.appender.Console.Target = System.out   
  8. log4j.appender.Console.ImmediateFlush = true  
  9. log4j.appender.Console.Threshold = DEBUG   
  10. log4j.appender.Console.layout = org.apache.log4j.PatternLayout   
  11. log4j.appender.Console.layout.ConversionPattern = <%-d{yyyy-MM-dd HH:mm:ss}> <%t> %l %n<%p> %m%n%n   
  12.   
  13. # Save the log info to the log file #   
  14. log4j.appender.LogFile = org.apache.log4j.RollingFileAppender   
  15. log4j.appender.LogFile.File = logs/log.log   
  16. log4j.appender.LogFile.Append = true  
  17. log4j.appender.LogFile.ImmediateFlush = false  
  18. log4j.appender.LogFile.MaxFileSize = 8MB   
  19. log4j.appender.LogFile.MaxBackupIndex = 256  
  20. log4j.appender.LogFile.Threshold = INFO   
  21. log4j.appender.LogFile.layout = org.apache.log4j.PatternLayout   
  22. log4j.appender.LogFile.layout.ConversionPattern = <%-d{yyyy-MM-dd HH:mm:ss}> <%t> %l %n<%p> %m%n%n   
  23.   
  24. # Save the error info to the error file. A file one day. #   
  25. log4j.appender.ErrorFile = org.apache.log4j.DailyRollingFileAppender   
  26. log4j.appender.ErrorFile.File = logs/error.log   
  27. log4j.appender.ErrorFile.Append = true  
  28. log4j.appender.ErrorFile.ImmediateFlush = false  
  29. log4j.appender.ErrorFile.Threshold = ERROR   
  30. log4j.appender.ErrorFile.layout = org.apache.log4j.PatternLayout   
  31. log4j.appender.ErrorFile.layout.ConversionPattern = <%-d{yyyy-MM-dd HH:mm:ss}> <%t> %l %n<%p> %m%n%n  
  
# Set log levels #
log4j.rootLogger = DEBUG, Console, LogFile, ErrorFile

# Output the log info to the Java Console #
log4j.appender.Console = org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target = System.out
log4j.appender.Console.ImmediateFlush = true
log4j.appender.Console.Threshold = DEBUG
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern = <%-d{yyyy-MM-dd HH:mm:ss}> <%t> %l %n<%p> %m%n%n

# Save the log info to the log file #
log4j.appender.LogFile = org.apache.log4j.RollingFileAppender
log4j.appender.LogFile.File = logs/log.log
log4j.appender.LogFile.Append = true
log4j.appender.LogFile.ImmediateFlush = false
log4j.appender.LogFile.MaxFileSize = 8MB
log4j.appender.LogFile.MaxBackupIndex = 256
log4j.appender.LogFile.Threshold = INFO
log4j.appender.LogFile.layout = org.apache.log4j.PatternLayout
log4j.appender.LogFile.layout.ConversionPattern = <%-d{yyyy-MM-dd HH:mm:ss}> <%t> %l %n<%p> %m%n%n

# Save the error info to the error file. A file one day. #
log4j.appender.ErrorFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.ErrorFile.File = logs/error.log
log4j.appender.ErrorFile.Append = true
log4j.appender.ErrorFile.ImmediateFlush = false
log4j.appender.ErrorFile.Threshold = ERROR
log4j.appender.ErrorFile.layout = org.apache.log4j.PatternLayout
log4j.appender.ErrorFile.layout.ConversionPattern = <%-d{yyyy-MM-dd HH:mm:ss}> <%t> %l %n<%p> %m%n%n


Java代码 复制代码
  1. import java.io.IOException;   
  2. import java.io.InputStream;   
  3. import java.util.Properties;   
  4.   
  5. import org.apache.log4j.BasicConfigurator;   
  6. import org.apache.log4j.Level;   
  7. import org.apache.log4j.LogManager;   
  8. import org.apache.log4j.Logger;   
  9. import org.apache.log4j.Priority;   
  10. import org.apache.log4j.PropertyConfigurator;   
  11.   
  12. public class EncapsulationLog4J    
  13. {   
  14.     public static final String PROFILE = "log4j.properties";   
  15.     private static EncapsulationLog4J encapsulationLog4J;   
  16.     static    
  17.     {   
  18.         encapsulationLog4J = new EncapsulationLog4J();   
  19.     }   
  20.     private Logger log4j;   
  21.     private EncapsulationLog4J()   
  22.     {   
  23.         log4j = LogManager.getLogger(EncapsulationLog4J.class);   
  24.         Properties pro = new Properties();   
  25.         InputStream is = getClass().getResourceAsStream(PROFILE);   
  26.         try    
  27.         {   
  28.             pro.load(is);   
  29.         } catch (IOException e)    
  30.         {   
  31.             BasicConfigurator.configure();   
  32.             e.printStackTrace();   
  33.         }   
  34.         PropertyConfigurator.configure(pro);   
  35.     }   
  36.        
  37.     public void log(String level,Object msg,Throwable e)   
  38.     {   
  39.         if(null!=log4j)   
  40.         {   
  41.             log4j.log((Priority)Level.toLevel(level), msg, e);   
  42.         }   
  43.     }   
  44.        
  45.     public void log(String level,Object msg)   
  46.     {   
  47.         log(level,msg,null);   
  48.     }   
  49.        
  50.     public void log(String level,Throwable e)   
  51.     {   
  52.         log(level,null,e);   
  53.     }   
  54.        
  55.     public static EncapsulationLog4J getInstance()   
  56.     {   
  57.         return encapsulationLog4J;   
  58.     }   
  59.        
  60.        
  61.        
  62.   
  63. }  
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.PropertyConfigurator;

public class EncapsulationLog4J 
{
	public static final String PROFILE = "log4j.properties";
    private static EncapsulationLog4J encapsulationLog4J;
    static 
    {
    	encapsulationLog4J = new EncapsulationLog4J();
    }
    private Logger log4j;
    private EncapsulationLog4J()
    {
    	log4j = LogManager.getLogger(EncapsulationLog4J.class);
    	Properties pro = new Properties();
    	InputStream is = getClass().getResourceAsStream(PROFILE);
    	try 
    	{
			pro.load(is);
		} catch (IOException e) 
		{
			BasicConfigurator.configure();
			e.printStackTrace();
		}
    	PropertyConfigurator.configure(pro);
    }
    
    public void log(String level,Object msg,Throwable e)
    {
    	if(null!=log4j)
    	{
    		log4j.log((Priority)Level.toLevel(level), msg, e);
    	}
    }
    
    public void log(String level,Object msg)
    {
    	log(level,msg,null);
    }
    
    public void log(String level,Throwable e)
    {
    	log(level,null,e);
    }
    
    public static EncapsulationLog4J getInstance()
    {
    	return encapsulationLog4J;
    }
    
    
	

}


Java代码 复制代码
  1. public class Log    
  2. {   
  3.     private static EncapsulationLog4J log = EncapsulationLog4J.getInstance();   
  4.        
  5.     public static void logError(String msg)   
  6.     {   
  7.         log.log("ERROR", msg);   
  8.     }   
  9.        
  10.     public static void logError(Throwable e)   
  11.     {   
  12.         log.log("ERROR", e);   
  13.     }   
  14.        
  15.     public static void logWarn(String msg)   
  16.     {   
  17.         log.log("WARN", msg);   
  18.     }   
  19.        
  20.     public static void logWarn(Throwable e)   
  21.     {   
  22.         log.log("WARN", e);   
  23.     }   
  24.        
  25.     public static void logInfo(String msg)   
  26.     {   
  27.         log.log("INFO", msg);   
  28.     }   
  29.        
  30.     public static void logInfo(Throwable e)   
  31.     {   
  32.         log.log("INFO", e);   
  33.     }   
  34.        
  35.     public static void logDebug(String msg)   
  36.     {   
  37.         log.log("DEBUG", msg);   
  38.     }   
  39.        
  40.     public static void logDebug(Throwable e)   
  41.     {   
  42.         log.log("DEBUG", e);   
  43.     }   
  44.        
  45. }  
public class Log 
{
	private static EncapsulationLog4J log = EncapsulationLog4J.getInstance();
	
	public static void logError(String msg)
	{
		log.log("ERROR", msg);
	}
	
	public static void logError(Throwable e)
	{
		log.log("ERROR", e);
	}
	
	public static void logWarn(String msg)
	{
		log.log("WARN", msg);
	}
	
	public static void logWarn(Throwable e)
	{
		log.log("WARN", e);
	}
	
	public static void logInfo(String msg)
	{
		log.log("INFO", msg);
	}
	
	public static void logInfo(Throwable e)
	{
		log.log("INFO", e);
	}
	
	public static void logDebug(String msg)
	{
		log.log("DEBUG", msg);
	}
	
	public static void logDebug(Throwable e)
	{
		log.log("DEBUG", e);
	}
	
}


Java代码 复制代码
  1. public class TestLog    
  2. {   
  3.   
  4.     /**  
  5.      * @param args  
  6.      */  
  7.     public static void main(String[] args)    
  8.     {   
  9.         Log.logDebug("test log debug");   
  10.         Log.logError("test Error");   
  11.   
  12.     }   
  13.   
  14. }  
public class TestLog 
{

	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		Log.logDebug("test log debug");
		Log.logError("test Error");

	}

}



还有一种方式 配置文件log4j.properties 放在src下

Java代码 复制代码
  1. import java.net.URL;   
  2.   
  3. import org.apache.log4j.BasicConfigurator;   
  4. import org.apache.log4j.Level;   
  5. import org.apache.log4j.Logger;   
  6. import org.apache.log4j.Priority;   
  7. import org.apache.log4j.PropertyConfigurator;   
  8.   
  9.   
  10.   
  11. public class LoggerService   
  12. {   
  13.     private Logger logger;   
  14.   
  15.     public LoggerService(String  location)   
  16.     {   
  17.         logger = (Logger) Logger.getLogger(location);   
  18.         //读取配置文件   
  19.         getLog4jConfig();   
  20.     }   
  21.   
  22.     public void debug(Object msg)   
  23.     {   
  24.         log("DEBUG", msg, null);   
  25.     }   
  26.   
  27.     public void debug(Object msg, Throwable t)   
  28.     {   
  29.         log("DEBUG", msg, t);   
  30.     }   
  31.   
  32.     public void info(Object msg)   
  33.     {   
  34.         log("INFO", msg, null);   
  35.     }   
  36.   
  37.     public void info(Object msg, Throwable t)   
  38.     {   
  39.         log("INFO", msg, t);   
  40.     }   
  41.   
  42.     public void warn(Object msg)   
  43.     {   
  44.         log("WARN", msg, null);   
  45.     }   
  46.   
  47.     public void warn(Object msg, Throwable t)   
  48.     {   
  49.         log("WARN", msg, t);   
  50.     }   
  51.   
  52.     public void error(Object msg)   
  53.     {   
  54.         log("ERROR", msg, null);   
  55.     }   
  56.   
  57.     public void error(Object msg, Throwable t)   
  58.     {   
  59.         log("ERROR", msg, t);   
  60.     }   
  61.   
  62.     private void log(String level, Object msg, Throwable e)   
  63.     {   
  64.         if (null != logger)   
  65.         {   
  66.             logger.log((Priority) Level.toLevel(level), msg, e);   
  67.         }   
  68.     }   
  69.        
  70.     /**  
  71.      * 读取配置文件  
  72.      */  
  73.     private void getLog4jConfig()   
  74.     {   
  75.         if (System.getProperty("log4j.configuration") == null)   
  76.         {   
  77.             URL url = ClassLoader.getSystemResource("log4j.properties");   
  78.             String path = "";   
  79.             if(null!=url)   
  80.             {   
  81.                 path = url.getPath();   
  82.             }   
  83.             PropertyConfigurator.configure(path);   
  84.             BasicConfigurator.configure();   
  85.   
  86.         }   
  87.     }   
  88.   
  89. }  
import java.net.URL;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.PropertyConfigurator;



public class LoggerService
{
    private Logger logger;

    public LoggerService(String  location)
    {
        logger = (Logger) Logger.getLogger(location);
        //读取配置文件
        getLog4jConfig();
    }

    public void debug(Object msg)
    {
        log("DEBUG", msg, null);
    }

    public void debug(Object msg, Throwable t)
    {
        log("DEBUG", msg, t);
    }

    public void info(Object msg)
    {
        log("INFO", msg, null);
    }

    public void info(Object msg, Throwable t)
    {
        log("INFO", msg, t);
    }

    public void warn(Object msg)
    {
        log("WARN", msg, null);
    }

    public void warn(Object msg, Throwable t)
    {
        log("WARN", msg, t);
    }

    public void error(Object msg)
    {
        log("ERROR", msg, null);
    }

    public void error(Object msg, Throwable t)
    {
        log("ERROR", msg, t);
    }

    private void log(String level, Object msg, Throwable e)
    {
        if (null != logger)
        {
            logger.log((Priority) Level.toLevel(level), msg, e);
        }
    }
    
    /**
     * 读取配置文件
     */
    private void getLog4jConfig()
    {
        if (System.getProperty("log4j.configuration") == null)
        {
            URL url = ClassLoader.getSystemResource("log4j.properties");
            String path = "";
            if(null!=url)
            {
                path = url.getPath();
            }
            PropertyConfigurator.configure(path);
            BasicConfigurator.configure();

        }
    }

}



Java代码 复制代码
  1. public class Log    
  2. {   
  3.        
  4.        
  5.     public static LoggerService getLoggerService(String name) {   
  6.         return new LoggerService(name);   
  7.     }   
  8.                
  9. }  
public class Log 
{
	
	
    public static LoggerService getLoggerService(String name) {
        return new LoggerService(name);
    }
			
}


Java代码 复制代码
  1. public class TestLog    
  2. {   
  3.   
  4.     public static void main(String[] args)   
  5.     {   
  6.         LoggerService log = Log.getLoggerService(TestLog.class.getName());   
  7.         log.warn("this is test logger");   
  8.     }   
  9.        
  10. }  
public class TestLog 
{

    public static void main(String[] args)
    {
        LoggerService log = Log.getLoggerService(TestLog.class.getName());
        log.warn("this is test logger");
    }
	
}

 

Java代码 复制代码
  1. import java.io.FileInputStream;   
  2. import java.io.IOException;   
  3. import java.util.Properties;   
  4.   
  5. import javax.servlet.ServletConfig;   
  6. import javax.servlet.ServletException;   
  7. import javax.servlet.http.HttpServlet;   
  8.   
  9. import org.apache.log4j.Logger;   
  10. import org.apache.log4j.PropertyConfigurator;   
  11.   
  12. public class Log4jInit extends HttpServlet   
  13. {   
  14.     private static final long serialVersionUID = -4499302208753939187L;   
  15.     static Logger             logger           = Logger   
  16.                                                        .getLogger(Log4jInit.class);   
  17.   
  18.     public void init(ServletConfig config) throws ServletException   
  19.     {   
  20.         String prefix = config.getServletContext().getRealPath("/");   
  21.         String file = config.getInitParameter("log4j");   
  22.         String filePath = prefix + file;   
  23.         Properties props = new Properties();   
  24.         try  
  25.         {   
  26.             FileInputStream istream = new FileInputStream(filePath);   
  27.             props.load(istream);   
  28.             istream.close();   
  29.             //设置路径   
  30. //            String logFile = prefix + props.getProperty("log4j.appender.file.File");   
  31. //            System.out.println("日志输出文件路径:"+logFile);   
  32. //            props.setProperty("log4j.appender.file.File",logFile);   
  33.             // 装入log4j配置信息   
  34.             PropertyConfigurator.configure(props);   
  35.             System.out.println("装载完成log4j.properties:"+filePath);   
  36.         }   
  37.         catch (IOException e)   
  38.         {   
  39.             System.out.println("Could not read configuration file [" + filePath   
  40.                     + "].");   
  41.             System.out.println("Ignoring configuration file [" + filePath   
  42.                     + "].");   
  43.             return;   
  44.         }   
  45.     }   
  46. }  
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jInit extends HttpServlet
{
    private static final long serialVersionUID = -4499302208753939187L;
    static Logger             logger           = Logger
                                                       .getLogger(Log4jInit.class);

    public void init(ServletConfig config) throws ServletException
    {
        String prefix = config.getServletContext().getRealPath("/");
        String file = config.getInitParameter("log4j");
        String filePath = prefix + file;
        Properties props = new Properties();
        try
        {
            FileInputStream istream = new FileInputStream(filePath);
            props.load(istream);
            istream.close();
            //设置路径
//            String logFile = prefix + props.getProperty("log4j.appender.file.File");
//            System.out.println("日志输出文件路径:"+logFile);
//            props.setProperty("log4j.appender.file.File",logFile);
            // 装入log4j配置信息
            PropertyConfigurator.configure(props);
            System.out.println("装载完成log4j.properties:"+filePath);
        }
        catch (IOException e)
        {
            System.out.println("Could not read configuration file [" + filePath
                    + "].");
            System.out.println("Ignoring configuration file [" + filePath
                    + "].");
            return;
        }
    }
}

 

Java代码 复制代码
  1. <servlet>   
  2.          <servlet-name>log4j-init</servlet-name>   
  3.          <servlet-class>   
  4.             com.web.serverlet.Log4jInit   
  5.          </servlet-class>   
  6.          <init-param>   
  7.            <param-name>log4j</param-name>   
  8.            <param-value>WEB-INF/classes/log4j.properties</param-value>   
  9.          </init-param>   
  10.          <load-on-startup>1</load-on-startup>   
  11.     </servlet>  
<servlet>
         <servlet-name>log4j-init</servlet-name>
         <servlet-class>
            com.web.serverlet.Log4jInit
         </servlet-class>
         <init-param>
           <param-name>log4j</param-name>
           <param-value>WEB-INF/classes/log4j.properties</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
    </servlet>

posted on 2009-03-24 13:36  cy163  阅读(19795)  评论(0编辑  收藏  举报

导航