龙空技术网

SSM集成LogBack日志框架实践-文字版

BeginCode 610

前言:

现时朋友们对“apache127001”大体比较关怀,朋友们都需要学习一些“apache127001”的相关文章。那么小编在网摘上汇集了一些关于“apache127001””的相关内容,希望兄弟们能喜欢,咱们快快来了解一下吧!

LogBack+SLF4J日志框架实践

前提:

maven工程,Spring+SpringMVC+Mybatis环境

相关依赖

<dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.21</version></dependency><dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version></dependency>

SLF4J-MDC扩展

通过在Filter中通过MDC,设置变量beginTrace值客户端IP+本地IP+时间毫秒值,主要是为了保证变量beginTrace值得唯一性,当然也可以通过JAVA的生成UUID,一样可以保证唯一性,实现方案不唯一,然后通过配置logback.xml配置文件打印该日志信息,记得在执行完请求调用链的时候,执行MDC.clear();清除设置的变量

package net.begincode.filter;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.slf4j.MDC;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import java.io.IOException;import java.net.InetAddress;/*** Created by yang on 2017/9/3.*/public class LogFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(LogFilter.class); private static String localIP = ""; static { try { InetAddress addr = InetAddress.getLocalHost(); localIP = addr.getHostAddress().toString().replace(".", "") + "-"; } catch (Exception e) { LOGGER.error("获取本地ip失败"); } } public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String ipStr = getIpAddress((HttpServletRequest) servletRequest).replace(".", ""); MDC.put("beginTrace", "BTraceId-" + ipStr + "-" + localIP + System.currentTimeMillis()); try { filterChain.doFilter(servletRequest, servletResponse); } finally { MDC.clear(); } } public void destroy() { } public final static String getIpAddress(HttpServletRequest request) throws IOException { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }}

logback.xml配置

配置1、简单配置

<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>[%d] BTraceId[%X{beginTrace}] %highlight(%-5level) %logger{0}:%L - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="STDOUT" /> </root></configuration>

配置2、指定文件

<configuration> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%X{beginTrace}自定义变量,%hightligth:高亮 %-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>[%d] BTraceId[%X{beginTrace}] %highlight(%-5level) %logger{0}:%L - %msg%n</pattern> </encoder> </appender> <!-- 按照每天生成日志文件 --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日志文件输出的文件名 ${catalina.home} tomcat目录--> <FileNamePattern>${catalina.home}/logs/log.%d{yyyy-MM-dd}.log</FileNamePattern> <!--日志文件保留天数--> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%X{beginTrace}自定义变量,%hightligth:高亮 %-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>[%d] BTraceId[%X{beginTrace}] %highlight(%-5level) %logger{0}:%L - %msg%n</pattern> </encoder> <!--日志文件最大的大小--> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>100MB</MaxFileSize> </triggeringPolicy> </appender> <!--myibatis log configure--> <logger name="com.apache.ibatis" level="TRACE"/> <logger name="java.sql.Connection" level="DEBUG"/> <logger name="java.sql.Statement" level="DEBUG"/> <logger name="java.sql.PreparedStatement" level="DEBUG"/> <!-- 日志输出级别 --> <root level="INFO"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </root></configuration>

日志文件在tomcat/logs目录下,会根据日志格式和文件配置保留30天内的日志,且最大100M一个日志文件

打印日志样式

[2017-09-13 00:01:38,884] BTraceId[BTraceId-127001-1921681101-1505232098848] INFO UserController:33 - test 中文日志[2017-09-13 00:01:38,961] BTraceId[BTraceId-127001-1921681101-1505232098848]

BeginCode出品

标签: #apache127001