如何在Java中从控制台获取异常日志并将其写入外部文件?


有几种日志框架可用于将数据记录到文件中。您也可以定义自己的方法。

示例 - 使用 I/O 包

下面的 Java 程序有一个存储 5 个整数值的数组,我们允许用户从数组中选择两个元素(元素的索引)并在它们之间执行除法运算。我们将此代码包装在 try 块中,并使用三个 catch 块捕获 ArithmeticException、InputMismatchException 和 ArrayIndexOutOfBoundsException。在每个块中,我们都调用 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
"+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 zero
2019-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 块中,并使用三个 catch 块捕获 ArithmeticException、InputMismatchException 和 ArrayIndexOutOfBoundsException。在每个块中,我们都调用 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
"+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 zero
2019-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

更新于:2019年9月12日

1K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.