标签:pos 文件的时间 format src sim 变量定义 let 工具 uil
上个星期领导交给我一个任务,就是写logback自定义转换实现以下要求
[IP][文件名][行号][YYMMDD][HHMMSS.sss][线程名称][socket号][代码包和函数名.行号]-[卡号|单位|商户|终端|交易类型][message]
eg:
输出结果
[192.168.1.134][comm.20880.log][100][16-11-07][19:20:01.002][fixThread001][00000000000020002222222222222001][com.bridge.method.66]-[1000198909875654|10000011|9887777||00000001|1212][hello world!]
logback的配置文件(自定义后在以下添加)
[%ip][文件名][行号][%.-1level][%date{ISO8601}][%baseMessageConvert][%][%30.30logger{10}|%M|%L] -%m%n
我们了解以下什么是logback:
c {length } lo {length } logger {length } |
输出日志的logger名,可有一个整形参数,功能是缩短logger名,设置为0表示只输入logger最右边点符号之后的字符串。 Conversion specifier Logger name Result |
C {length } class {length } |
输出执行记录请求的调用者的全限定名。参数与上面的一样。尽量避免使用,除非执行速度不造成任何问题。 |
contextName cn |
输出上下文名称。 |
d {pattern } date {pattern } |
输出日志的打印日志,模式语法与java.text.SimpleDateFormat 兼容。 Conversion Pattern Result |
F / file | 输出执行记录请求的java源文件名。尽量避免使用,除非执行速度不造成任何问题。 |
caller{depth} caller{depth, evaluator-1, ... evaluator-n} | 输出生成日志的调用者的位置信息,整数选项表示输出信息深度。 例如, %caller{2} 输出为: 0 [main] DEBUG - logging statement Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22) Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17) 例如, %caller{3} 输出为: 16 [main] DEBUG - logging statement Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22) Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17) Caller+2 at mainPackage.ConfigTester.main(ConfigTester.java:38) |
L / line | 输出执行日志请求的行号。尽量避免使用,除非执行速度不造成任何问题。 |
m / msg / message | 输出应用程序提供的信息。 |
M / method | 输出执行日志请求的方法名。尽量避免使用,除非执行速度不造成任何问题。 |
n | 输出平台先关的分行符“\n”或者“\r\n”。 |
p / le / level | 输出日志级别。 |
r / relative | 输出从程序启动到创建日志记录的时间,单位是毫秒 |
t / thread | 输出产生日志的线程名。 |
replace(p ){r, t} | p 为日志内容,r 是正则表达式,将p 中符合r 的内容替换为t 。 例如, "%replace(%msg){‘\s‘, ‘‘}" |
%logger | mainPackage.sub.sample.Bar | mainPackage.sub.sample.Bar |
%logger{0} | mainPackage.sub.sample.Bar | Bar |
%logger{5} | mainPackage.sub.sample.Bar | m.s.s.Bar |
%logger{10} | mainPackage.sub.sample.Bar | m.s.s.Bar |
%logger{15} | mainPackage.sub.sample.Bar | m.s.sample.Bar |
%logger{16} | mainPackage.sub.sample.Bar | m.sub.sample.Bar |
%logger{26} | mainPackage.sub.sample.Bar | mainPackage.sub.sample.Bar |
%d | 2006-10-20 14:06:49,812 |
%date | 2006-10-20 14:06:49,812 |
%date{ISO8601} | 2006-10-20 14:06:49,812 |
%date{HH:mm:ss.SSS} | 14:06:49.812 |
%date{dd MMM yyyy ;HH:mm:ss.SSS} | 20 oct. 2006;14:06:49.812 |
package com.ykt.comm.util.logback; import java.util.HashMap; import java.util.Map; import ch.qos.logback.classic.pattern.ClassicConverter; import ch.qos.logback.classic.spi.ILoggingEvent; import com.google.gson.Gson; public class BaseMessageConvert extends ClassicConverter { public static String SPlIT_CHAR_REG = "\\|"; @Override public String convert(ILoggingEvent event) { //调用MessageUtil工具类执行后产生新生成的先成名和socketId以及其他各个字段 String myThreadName = event.getThreadName(); String[] baseMessageArray = myThreadName.split(SPlIT_CHAR_REG); if (baseMessageArray.length == 1) { return ""; } else { //这是指定排序 Gson gson = new Gson(); @SuppressWarnings("unchecked") Map<String, String> data = gson.fromJson(baseMessageArray[1], HashMap.class); String socketId = data.get(LogKeyConstant.LOG_KEY_SOCKETID.getpCode()); String txnType = data.get(LogKeyConstant.LOG_KEY_TXNTYPE.getpCode()); String seq = data.get(LogKeyConstant.LOG_KEY_SEQ.getpCode()); String unit = data.get(LogKeyConstant.LOG_KEY_UNIT.getpCode()); String mchnt = data.get(LogKeyConstant.LOG_KEY_MCHNT.getpCode()); String pos = data.get(LogKeyConstant.LOG_KEY_POS.getpCode()); String cardNo = data.get(LogKeyConstant.LOG_KEY_CARDNO.getpCode()); StringBuilder builder = new StringBuilder(); builder.append("[通讯号:").append(socketId).append("|交易类型:").append(txnType).append("|交易流水:").append(seq).append("|单位号:") .append(unit).append("|商户号:").append(mchnt).append("|终端号:").append(pos).append("|卡号:").append(cardNo) .append("]"); return builder.toString(); } } } |
package com.ykt.comm.util.logback; import java.net.InetAddress; import java.net.UnknownHostException; import ch.qos.logback.classic.pattern.ClassicConverter; import ch.qos.logback.classic.spi.ILoggingEvent; public class IpConvert extends ClassicConverter{ @Override public String convert(ILoggingEvent event) { String hostAddress = null; try { hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } return hostAddress; }} |
package com.ykt.comm.util.logback; /** * 日志 打印 元素 * * @author victor [socketid|交易类型|交易流水|单位|商户|终端|卡号] */ public enum LogKeyConstant { LOG_KEY_SOCKETID("SOCKETID", "通讯号"), LOG_KEY_TXNTYPE("TXNTYPE", "交易类型"), LOG_KEY_SEQ("SEQ", "交易流水"), LOG_KEY_UNIT("UNIT", "单位号"), LOG_KEY_MCHNT("MCHNT", "商户号"), LOG_KEY_POS("POS", "终端号"), LOG_KEY_CARDNO("CARDNO", "卡号"), ; private String pCode; private String pName; private LogKeyConstant(String pCode, String pName) { this.pCode = pCode; this.pName = pName; } public String getpCode() { return pCode; } public void setpCode(String pCode) { this.pCode = pCode; } public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public static boolean containPCode(String pCode) { boolean result = false; for (LogKeyConstant logKeyConstant : LogKeyConstant.values()) { if (pCode.equals(logKeyConstant.pCode)) { result = true; break; } } return result; } } |
package com.ykt.comm.util.logback; import com.google.gson.Gson; import com.google.gson.JsonObject; public class MessageUtil { public static String SPlIT_CHAR_REG = "\\|"; public static String SPlIT_CHAR = "|"; /** * 根据发送过来的key 和 value, 拼装进线程名 key 需要定义宏定义, 处理过程中需要先对 宏进行判定,只有相同数据的宏才能进行设置 处理后的JSON数据需要根据特殊定义排序??? * * @param key * @param value */ public static void setMessage(String key, String value) { //TODO 对key进行宏定义判定 if (!LogKeyConstant.containPCode(key)) { return; } Gson gson = new Gson(); String addStr = null; String strArray[] = Thread.currentThread().getName().split(SPlIT_CHAR_REG); if (strArray.length == 1) { //第一次向线程名赋值数据,先创建一个jsonObject对象 JsonObject jsonObject = new JsonObject(); //将key,value参数存入jsonObject对象 jsonObject.addProperty(key, value); //将jsonObject对象转换成json字符串然后赋值给字符串变量addStr addStr = gson.toJson(jsonObject); } else { //第N次向线程名赋值数据 //若存在|获取数组的第二个元素相当于业务字段的字符串 String baseMessage = strArray[1]; //通过这个字符串获取jsonObject对象 JsonObject jsonObjectAgain = gson.fromJson(baseMessage, JsonObject.class); //将参数key value用jsonObjectAgain对象存储 jsonObjectAgain.addProperty(key, value); //将jsonObjectAgain对象转换成json字符串并赋值给addStr addStr = gson.toJson(jsonObjectAgain); //需要对ADDSTR 根据要求排序 //[通讯号,交易类型,交易流水,单位,商户,终端,卡号] } //System.out.println(addStr); Thread.currentThread().setName(strArray[0] + SPlIT_CHAR + addStr); // System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { MessageUtil.setMessage(LogKeyConstant.LOG_KEY_SOCKETID.getpCode(), "通讯号-xxx"); MessageUtil.setMessage(LogKeyConstant.LOG_KEY_TXNTYPE.getpCode(), "交易类型-xxx"); } } |
package com.ykt.comm.util.logback; import ch.qos.logback.classic.pattern.ClassicConverter; import ch.qos.logback.classic.spi.ILoggingEvent; /** * * @author Administrator * */ public class MyThreadConvert extends ClassicConverter{ @Override public String convert(ILoggingEvent event) { return event.getThreadName().split("\\|")[0]; } } |
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="60000" debug="true"> <property name="APP_Name" value="acc" /> <!-- 这里的converterClass要把包名写对了否则不能正常打印日志 --> <conversionRule conversionWord="ip" converterClass="com.ykt.comm.util.logback.IpConvert" /> <conversionRule conversionWord="baseMessage" converterClass="com.ykt.comm.util.logback.BaseMessageConvert" /> <conversionRule conversionWord="myThread" converterClass="com.ykt.comm.util.logback.MyThreadConvert" /> <!-- [%date{ISO8601}][%-5level][%thread][%c] -%m%n --> <!-- [%date{HH:mm:ss.SSS}][%.-1level][%15.15thread][%30.30logger{10}.%L] -%m%n --> <property name="Log_Pattern" value="[%ip][%date{ISO8601}][%.-1level][%myThread][%baseMessage][%30.30logger{10}-%method.%line]-%m%n" /> <property name="File_Pattern" value="../logs/%d{yyyyMMdd}/acc/" /> <contextName>${APP_Name}</contextName> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>${Log_Pattern}</pattern> </encoder> </appender> <appender name="root" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${File_Pattern}acc-acc.log</fileNamePattern> </rollingPolicy> <append>true</append> <Prudent>true</Prudent> <encoder><pattern>${Log_Pattern}</pattern></encoder> </appender> <appender name="dubbo" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${File_Pattern}dubbo.log</fileNamePattern> </rollingPolicy> <append>true</append> <Prudent>true</Prudent> <encoder><pattern>${Log_Pattern}</pattern></encoder> </appender> <!-- addtivity,默认为true,将此loger的打印信息向上级传递;--> <!-- 没有设置appender,此loger本身不打印任何信息 --> <logger name="com.alibaba" level="ERROR" additivity="false"> <appender-ref ref="dubbo"/> <appender-ref ref="STDOUT"/> </logger> <logger name="com" level="${dubbo.logger.level}" additivity="false"> <appender-ref ref="root" /> <appender-ref ref="STDOUT"/> </logger> <!-- trace, debug, info, warn, error --> <root level="${dubbo.logger.level}"> <appender-ref ref="root" /> <appender-ref ref="STDOUT"/> </root> <!-- 关闭相关的日志 --> <logger name="com.acc.dal.dao" level="OFF" /> <logger name="org.mybatis.spring" level="OFF" /> <logger name="org.apache.zookeeper" level="ERROR" /> </configuration> |
标签:pos 文件的时间 format src sim 变量定义 let 工具 uil
原文地址:http://www.cnblogs.com/yyssyh213/p/6086156.html