[英]Logger handler wont work in different classes java
I'm pretty new in Java but I have to write a simple logger. 我是Java的新手,但我必须编写一个简单的记录器。 My problem is that my logger won't transfer its handler. 我的问题是我的记录器不会转移其处理程序。
My first class is: 我的第一堂课是:
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);
}
}
and i want to transfer the logger to another class by doing this: 我想通过这样做将记录器转移到另一个类:
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" );
}
}
i tried nearly everything that i've found, and the logger functions but it only gives its output on console and not how it should be in a file 我尝试了几乎所有找到的内容以及logger功能,但它仅在控制台上提供其输出,而不是在文件中的显示方式
change this: 改变这个:
static final Logger logger = Logger.getLogger("myLogger");
To 至
public static final Logger logger = Logger.getLogger("myLogger");
Reason you have given it a default access in your class where you defined Logger and using defail access you can access it in package only. 您在定义Logger的类中为其提供了默认访问权限的原因,并且使用defail访问权限只能在包中访问它。 While where you are using is you have another package and hence error. 当您使用的是另一个软件包时,会出现错误。
Apart form above use logger like: 上面的其他形式使用记录器,例如:
LoggerInterface.logger.info( "Hat funktioniert" );
Since you defined it static so use classname.instance.method(parameter) 由于您将其定义为静态,因此请使用classname.instance.method(parameter)
In your test you never configured your logger. 在测试中,您从未配置过记录器。 Try this: 尝试这个:
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" );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.