在框架处理日志的时候,支持配置方式生成日志。日志内容可以根据一定的规则来生成。这里就可以使用Velocity了。
下面针对常用的几种类型进行测试
1)map
Map map = new HashMap();
map.put("abc", "def");
context.put("param", map );
String commentEL = "$param.abc";
结果输出为def
2)dto
ServiceLogDto dto = new ServiceLogDto();
dto.setPartyCode("logCode");
context.put("param", dto );
commentEL = "$param.partyCode";
结果输出为logCode
3)[ ] 数组
ServiceLogDto [] dtos = new ServiceLogDto[2];
dtos[0]=dto;
dtos[1]=new ServiceLogDto();
dtos[1].setPartyCode("testCode");
context.put("param", dtos );
commentEL = "#foreach($o in $param)$o.partyCode #end";
结果输出为 logCode testCode
4)list
List list = new ArrayList();
list.add(dto);
ServiceLogDto dto2 = new ServiceLogDto();
dto2.setPartyCode("test2");
list.add(dto2);
context.put("param", list );
commentEL = "#foreach($o in $param)$o.partyCode #end";
输出为 logCode test2
基本的类型都能用,即便有复杂的类型也可以在数据源这边转化一下。
附上上面代码片段的前后备用
VelocityEngine engine = new VelocityEngine();
engine.init();
VelocityContext context = new VelocityContext();
/some code below
String re= evaluate(engine, context, commentEL );
System.out.println(re);
///
private static String evaluate(VelocityEngine engine, VelocityContext context, String expr) {
if (expr == null || expr.trim().length() == 0) {
return "";
}
try {
CharArrayWriter writer = new CharArrayWriter();
engine.evaluate(context, writer, "", expr);
return writer.toString();
}
catch (Exception e) {
return expr;
}
}