How to log repeated warnings only once

后端 未结 4 2133
执念已碎
执念已碎 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:02

    Here is what I can come up with: a class that accumulates warnings which can be dumped at the end. It's in groovy, but you can get the point. The dumping part can be customized to use a logger, of course.

    class BadNews {
      static Map> warnings = [:];
    
      static void warn(String key, Object uniqueStuff) {
        def knownWarnings = warnings[key]
        if (! knownWarnings) {
          knownWarnings = []
          warnings[key] = knownWarnings
        }
        knownWarnings << uniqueStuff
      }
    
      static void dumpWarnings(PrintStream out) {
        warnings.each{key, stuffs ->
          out.println("$key: " + stuffs.size())
          stuffs.each{
            out.println("\t$it")
          }
        }
      }
    }
    
    class SomewhereElse {
      def foo(Bar bar) {
        if (! bar)
          BadNews.warn("Empty bar", this)
      }
    }
    

提交回复
热议问题