How to log repeated warnings only once

后端 未结 4 2123
执念已碎
执念已碎 2021-02-12 23:36

There is a pattern that happens every now and then. I have a method called many times, and it contains this snippet:

Foo foo = getConfiguredFoo();
if (foo == nu         


        
4条回答
  •  渐次进展
    2021-02-13 00:16

    You could write a wrapper around your logging to store the last line logged. Depending on how you implement, you could add some sort of counter to log how many times it got logged or you may choose to subclass Logger instead of having an external wrapper. Could be configurable with a boolean suppressDuplicates if you needed that too.

    public class LogWrapper{
        Logger logger = Logger.getLogger("your logger here");
        String lastLine = new String();
    
        public void warn(String s){
            if (lastLine.compareToIgnoreCase(s) == 0)
                return;
            else {
                lastLine = s;
                logger.warn(s);
            }
        }
    }
    

提交回复
热议问题