如何从控制台获取异常日志并将其写入Java中的外部文件?
有几种日志记录框架可用于将数据记录到文件中。您也可以定义自己的方法。
示例-使用I / O包
下面的Java程序具有一个存储5个整数值的数组,我们让用户从数组中选择两个元素(元素的索引)并在它们之间进行除法。我们将这段代码包装在try块中,其中包含三个捕获ArithmeticException,InputMismatchException和ArrayIndexOutOfBoundsException的catch块。在每个方法中,我们都在调用writeToFile()方法。
此方法接受异常对象,并使用Files类的write()方法将其附加到文件中。
示例
import java.io.IOException;import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class LoggingToFile {
private static void writeToFile(Exception ex) throws IOException {
//Retrieving the log file
Path logFile = Paths.get("ExceptionLog.txt");
//Preparing the data to be logged
byte bytes[] = ("\r\n"+LocalDateTime.now()+": "+ ex.toString()).getBytes();
//Appending the exception to your file
Files.write(logFile, bytes, StandardOpenOption.APPEND);
System.out.println("Exception logged to your file");
}
public static void main(String [] args) throws IOException {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)");
try {
int a = sc.nextInt();
int b = sc.nextInt();
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Warning: You have chosen a position which is not in the array");
writeToFile(ex);
}catch(ArithmeticException ex) {
System.out.println("Warning: You cannot divide an number with 0");
writeToFile(ex);
}catch(InputMismatchException ex) {
System.out.println("Warning: You have entered invalid input");
writeToFile(ex);
}
}
}
输出1
Enter 3 integer values one by one:Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
2
4
Warning: You cannot divide an number with 0
Exception logged to your file
输出2
Enter 3 integer values one by one:Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
5
12
Warning: You have chosen a position which is not in the array
Exception logged to your file
输出3
Enter 3 integer values one by one:Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
hello
Warning: You have entered invalid input
Exception logged to your file
ExceptionLog.txt
2019-07-19T17:57:09.735: java.lang.ArithmeticException: / by zero2019-07-19T17:57:39.025: java.lang.ArrayIndexOutOfBoundsException: 12
2019-07-19T18:00:23.374: java.util.InputMismatchException
使用log4j将异常记录到文件
以下是使用记录器库log4j将异常记录到文件中的示例。
Log4j2.xml
<?xml version="1.0" encoding="UTF-8"?><Configuration status="warn" name="Example" packages="">
<Appenders>
<File name="file" fileName="d:/example.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="file"/>
</Root>
</Loggers>
</Configuration
Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 ">http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.javacodegeeks.snippets.enterprise</groupId>
<artifactId>log4jexample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>
</project>
LoggingToFile.java
下面的Java程序具有一个存储5个整数值的数组,我们让用户从数组中选择两个元素(元素的索引)并在它们之间进行除法。我们将这段代码包装在try块中,其中包含三个捕获ArithmeticException,InputMismatchException和ArrayIndexOutOfBoundsException的catch块。在每个方法中,我们都在调用writeToFile()方法。
此方法接受异常对象,并使用Files类的write()方法将其附加到文件中。
示例
import java.io.IOException;import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LoggingToFile {
static Logger log = LogManager.getLogger(Sample.class.getName());
private static void writeToFile(Exception ex) throws IOException {
//Retrieving the log file
Path logFile = Paths.get("ExceptionLog.txt");
//Preparing the data to be logged
byte bytes[] = ("\r\n"+LocalDateTime.now()+": "+ ex.toString()).getBytes();
//Appending the exception to your file
Files.write(logFile, bytes, StandardOpenOption.APPEND);
System.out.println("Exception logged to your file");
}
public static void main(String [] args) throws IOException {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)");
try {
int a = sc.nextInt();
int b = sc.nextInt();
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Warning: You have chosen a position which is not in the array");
log.info(ex.toString());
System.out.println("Exception logged to your file");
}catch(ArithmeticException ex) {
System.out.println("Warning: You cannot divide an number with 0");
log.info(ex.toString());
System.out.println("Exception logged to your file");
}catch(InputMismatchException ex) {
System.out.println("Warning: You have entered invalid input");
log.info(ex.toString());
System.out.println("Exception logged to your file");
}
}
}
输出1
Array: [10, 20, 30, 2, 0, 8]Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
2
4
Warning: You cannot divide an number with 0
Exception logged to your file
输出2
Array: [10, 20, 30, 2, 0, 8]Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
5
12
Warning: You have chosen a position which is not in the array
Exception logged to your file
输出3
Array: [10, 20, 30, 2, 0, 8]Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
hi
Warning: You have entered invalid input
Exception logged to your file
ExceptionLog.txt
2019-08-01 13:53:13,943 INFO a.Sample [main] java.lang.ArithmeticException: / by zero2019-08-01 13:53:45,127 INFO a.Sample [main] java.lang.ArrayIndexOutOfBoundsException: 12
2019-08-01 13:54:06,500 INFO a.Sample [main] java.util.InputMismatchException
以上是 如何从控制台获取异常日志并将其写入Java中的外部文件? 的全部内容, 来源链接: utcz.com/z/322481.html