Programmazione:Java/Logging

Da WikiSitech.
Vai alla navigazioneVai alla ricerca

Logging

Per loggare avere un log 'utilizzabile' è necessario che l'eccezione venga loggata al massimo due volte:

  • Chi intercetta l'eccezione originale deve loggare senza lo stacktrace e trasformarla in un eccezione applicativa
  • Chi intercetta l'eccezione applicativa deve loggare l'eccezione completa di stacktrace

tutti gli altri punti in cui passa l'eccezione devono propagarla senza intercettarla e riloggarla nuovamente

Bad Practice (case 1) public class A {

  public static void f() throws AppException {
     try {
        // Do something
     } catch(Throwable t) {
        throw new AppException(t);
     }
  }

}

public class B {

  void f1() {
     try {
        A.f();
     } catch(AppException t) {
     }      
  }

}

Bad Practice (case 2) public class A {

  public static void f() throws AppException {
     try {
        // Do something
     } catch(Throwable t) {
        t.printStackTrace();
        throw new AppException(t);
     }
  }

}

public class B {

  void f1() {
     try {
        A.f();
     } catch(AppException t) {
        t.printStackTrace();
     }      
  }

}

Bad Practice (case 3)

public class A {

  public static void f() throws TExcept {
     try {
        // Do something
     } catch(Throwable t) {
        System.out.println(t.getMessage();
        throw new TExcept(t);
     }
  }

}

public class B {

  void f1() {
     try {
        A.f();
     } catch(TExcept t) {
        System.out.println(t.getMessage();
     }      
  }

}