How to log repeated warnings only once

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

    I faced a similar problem sometime ago but could not find any way of dealing with this in Log4J. I finally did the following:

    Foo foo = getConfiguredFoo();
    if (foo == null) {
      if(!warningLogged)logger.warn("Foo not configured");
      warningLogged = true
      foo = getDefaultFoo();
    }
    

    This solution is OK if you have one or two log statements you don't want to see repeated in your logs but does not scale up with more log statements (you need a boolean for every message logged)

提交回复
热议问题