我有一种情况,我想将我创建的所有日志写入文本文件.
我们使用java.util.logging.Logger API来生成日志.
我试过了:
private static Logger logger = Logger.getLogger(className.class.getName());
FileHandler fh;
fh = new FileHandler("C:/className.log");
logger.addHandler(fh);
Run Code Online (Sandbox Code Playgroud)
但仍然只在控制台上登录....
Sri*_*ati 218
试试这个样本.这个对我有用.
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
Run Code Online (Sandbox Code Playgroud)
在MyLogFile.log中生成输出
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
Run Code Online (Sandbox Code Playgroud)
编辑:
要删除控制台处理程序,请使用
logger.setUseParentHandlers(false);
Run Code Online (Sandbox Code Playgroud)
因为ConsoleHandler是从父记录器注册的,所有记录器都来自该记录器.
小智 15
首先,您在哪里定义了记录器以及从哪个类\方法尝试调用它?有一个工作的例子,新鲜出炉:
public class LoggingTester {
private final Logger logger = Logger.getLogger(LoggingTester.class
.getName());
private FileHandler fh = null;
public LoggingTester() {
//just to make our log file nicer :)
SimpleDateFormat format = new SimpleDateFormat("M-d_HHmmss");
try {
fh = new FileHandler("C:/temp/test/MyLogFile_"
+ format.format(Calendar.getInstance().getTime()) + ".log");
} catch (Exception e) {
e.printStackTrace();
}
fh.setFormatter(new SimpleFormatter());
logger.addHandler(fh);
}
public void doLogging() {
logger.info("info msg");
logger.severe("error message");
logger.fine("fine message"); //won't show because to high level of logging
}
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您忘记定义格式化程序,如果您需要简单的格式化程序,您可以按照上面的说明进行操作,但还有另一个选项,您可以自己格式化,有一个示例(只需插入它而不是此行fh .setFormatter(新的SimpleFormatter())代码):
fh.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
SimpleDateFormat logTime = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(record.getMillis());
return record.getLevel()
+ logTime.format(cal.getTime())
+ " || "
+ record.getSourceClassName().substring(
record.getSourceClassName().lastIndexOf(".")+1,
record.getSourceClassName().length())
+ "."
+ record.getSourceMethodName()
+ "() : "
+ record.getMessage() + "\n";
}
});
Run Code Online (Sandbox Code Playgroud)
或任何其他任何你喜欢的修改.希望能帮助到你.
日志文件的位置可以通过logging.properties文件进行控制.它可以作为JVM参数传递:java -Djava.util.logging.config.file=/scratch/user/config/logging.properties
详细信息:https://docs.oracle.com/cd/E23549_01/doc.1111/e14568/handler.htm
配置文件处理程序
要将日志发送到文件,请将FileHandler添加到logging.properties文件中的handlers属性.这将启用全局文件记录.
handlers= java.util.logging.FileHandler 通过设置以下属性来配置处理程序:
java.util.logging.FileHandler.pattern=<home directory>/logs/oaam.log
java.util.logging.FileHandler.limit=50000
java.util.logging.FileHandler.count=1
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
Run Code Online (Sandbox Code Playgroud)
java.util.logging.FileHandler.pattern指定输出文件的位置和模式.默认设置是您的主目录.
java.util.logging.FileHandler.limit以字节为单位指定记录器写入任何一个文件的最大数量.
java.util.logging.FileHandler.count指定要循环的输出文件的数量.
java.util.logging.FileHandler.formatter指定文件处理程序类用于格式化日志消息的java.util.logging格式化程序类.SimpleFormatter编写简短的"人类可读"日志记录摘要.
要指示java使用此配置文件而不是$ JDK_HOME/jre/lib/logging.properties:
java -Djava.util.logging.config.file=/scratch/user/config/logging.properties
Run Code Online (Sandbox Code Playgroud)
小智 5
import java.io.IOException;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
/**
* @author Kiran
*
*/
public class MyLogger {
public MyLogger() {
}
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
Appender fh = null;
try {
fh = new FileAppender(new SimpleLayout(), "MyLogFile.log");
logger.addAppender(fh);
fh.setLayout(new SimpleLayout());
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
也许这就是你需要的......
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* LogToFile class
* This class is intended to be use with the default logging class of java
* It save the log in an XML file and display a friendly message to the user
* @author Ibrabel <ibrabel@gmail.com>
*/
public class LogToFile {
protected static final Logger logger=Logger.getLogger("MYLOG");
/**
* log Method
* enable to log all exceptions to a file and display user message on demand
* @param ex
* @param level
* @param msg
*/
public static void log(Exception ex, String level, String msg){
FileHandler fh = null;
try {
fh = new FileHandler("log.xml",true);
logger.addHandler(fh);
switch (level) {
case "severe":
logger.log(Level.SEVERE, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Error", JOptionPane.ERROR_MESSAGE);
break;
case "warning":
logger.log(Level.WARNING, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Warning", JOptionPane.WARNING_MESSAGE);
break;
case "info":
logger.log(Level.INFO, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Info", JOptionPane.INFORMATION_MESSAGE);
break;
case "config":
logger.log(Level.CONFIG, msg, ex);
break;
case "fine":
logger.log(Level.FINE, msg, ex);
break;
case "finer":
logger.log(Level.FINER, msg, ex);
break;
case "finest":
logger.log(Level.FINEST, msg, ex);
break;
default:
logger.log(Level.CONFIG, msg, ex);
break;
}
} catch (IOException | SecurityException ex1) {
logger.log(Level.SEVERE, null, ex1);
} finally{
if(fh!=null)fh.close();
}
}
public static void main(String[] args) {
/*
Create simple frame for the example
*/
JFrame myFrame = new JFrame();
myFrame.setTitle("LogToFileExample");
myFrame.setSize(300, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
JPanel pan = new JPanel();
JButton severe = new JButton("severe");
pan.add(severe);
JButton warning = new JButton("warning");
pan.add(warning);
JButton info = new JButton("info");
pan.add(info);
/*
Create an exception on click to use the LogToFile class
*/
severe.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"severe","You can't divide anything by zero");
}
}
});
warning.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"warning","You can't divide anything by zero");
}
}
});
info.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"info","You can't divide anything by zero");
}
}
});
/*
Add the JPanel to the JFrame and set the JFrame visible
*/
myFrame.setContentPane(pan);
myFrame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
347503 次 |
| 最近记录: |