2014-11-03 22 views
0

我在Java中很新,但我必须编写一个简单的记录器。 我的问题是我的记录器不会传输它的处理程序。记录器处理程序不会在不同的类中工作java

我第一类是:

public class LoggerClass { 
    static final Logger logger = Logger.getLogger("myLogger"); 

    FileHandler fh; 
     public LoggerClass() { 
     try { 
      this.fh = new FileHandler("C:/Users/Administrator/Desktop/Logging%u.txt"); 
     } catch (IOException | SecurityException ex) { 
      Logger.getLogger(LoggerClass.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     logger.addHandler(fh); 
     SimpleFormatter formatter = new SimpleFormatter(); 
     fh.setFormatter(formatter); 

    } 

} 

,我想通过这样的记录转移到另一个类:

package Logger; 
import static Logger.LoggerClass.logger; 
import java.io.IOException; 
import java.util.logging.Level; 

public class LoggingTest { 

    public static void main(String[] args) throws IOException { 

     try 
    { 
     ((Object) null).toString(); 
    } 
    catch (Exception e) 
    { 
     logger.log(Level.SEVERE, "oh oh", e); 
    } 

    logger.info("Hat funktioniert"); 
    } 
    } 

我想几乎所有我发现,并记录器功能但它只在控制台上给出它的输出,而不是它应该如何在文件中

+0

请注意,您有几件事情是错误的 - 在类之间共享记录器实例并在不是例如时调用您的类接口。记录器通常应该使用外部配置进行配置,通常是静态配置文件:.xml或.properties。 – eis 2014-11-03 12:50:44

+0

我很抱歉“LoggerInterface”的事情,它是从以前的尝试。 – 2014-11-03 13:15:55

回答

0

在你测试你从来没有配置你的记录。试试这个:

package Logger; 
    import static Logger.LoggerClass.logger; 
    import java.io.IOException; 
    import java.util.logging.Level; 

    //There are better ways to do this. 
    static { 
     new LoggerClass(); 
    } 

    public class LoggingTest { 



    public static void main(String[] args) throws IOException { 

     try 
    { 
     ((Object) null).toString(); 
    } 
    catch (Exception e) 
    { 
     logger.log(Level.SEVERE, "oh oh", e); 
    } 

    logger.info("Hat funktioniert"); 
    } 
    } 
0

更改此项:

static final Logger logger = Logger.getLogger("myLogger"); 

public static final Logger logger = Logger.getLogger("myLogger"); 

原因,你给了它在您定义记录器和使用defail访问你只能访问它在你的包一类的默认访问。当你使用的是你有另一个包,因此错误。

除了上述形式使用日志如:

LoggerInterface.logger.info("Hat funktioniert"); 

既然你将它定义静态的,所以使用classname.instance.method(参数)