欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

log4j2日志web项目配置

程序员文章站 2022-05-24 15:42:47
...

log4j2 日志配置:
log4j和log4j2的区别可以百度看下,简单的知道好处是简化了配置
1、log4j采用.properies类型配置文件,log4j2采用了xml,
2、log4j2 保存日志用的异步保存方式,提高了效率(某天在博客上看到一篇文章,说可以采用半异步,半同步方式保存,具体哪个方式最适合可以百度下)

  1. 首先导入jar: log4j-api-2.5.jar log4j-core-2.5.jar
  2. xml: log4j2.xml(貌似命名不能改变)
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <ThresholdFilter level="WARN" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
        </Console>
        <RollingFile name="dealFile" fileName="D:/clzlog/clz_oper/err/info.log"
            filePattern="D:/clzlog/clz_oper/err/$${date:yyyy-MM-dd}/HF-%d{MM-dd-yyyy}-%i.gz">
			<PatternLayout pattern="[Time]\:[%d{HH:mm:ss.SSS}] [%t] %n%msg%n%n" />
			<SizeBasedTriggeringPolicy size="5MB" />
			<DefaultRolloverStrategy max="300" />
		</RollingFile>
		<RollingFile name="sqlFile" fileName="D:/clzlog/clz_oper/info/info.log"
			filePattern="D:/clzlog/clz_oper/info/$${date:yyyy-MM-dd}/HF-%d{MM-dd-yyyy}-%i.gz">
            <PatternLayout pattern="[Time]\:[%d{HH:mm:ss.SSS}] [%t] %n%msg%n%n" />
            <SizeBasedTriggeringPolicy size="5MB" />
            <DefaultRolloverStrategy max="300" />
        </RollingFile>
    </appenders>
    <loggers>
        <AsyncLogger name="errinfo" level="info" includeLocation="false">
            <AppenderRef ref="dealFile" />
        </AsyncLogger>
        <AsyncLogger name="info" level="info" includeLocation="false">
            <AppenderRef ref="sqlFile" />
        </AsyncLogger>
        <root level="error">  
            <appender-ref ref="Console" />  
        </root> 
    </loggers>
</configuration>

保存本地地址,并且在大于5M会自动打成压缩包,保存本地

  1. web.xml配置
  <context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>/WEB-INF/classes/log4j2.xml</param-value>
  </context-param>
  1. 公共方法 日志类, 也可以拿到baseinfo 那种一开始就加载的公共类
    package com.mer.util;


import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.mer.entity.AdminInfo;


public class LogUtil {
    private static final Logger loggerE = LogManager.getLogger("errinfo");
    private static final Logger loggeri = LogManager.getLogger("info");
    private StringBuffer msg;
    private String newLine="\n";
    protected HttpServletRequest request;

    /**
     * ********************************************************
     * @Title: getRequest
     * @Description: 获取request
     * @return HttpServletRequest
     * @date 2014-8-12 上午12:59:09
     ********************************************************
     */
    public HttpServletRequest getRequest() {
        request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 
     *********************************************************.<br>
     * [方法] getUserName <br>
     * [描述] 获取当前用户登录名 <br>
     * [参数] TODO(对参数的描述) <br>
     * [返回] String <br>
     * [时间] 2015-4-16 上午09:45:52 <br>
     *********************************************************.<br>
     */
    public static String getUserName(){
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        Object obj=request.getSession().getAttribute("admininfo");
        String userName ="";
        if (obj!=null) {
            userName = ((AdminInfo)obj).getAdmin_name();
        }
        return userName;
    }

    /**
     * 
     ********************************************************* .<br>
     * [方法] info <br>
     * [描述] 方法过程记录 <br>
     * [参数] info <br>
     * [返回] void <br>
     * [时间] 2015-11-30 下午3:51:14 <br>
     ********************************************************* .<br>
     */
    public void info(String  info) {
        msg = new StringBuffer();
        msg.append("   时间: ").append(DateUtil.get4yMdHms(new Date()));
        msg.append(newLine);
        msg.append("   操作人: ").append(getUserName());
        msg.append(newLine);
        msg.append("   请求地址: ").append(getRequest().getQueryString());
        msg.append(newLine);
        msg.append("[信息]: ").append(info);
        msg.append(newLine);
        loggeri.info(msg.toString());
    }

    /**
     * 
     ********************************************************* .<br>
     * [方法] errinfo <br>
     * [描述] 记录异常通用错误 <br>
     * [参数] exp <br>
     * [返回] void <br>
     * [时间] 2015-11-30 下午3:51:14 <br>
     ********************************************************* .<br>
     */
    public void errinfo(String  info,Exception e) {
        msg = new StringBuffer();
        msg.append("   时间: ").append(DateUtil.get4yMdHms(new Date()));
        msg.append(newLine);
        msg.append("   操作人: ").append(getUserName());
        msg.append(newLine);
        msg.append("   请求地址: ").append(getRequest().getQueryString());
        msg.append(newLine);
        msg.append("[Exp信息]: ").append(info+changeExtInfo(e));
        msg.append(newLine);
        loggerE.info(msg.toString());
    }

    /**
     * 
     ********************************************************* .<br>
     * [方法] changeExtInfo <br>
     * [描述] 处理异常信息 <br>
     * [参数] 异常对象 <br>
     * [返回] String <br>
     * [时间] 2015-5-15 下午4:30:57 <br>
     ********************************************************* .<br>
     */
    private String changeExtInfo(Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();

    }


}

我这因未获取到4j对象,所以new了下日志类,从公共方法调用下,有的可以直接在公共Controller获取调用
log4j2日志web项目配置

然后调用这方法就行(这样能把错误信息全部记录下来) ,欢迎评论指教