【Log4j实战】在线查看log日志并使用tomcat验证账户权限

来源:互联网 发布:淘宝新店推广文字 编辑:程序博客网 时间:2024/04/29 09:02

有时候,查看log日志都要跑到服务器,或者把log文件下载下来看,还是比较麻烦的,今天咱们做个配置,让log日志可以在线查看。我使用的容器是Tomcat,所以,这是针对Tomcat的服务而言

原理说起来非常简单,就是让生成的日志到项目同级,在tomcat中作为一个静态资源项目可以通过网络在线查看,安全也不能忽视,不能让谁都能看到,这里我选择了让tomcat来负责账户权限校验,参考了tomcat自带示例manager的配置。

  • 首先,我们把日志文件保存的路径修改下,保存到项目的同级目录。在web.xml中添加一个配置,这里的webApp.root可以随意指定,参数名不可修改
    <!--日志文件路径映射到WEB-INF下--><context-param>  <param-name>webAppRootKey</param-name>  <param-value>webApp.root</param-value></context-param>

  • 修改log4j.properties文件,修改一下日志文件的保存路径,这么简单一改,日志文件就保存到项目同级的log文件夹中了
    log4j.appender.D.File=${webApp.root}/../log/debug.log

  • 接着,我们再来添加下tomcat权限验证,在tomcat的webapps中创建一个log文件夹,然后创建一个WEB-INF文件夹,里面放上一个web.xml,内容如下
    <?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  version="3.0"  metadata-complete="true">  <display-name>Log Application</display-name>    <filter>    <filter-name>SetCharacterEncoding</filter-name>    <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>    <init-param>      <param-name>encoding</param-name>      <param-value>UTF-8</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>SetCharacterEncoding</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>  <!-- Define a Security Constraint on this Application -->  <!-- NOTE:  None of these roles are present in the default users file -->  <security-constraint>    <web-resource-collection>      <web-resource-name>Log Manager interface (for humans)</web-resource-name>      <url-pattern>/*</url-pattern>    </web-resource-collection>    <auth-constraint>       <role-name>log</role-name>    </auth-constraint>  </security-constraint>  <!-- Define the Login Configuration for this Application -->  <login-config>    <auth-method>BASIC</auth-method>    <realm-name>Tomcat Manager Application</realm-name>  </login-config>  <!-- Security roles referenced by this web application -->  <security-role>    <description>      The role that is required to access the HTML Manager pages    </description>    <role-name>log</role-name>  </security-role></web-app>

  • 上面指定了访问log项目时的账户角色为log,这个log角色的配置就要看tomcat/conf下的tomcat-users.xml了,在<tomcat-users>标签中把角色log加上,并加一个用户
    <role rolename="log"/><user username="log" password="123" roles="log"/>

  • 再给项目来个首页重定向,在log目录下添加一个index.jsp文件,内容只有一行,我这想默认就看到debug.log,所以就下面这么写
    <% response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/debug.log")); %>

  • 访问下,看看效果


输入我们配置的账户log/123,登录,有没有看到日志,看到就说明大功告成了