2010-10-13 12 views
6

Actualmente estoy escribiendo un logger utilizando log4j. Una vez que cargué en un log4j.properties o un archivo log4j.xml, me preguntaba si había una forma de detectar si el archivo de configuración del registrador es válido. Si no es válido, esperaba cargar una configuración predeterminada (que está ubicada en otro archivo) en su lugar.log4j error de archivo de configuración detección

Gracias

+1

Sí, esto es condenado molesto, Estoy de acuerdo. Aunque no creo que puedas hacer esto. – skaffman

+0

Hice una buena búsqueda en Google y no apareció nada. Esperaba que el desbordamiento de pila pudiera darme una respuesta, pero supongo que tendré que confiar en la buena entrada del usuario si deciden alterar el archivo. ¡Gracias por su respuesta! :) – user459811

Respuesta

1

Sólo se puede tratar de comprobar manualmente si hay un registrador de ser inexistente o no.

http://svn.apache.org/viewvc/logging/log4j/trunk/src/main/java/org/apache/log4j/LogManager.java?view=markup

como: LogManager.exists ("registrador de su nombre");

Además, puede verificar si su xml es válido o no validarlo con la DTD.

Pero, ¿cuál es la definición de un archivo de registro "válido"? Si su única base de sintaxis utiliza la validación DTD y verifica si el archivo de propiedades está en buen formato.

Si un archivo es válido si tiene una constelación específica, utilice el enfoque manual anterior.

Espero que ayude, Cristiano

2

Hemos resuelto este problema mediante la reorientación de System.err antes de cargar la configuración y la comprobación de si los errores se registran en la corriente:

class ConfigurationLoader { 
    class Log4jConfigStderrStream extends ByteArrayOutputStream { 
     private int lineCount; 

     private StringBuilder output; 

     private PrintStream underlying; 

     public Log4jConfigStderrStream(PrintStream underlying) { 
      this.lineCount = 0; 
      this.output = new StringBuilder(""); 
      this.underlying = underlying; 
     } 

     @Override 
     public void flush() throws IOException { 
      String[] buffer; 
      synchronized (this) { 
       buffer = this.toString().split("\n"); 
       super.flush(); 
       super.reset(); 
       for (int i = 0; i < buffer.length; i++) { 
        String line = buffer[i].replace("\n", "").replace("\r", 
          ""); 
        if (line.length() > 0) { 
         this.lineCount++; 
         this.output.append(line); 
         this.output.append("\n"); 
        } 
       } 
      } 
     } 

     public String getOutput() { 
      return this.output.toString(); 
     } 

     public PrintStream getUnderlying() { 
      return this.underlying; 
     } 

     public boolean hasErrors() { 
      return this.lineCount == 0 ? false : true; 
     } 
    } 

    private String output; 

    public void flushOutput() { 
     if (!"".equals(this.output)) 
      System.err.print(this.output); 
    } 

    public boolean loadConfiguration(String filename) { 
     Log4jConfigStderrStream confErr; 
     confErr = new Log4jConfigStderrStream(System.err); 
     System.setErr(new PrintStream(confErr, true)); 
     LogManager.resetConfiguration(); 
     DOMConfigurator.configure(filename); 
     System.setErr(confErr.getUnderlying()); 
     this.output = confErr.getOutput(); 
     return !confErr.hasErrors(); 
    } 
} 
Cuestiones relacionadas