2

I have a module that I'm working on which has the logger set up like this:

public class MyClass {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);

    public MyClass(String org, String division) {
        this.org = org;
        this.division = division;
    }

    public void myMethod() {
      if(blah) {
          LOGGER.log("Something happened");
      } else {
          LOGGER.log("Something went Wrong");
      }
    }
}

Now, this module is running for multiple orgs and divisions, so my logs look like this in Splunk:

Something happened
Something went Wrong
Something happened
Something happened
Something went Wrong

with no info of org or division, To fix this, someone started adding a addPrefix method, which looks like this:

private String addPrefix() {
    return String.format("(%s, %s)", this.org, this.division);
}

and updated logs to LOGGER.log("{} Something happened", addPrefix()); and LOGGER.log("{} Something went wrong", addPrefix());

Now our logs look like this:

(org1, div1) Something happened
(org1, div2) Something went Wrong
(org2, div3) Something happened

Problem is, as the number of logs increase, it's painful to maintain this and ensure everyone adds {}, addPrefix() to their logs. Is there a better way to do this?

I looked into mdc but could not figure out how to use it here.

Should I initialize my logger within my constructor where my parameters are all known? Will that affect logging in static methods? Is there a memory overhead to doing this?

navinpai
  • 955
  • 11
  • 33

1 Answers1

0

What do you mean "I looked into mdc but could not figure out how to use it here.". What you are describing is the "poster child" for when you would want to use the MDC. You would add the organization name and division name to the MDC at the start of the request (whatever that may be with the technology you are using) and then configure your chosen Logging Framework to add the organization and division to your output. You haven't provided any details on what framework you are using or what your configuration looks like but with Log4j 2 you would configure

<PatternLayout pattern="(%X{organization, division}) %msg%n"/>

assuming the keys you chose to store the data in were named "organization" and "division". This would result in output just like your example above.

rgoers
  • 8,696
  • 1
  • 22
  • 24