Java tutorial
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.otter.shared.arbitrate.impl.interceptor; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * event? * * @author jianghang 2011-9-28 ?07:13:40 * @version 4.0.0 */ public class LogInterceptor implements MethodInterceptor { private static final String DATA_FORMAT = "yyyy-MM-dd HH:mm:ss.sss"; private static String MESSAGE = "\n=======================================\n[Class:{0} , Method:{1} , time:{2} , take:{3}ms]\n{4}Result\r\t{5}\n======================================="; public Object invoke(MethodInvocation methodInvocation) throws Throwable { long startTime = System.currentTimeMillis(); Object result = null; try { result = methodInvocation.proceed(); } catch (Exception e) { dump(methodInvocation, e, System.currentTimeMillis() - startTime);// ? throw e; } // ? dump(methodInvocation, result, System.currentTimeMillis() - startTime); // ? return result; } /** * ?logger * * @param obj */ protected Logger getLogger(Class obj) { return LoggerFactory.getLogger(obj); } /** * ? * * @param methodInvocation * @param take */ private void dump(MethodInvocation methodInvocation, Object result, long take) { // ?? Logger log = getLogger(methodInvocation.getMethod().getDeclaringClass()); Object[] args = methodInvocation.getArguments(); StringBuffer buffer = getArgsString(args); if (log.isInfoEnabled()) { String className = ClassUtils.getShortClassName(methodInvocation.getMethod().getDeclaringClass()); String methodName = methodInvocation.getMethod().getName(); String resultStr = getResultString(result); String now = new SimpleDateFormat(DATA_FORMAT).format(new Date()); log.info(MessageFormat.format(MESSAGE, new Object[] { className, methodName, now, take, buffer.toString(), resultStr })); } } /** * ? * * @param result * @return */ protected String getResultString(Object result) { if (result == null) { return StringUtils.EMPTY; } if (result instanceof Map) { // ?map return getMapResultString((Map) result); } else if (result instanceof List) {// ?list return getListResultString((List) result); } else if (result.getClass().isArray()) {// ?array return getArrayResultString((Object[]) result); } else { // ?string return ObjectUtils.toString(result, StringUtils.EMPTY).toString(); // return ToStringBuilder.reflectionToString(result, ToStringStyle.SIMPLE_STYLE); } } /** * ?mapstring?value?toString?, copy from {@link AbstractMap} * * @param result * @return */ private String getMapResultString(Map result) { StringBuilder sb = new StringBuilder(); Iterator<Entry> i = result.entrySet().iterator(); if (!i.hasNext()) { return "{}"; } sb.append('{'); for (;;) { Entry e = i.next(); Object key = e.getKey(); Object value = e.getValue(); // ?: getResultString(e)? sb.append(key == this ? "(this Map)" : getResultString(key)); sb.append('='); // ?: getResultString(e)? sb.append(value == this ? "(this Map)" : getResultString(value)); if (!i.hasNext()) { return sb.append('}').toString(); } sb.append(", "); } } /** * ?liststring?value?toString?, copy from {@link AbstractCollection} * * @param result * @return */ private String getListResultString(List result) { StringBuilder sb = new StringBuilder(); Iterator i = result.iterator(); if (!i.hasNext()) { return "[]"; } sb.append('['); for (;;) { Object e = i.next(); // ?: getResultString(e)? sb.append(e == this ? "(this Collection)" : getResultString(e)); if (!i.hasNext()) { return sb.append(']').toString(); } sb.append(", "); } } /** * ?arraystring?value?toString? * * @param result * @return */ private String getArrayResultString(Object[] result) { return getListResultString(Arrays.asList(result)); } /** * ?? * * @param args * @return */ private StringBuffer getArgsString(Object[] args) { StringBuffer buffer = new StringBuffer(); String prefix = "args "; for (int i = 0; i < args.length; i++) { if (args.length > 1) { buffer.append(prefix + (i + 1)); } buffer.append("\r\t"); buffer.append(getResultString(args[i])); buffer.append("\n"); } return buffer; } }