GoFramework框架简介(二)日志篇

158 阅读1分钟

框架的核心日志组件是log4j2,定义了日志格式,日志文件、及日志滚动文件的路径。
配置文件如下:

<?xml version="1.0" encoding="UTF-8"?> <Configuration status="INFO" schema="Log4J-V2.0.xsd" packages="org.go.framework.core.log"> <Appenders> <!-- 控制台输出 --> <Console name="Console" target="SYSTEM_OUT" > <PatternLayout pattern="%d{DEFAULT} %level{length=5} [%tid] [%logger] MsgId[${ctx:MsgId}] %m%n"/> </Console> <!-- 日志文件--> <RollingRandomAccessFile name="All" fileName="${sys:sys.trc}trc/all_${sys:application.name}.log" filePattern="/data/log-elk/%d{dd}/all_${sys:application.name}_%d{yyyy-MM-dd}.log" immediateFlush="false"> <PatternLayout pattern="%d{DEFAULT} %level{length=5} [%thread-%tid] Class=[%logger] MsgId[${ctx:MsgId}] PhoneNum[${ctx:GIGOLD_USR_MOBILE}] ProjectName[${sys:application.name}] %m%n"/> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> </Policies> </RollingRandomAccessFile> <!-- 重写规则 --> <GigoldRewrite name="ALLRewrite"> <AppenderRef ref="All"/> <AppenderRef ref="Console"/> <GigoldMapRewritePolicy/> </GigoldRewrite> <!-- 所有日志 end--> </Appenders> <Loggers> <Root> <AppenderRef ref="ALLRewrite" /> </Root> </Loggers> </Configuration>

其中ctx:MsgId的实现原理是使用MDC写入到线程Map中,再使用日志rewrite策略实现。 import org.apache.logging.log4j.ThreadContext; public final static void initialMsgId() { if (!ThreadContext.containsKey(MSG_ID)) {// 如果为空代表是线程最初始入口 ThreadContext.put(MSG_ID, JrnGenerator.genMsgId()); } } @Plugin(name = "GigoldMapRewritePolicy", category = "Core", elementType = "rewritePolicy", printObject = true) public final class GigoldMapRewritePolicy implements RewritePolicy { /** * 动态生成每个类的日志文件的Key */ public static final String NULL = "null"; private GigoldMapRewritePolicy() { } /** * Rewrite the event.l * * @param source a logging event that may be returned or used to create a new logging event. * @return The LogEvent after rewriting. */ @Override public LogEvent rewrite(final LogEvent source) { HashMap<String, String> contextMap = Maps.newHashMap(source.getContextMap()); contextMap.put(MSG_ID, contextMap.containsKey(MSG_ID)?contextMap.get(MSG_ID): NULL); contextMap.put(GIGOLD_USR_MOBILE, contextMap.containsKey(GIGOLD_USR_MOBILE)?contextMap.get(GIGOLD_USR_MOBILE): NULL); Collections.unmodifiableMap(contextMap); return new Log4jLogEvent.Builder(source).setContextMap(contextMap).build(); } @PluginFactory public static GigoldMapRewritePolicy createPolicy() { return new GigoldMapRewritePolicy(); } }\

控制台输出会输出在wrapper.log中。在服务器环境应该尽量屏蔽控制台输出,而输出在trc文件上。

其中控制台或者文件是否输出日志,可以由server.properties中的属性来控制
分别是log.console.trigger和log.routing.trigger属性

关键代码

private void dynamicConsole(GigoldRewrit rewrite) { if (!Boolean .valueOf(getProperty(LOG_CONSOLE_TRIGGER) != null ? getProperty(LOG_CONSOLE_TRIGGER) : Boolean.FALSE.toString())) { rewrite.removeAppenders(CONSOLE);// 移除控制台日志 } } private void dynamicFileAppender(GigoldRewrit rewrite) { if (!Boolean .valueOf(getProperty(LOG_ROUTING_TRIGGER) != null ? getProperty(LOG_ROUTING_TRIGGER) : Boolean.FALSE.toString())) { rewrite.removeAppenders(ROUTING);// 移除路由日志 } }

框架日志输出的几个类:RPCLogger,ITFLogger,WebLogger等。

框架日志中几个重要的参数:

1.png 如果我们在项目中需要进行日志记录,推荐是继承org.go.framework.service.AbstractService这样的类,而非是在类中定义这样的日志实例:

private static Logger log = LogManager.getLogger(UserController.class.getName());

写日志时推荐以下的作法:

info("当前登录用户是:{}", userId);

不推荐的作法:

info("当前登录用户是:" + userId);

因为如果当前日志级别不需要打印时,后者需要进行一次字符串的计算,而前者不需要。