Logging Intercepter例子

public class LoggingInterceptor {


    private final static Logger log = LoggerFactory.getLogger("MethodLogging");


    public final static String IO_LOGGER_KEY = "method";
    
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        Method method = getMethod(point);
        LogIgnore ignore = method.getAnnotation(LogIgnore.class);


        if (ignore == null && method != null) {
            logInputMessage(point, method);
        }


        Object output = point.proceed();


        if (ignore == null && method != null) {
            logOutputMessage(point, method, output);
        }


        return output;
    }


    protected void logInputMessage(JoinPoint jp, Method method) {
        boolean mdc = false;
        
        try {
            InputLog ann = method.getAnnotation(InputLog.class);


            // check whether need to log input arguments
            if (ann != null && !ArrayUtils.isEmpty(jp.getArgs())) {
                // if LogIgnore applied on method, will ignored whole method
                // log
                Object[] args = jp.getArgs();
                Annotation[][] anns = method.getParameterAnnotations();


                for (int i = 0; i < args.length; i++) {
                    LogMask mask = null;


                    if (anns != null) {
                        LogIgnore ignore = getParameterAnnotation(anns[i], LogIgnore.class);
                        if (ignore != null) {
                            continue; // ignore output the parameter log
                        }


                        mask = getParameterAnnotation(anns[i], LogMask.class);
                    }


                    StringBuilder text = new StringBuilder();
                    String prefix = ann.prefix();


                    // build object log
                    Object body = buildLogMessageBody(args[i], mask, text);


                    String logPrefix = getInputPrefix(jp, method, prefix, i);
                    String loggerText = getLoggerText(jp, method);
                    
                    putLoggerText(loggerText);
                    mdc = true;
                    
                    outputMessage(logPrefix, body, ann.value());
                }
            }
        } catch (Throwable t) {
            log.warn("exception occured when logging input {}", t.toString());
        }finally{
            if(mdc){
                removeLoggerText();
            }
        }
    }


    protected void logOutputMessage(JoinPoint jp, Method method, Object output) {
        boolean mdc = false;
        
        try {
            OutputLog ann = method.getAnnotation(OutputLog.class);


            if (ann != null) {
                StringBuilder text = new StringBuilder();


                String prefix = ann.prefix();


                // build object log
                LogMask mask = method.getAnnotation(LogMask.class);
                Object body = buildLogMessageBody(output, mask, text);


                String logPrefix = getOutputPrefix(jp, method, prefix);
                String loggerText = getLoggerText(jp, method);
                
                putLoggerText(loggerText);
                mdc = true;
                
                outputMessage(logPrefix, body, ann.value());
            }
        } catch (Throwable t) {
            log.warn("exception occured when logging output {}", t.toString());
        }finally{
            if(mdc){
                removeLoggerText();
            }
        }
    }


    protected Object buildLogMessageBody(Object arg, LogMask mask, StringBuilder text) {
        Object body = null;


        if (arg != null && LogUtils.isSimpleType(arg.getClass())) {
            // for simple types, log as string way
            if (mask != null) {
                if (mask.value() == LogMaskType.SimpleMask) {
                    // for simple mask, mark some chars
                    text = text.append(LogUtils.markString(String.valueOf(arg), LogMaskType.SimpleMask.getMask()));
                } else {
                    // for full mask, mask all chars with mask chars
                    text = text.append(LogUtils.markFullString(String.valueOf(arg), LogMaskType.FullMask.getMask()));
                }
            } else {
                // no mask, output object directly
                text = text.append(String.valueOf(arg));
            }


            body = text;
        } else {
            // output object
            body = arg;
        }


        return body;
    }


    protected String getLoggerText(JoinPoint jp, Method method){
        return StringUtils.join(new Object[] {jp.getTarget().getClass().getCanonicalName(), ".", method.getName()});
    }
    
    protected String getInputPrefix(JoinPoint jp, Method method, String prefix, int index) {
        String text = prefix;
        if (StringUtils.isBlank(prefix)) {
//            text = StringUtils.join(new Object[] { jp.getTarget().getClass().getCanonicalName(), ".", method.getName(),
//                    " args[", index, "]->" });
            text = StringUtils.join(new Object[] { "input args[", index, "]->" });
        }
        return text;
    }


    protected String getOutputPrefix(JoinPoint jp, Method method, String prefix) {
        String text = prefix;
        if (StringUtils.isBlank(prefix)) {
//            text = StringUtils.join(new Object[] { "==>", jp.getTarget().getClass().getCanonicalName(), ".", method.getName(),
//                    " output->" });
            text = StringUtils.join(new Object[] { "output==>"});       }
        return text;
    }


    protected void outputMessage(String prefix, Object text, LogLevel level) {
        if (level == LogLevel.INFO) {
            log.info("{}[{}]", prefix, text);
        } else if (level == LogLevel.DEBUG) {
            log.debug("{}[{}]", prefix, text);
        } else if (level == LogLevel.WARN) {
            log.warn("{}[{}]", prefix, text);
        } else if (level == LogLevel.ERROR) {
            log.error("{}[{}]", prefix, text);
        } else if (level == LogLevel.TRACE) {
            log.trace("{}[{}]", prefix, text);
        }
    }


    protected void putLoggerText(String loggerText){
        MDC.put(IO_LOGGER_KEY, loggerText);
    }
    
    protected void removeLoggerText(){
        MDC.remove(IO_LOGGER_KEY);
    }
    
    @SuppressWarnings("unchecked")
    private <T extends Annotation> T getParameterAnnotation(Annotation[] anns, Class<T> c) {
        T t = null;


        if (!ArrayUtils.isEmpty(anns)) {
            for (Annotation ann : anns) {
                if (ann.annotationType() == c) {
                    t = (T) ann;
                    break;
                }
            }
        }


        return t;
    }


    private Method getMethod(JoinPoint jp) {
        Method method = null;
        Signature signature = jp.getSignature();


        if (signature instanceof MethodSignature) {
            MethodSignature ms = (MethodSignature) jp.getSignature();
            method = AopUtils.getMostSpecificMethod(ms.getMethod(), jp.getTarget().getClass());
        }


        return method;
    }
}

Python 的 `logging` 模块是一个强大的工具,用于在应用程序中记录调试信息、错误日志以及其他有用的数据。下面是一个简单的例子,展示了如何设置和使用 `logging`: ```python import logging # 设置日志级别 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # 定义一个日志处理器 def log_info(message): logger = logging.getLogger(__name__) logger.info(message) # 使用日志处理器 log_info('This is an informational message.') log_info('An error occurred: %s', 'Something went wrong.') # 输出结果 # 输出时间戳、INFO级别标签和消息文本:"2023-04-16 15:27:48,123 - INFO - This is an informational message." # 输出时间戳、ERROR级别标签、异常信息:"2023-04-16 15:27:49,678 - ERROR - An error occurred: Something went wrong." # 更高级别的使用,可以自定义文件名和日志格式,例如: # handler = logging.FileHandler('application.log') # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # handler.setFormatter(formatter) # logger.addHandler(handler) ``` 在这个例子中,我们首先设置了日志的基本配置,然后创建了一个函数 `log_info` 来方便地插入日志信息。当调用 `log_info` 时,它会自动将当前时间和相应的信息添加到日志记录中。 通过修改 `level` 参数,你可以控制哪些级别的信息会被记录,例如 `debug`、`info`、`warning`、`error` 和 `critical` 等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值