javaWeb project configuration log4j

Some time ago, due to the need to deploy the project to the server, because I was used to printing to the console DEBUG tracking, after deploying to the server, I found that it was difficult to track the problem with the console information, and the console could not copy the printed information, so I made up my mind. Output the log of the project yourself to a folder that you can view at any time.    


Log4j consists of three important components: the priority of log information, the output destination of log information, and the output format of log information . The priority of the log information from high to low is ERROR , WARN , INFO , DEBUG, ALL , which are used to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or a file; The output format controls the display content of the log information.


1. First, you have a Web project. Second, you have to prepare the log4j dependency package log4j-1.2.15.jar commons-logging-1.0.4.jar and test the next 2 dependency packages respectively, otherwise an error will be reported.

2. Create a new log4j configuration in WEB-INF in the root directory of your project. Name it log4j.properties. You can re-specify the location and file name, as long as the configuration can be found according to the path in the subsequent configuration. Generally take the agreed mature way.

    

            log4j.rootLogger = [ level ] , appenderName1,appenderName2, …

              1. rootLogger     refers to configuring log4j  The level includes 5 kinds of articles, which means that only information above the INFO levelis printed

                                                                 appenderName1   appenderName2 ...  refers to where to output the log information is specified by the following

    2. The appender specifies where to print the log information

        1.org.apache.log4j.ConsoleAppender (console), 2.org.apache.log4j.FileAppender (file) , 3.org.apache.log4j.DailyRollingFileAppender ( generates a log file every day), 4.org.apache. log4j.RollingFileAppender (generate a new file when the file size reaches the specified size ) 5.org.apache.log4j.WriterAppender (send log information to any specified place in stream format)
        
        
          
        

    3. layout   configures the format of the log information (layout)

        1.org.apache.log4j.HTMLLayout (layout in HTML form), 2.org.apache.log4j.PatternLayout (layout pattern can be specified flexibly ), 3.org.apache.log4j.SimpleLayout ( level of log information included ) and information string), 4.org.apache.log4j.TTCCLayout (contains log generation time, thread, category, etc.)
        
        
        



   The specific log4j configuration has been searched on the Internet, and I will not repeat it here. Below is the specific meaning of my configuration

log4j.rootLogger=info,ServerDailyRollingFile,stdout log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender            log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.ServerDailyRollingFile.File=D:/hang222/hlserverlogs/hlserver.log               log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout                   log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d - %m%n
log4j.appender.ServerDailyRollingFile.Append=true

log4j.appender.stdout=org.apache.log4j.ConsoleAppender                               log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] %m%n



   1.1 ServerDailyRollingFile = org.apache.log4j.DailyRollingFileAppender   generates a log file every day and defines the format of printing log time and the path of the log later, where you can use a relative path where you only need to modify D:/hang213/hlserverlogs/hlserver. log,

   1.1.1 Normal relative path:

     log4j.appender.logfile.File=../logs/app.log, record the log to the logs folder under tomcat;

                       log4j.appender.logfile.File=logs/app.log, record the log to the logs folder in the bin directory of tomcat;

   1.1.2 The relative path of the environment variable: (other needs can be searched online) You can locate the location you want by printing in the program

       System.out.println("Java运行时环境版本:/n"+System.getProperty("java.version"));  

                 log4j.appender.logfile.File=${user.dir}/logs/app.log,使用tomcat容器时${user.dir}对应tomcat的bin目录;

                      log4j.appender.logfile.File=${user.home}/logs/app.log,${user.home}对应操作系统当前用户目录
                       log4j.appender.logfile.File=${webApp.root}/logs/app.log,${webApp.root}对应当前应用根目录

  1.2 stdout= org.apache.log4j.ConsoleAppender    打印在控制台

      PropertyConfigurator.configure(props); //装入log4j配置信息

      } catch (IOException e) {
       e.printStackTrace();
      }
      System.err.println("初始化log4j日志组件");
     }

}

