How to temporarily disable protocol tracing during a JavaMail IMAP connection

爱⌒轻易说出口 提交于 2019-12-13 04:47:30

问题


You can specify whether JavaMail emits a protocol-level trace either when setting the Properties for your Session (by setting the "mail.debug" property to "true") or by calling Session.setDebug before you do the store connect.

However, when the Protocol object gets instantiated, it creates a "protocol" TraceLogger that persists for the lifetime of the protocol object. Which appears to mean that you can't temporarily disable protocol-level debug logging on a connection once you start using it.

There is a Protocol.suspendTracing method. And it does allow you to temporarily turn off protocol trace output. A bunch of the IMAP auth methods use it to keep your credentials out of the logfile. But suspendTracing is protected, so it's not callable from regular user code.

Is there another way to temporarily turn off IMAP protocol tracing? (I'd prefer temporarily turning off just the traceInput logging, but I'm fine with disabling all logging.) Do I need to write and register a whole Protocol subclass so I can get access to Protocol.suspendTracing?


回答1:


You could use Session.setDebugOut to set your own stream and control it from there.

If you're using java.util.logging, you can change the logging level at any time.




回答2:


Not the best solution but, you can install a custom log filter on the com.sun.mail.imap.protocol logger to check that some specific thread is allowed to produce output. Assuming your connection is local to one thread

    public class ServiceFilter implements Filter {

        private static final ThreadLocal<javax.mail.Service> id = new ThreadLocal<>();

        public static void suspendTracing(javax.mail.Service s) {
            id.set(Objects.requireNonNull(s));
        }

        public static void enableTracing(javax.mail.Service s) {
            if (s.equals(id.get())) {
                id.remove();
            }
        }

        @Override
        public boolean isLoggable(LogRecord record) {
            return id.get() == null;
        }
    }

The downside is that this code becomes part of your project and it is another resource that you have to manage.



来源:https://stackoverflow.com/questions/30201743/how-to-temporarily-disable-protocol-tracing-during-a-javamail-imap-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!