0

I am trying to log information within my system.Whenever logging I do a check if a state is valid and only then do I log that information.

//doing this logging all over the place in my code base. 
if(checkIsValid){
  Object obj =new Object(string1,Integer2,........String10);
  log(obj);
}

The question here is how do I refactor my code so that I don't have to repeat this block of code everywhere for logging.

One of the solution is I could write a supplementary method like this.

 method(String1,Integer2,......String10){
  if(checkIsValid){
  Object obj =new Object(string1,Integer2,.........String10);
  log(obj);
  }
}

But the downside is that I would have to pass a number of strings as arguments to my method which does not look clean at all.

luckysing_noobster
  • 1,933
  • 5
  • 24
  • 50

3 Answers3

4

If you are using log4j for logging you can extends the logger class and overwrite the log, debug, error .... etc methods with your own validation.

If not you can do as you say: create a new method as below:

  public void validateAndLog(Object obj){
       if(checkIsValid){
          log(obj);
       }
  }

OR

 public void validateAndLog(String... strs){
           if(checkIsValid){
              log(Arrays.toString(strs));
           }
      }
Ali Helmy
  • 784
  • 6
  • 18
  • Note how the second example uses varargs - this lets you pass as many strings as you like to the method, as individual arguments to the method, and treats it as an array inside the method. – Carl Manaster Jul 10 '15 at 14:40
0

You could use a factory function for your object similar to

public Object createObjChecked(String1,......String10){
    Object obj = null;
    if(checkIsValid(String1, ..., String10)){
        obj = new Object(string1,.........String10);
        log(obj);
    }
    return obj;
}

Then you could check if the object was actually created at usage location.

nucleon
  • 1,128
  • 1
  • 6
  • 19
0

You solution is good. You are only missing passing varargs:

void myLogMethod(String format, Object args){
  if(checkIsValid){
    Object obj = new Object(format, args);
    log(obj);
  }
}

This is the kind of approach taken by slf4j. See http://www.slf4j.org/apidocs/org/slf4j/Logger.html

JnRouvignac
  • 807
  • 5
  • 19