三、在Web.xml配置log4j 用于项目自动加载log4j的配置   

   <!-- 加载Log4J 配置文件  -->  
    <context-param>  
     <param-name>log4jConfigLocation</param-name>  
     <param-value>WEB-INF/log4j.properties</param-value>  
    </context-param>     
 
    <context-param>  
     <param-name>log4jRefreshInterval</param-name>  
      <param-value>3000</param-value>  
    </context-param>  
 
 <listener>  
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
 </listener>

  项目在运行时就会根据设置的路径将log4j的配置加载,log4jRefreshInterval这是设置每3秒扫描查看配置是否发生变化,等同于动态加载,不过一般不需要可以去掉,上面使用监听器,当然也可以servlet实现,原理相同:只需将listener换成servlet

<servlet>    
 <servlet-name>log4j</servlet-name>    
 <servlet-class>    
 org.springframework.web.util.Log4jConfigServlet    
 </servlet-class>    
 <load-on-startup>1</load-on-startup>    
</servlet>

到此 我们的log4j就配置完成了,在项目中需要打印日志的方法时:

private static Logger logger = Logger.getLogger(类名.class);


logger.info("打印的日志"+需要打印的参数等);

到此over  查看下完成没有:控制台


文件:


 

当然由于配置了 DatePattern  你的前面日志文件会自动生成 hlserver.log.2017-10-18


我了解的还有一种就是通过servlet初始化init()方法中加载file属性实现相对路径

原理相同  写一个类 用于加载log4j的配置  并在WEB.xml配置这个类并加载他。


/WEB-INF/config/log4j.properties

log4j.appender.AFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.AFile.DatePattern='.'yyyy-MM-dd'.html'
log4j.appender.AFile.File=..//webapps//logs//d1cm_log.html
log4j.appender.AFile.layout=org.apache.log4j.HTMLLayout
log4j.appender.AFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p %c %m %n




com.lq.utils.ConfigServlet.java

public class ConfigServlet extends HttpServlet {
    
     private static final long serialVersionUID = 1L;
     public void init(ServletConfig config) throws ServletException {
      super.init(config);
          //初始化log4j日志组件
      initLogConfig(config);
      
     }
    
    
     private void initLogConfig(ServletConfig config) {
      String prifix = getServletContext().getRealPath("/");
        //System.out.println(prifix);
        
         //获取log4j配置文件地址
      String Log4jFile = config.getInitParameter("Log4jFile");
      //System.out.println(Log4jFile);
      String filePath = prifix + Log4jFile;
      //System.out.println(filePath);
      PropertyConfigurator.configure(filePath);
      Properties props = new Properties();
     /* try {
       String Log4jFileSavePath = config.getInitParameter("Log4jFileSavePath");
       //System.out.println(Log4jFileSavePath);
       FileInputStream log4jStream = new FileInputStream(filePath);
       props.load(log4jStream);
       log4jStream.close();
       //设置日志保存地址
       String logFile = prifix + Log4jFileSavePath + File.separator + "d1cm_log.html" ;
       //System.out.println(logFile);
       props.setProperty("log4j.appender.AFile.File", logFile);
       PropertyConfigurator.configure(props); //装入log4j配置信息
      } catch (IOException e) {
       e.printStackTrace();
      }*/
      System.err.println("初始化log4j日志组件");
     }

}

web.xml

 <!-- 系统初始化配置信息  servlet -->
 <servlet>
  <servlet-name>configServlet</servlet-name>
  <servlet-class>com.common.config.ConfigServlet</servlet-class>
  <init-param>
   <param-name>Log4jFile</param-name>
   <param-value>/WEB-INF/config/log4j.properties</param-value>
  </init-param>
  <init-param>
   <param-name>Log4jFileSavePath</param-name>
   <param-value>/logs</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

There are many online resources, slowly summarize and learn slowly

The third is implemented according to this URL: I haven't studied much, and it is similar to the configuration load.

  http://blog.csdn.net/longaohun/article/details/6233099

   

实现完了发现控制台还好,日志文件中每次启动重新启动项目就老是显示很多不需要的信息,严重干扰了阅读查错,


网站上找了半天解决办法,什么不打印Spring的相关等,最后幡然醒悟,你将一个成熟的项目部署到服务器后,很少会不断的重启服务,自己想多了。。。。。不知道会不会有人和我一样陷入怪圈。



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325556381&siteId=291194637