How to get Exception log from a console and write it to external file in java?


There are several logging frame works available to log your data in to files. You can also define your own method.

Example − Using I/O package

Following Java program has an array storing 5 integer values, we are letting the user to choose two elements from the array (indices of the elements) and performing division between them. We are wrapping this code in try block with three catch blocks catching ArithmeticException, InputMismatchException and, ArrayIndexOutOfBoundsException. In each of them we are invoking the writeToFile() method.

This method accepts an exception object, and appends it to a file using the write() method of the Files class.

Example

 Live Demo

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);
      }
   }
}

Output 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

Output 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

Output 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

Logging exceptions to a file using log4j

Following is an example which logs exceptions into a file using the logger library 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

Following Java program has an array storing 5 integer values, we are letting the user to choose two elements from the array (indices of the elements) and performing division between them. We are wrapping this code in try block with three catch blocks catching ArithmeticException, InputMismatchException and, ArrayIndexOutOfBoundsException. In each of them we are invoking the writeToFile() method.

This method accepts an exception object, and appends it to a file using the write() method of the Files class.

Example

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");
      }
   }
}

Output1

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

Output2

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

Output3

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
raja
Published on 12-Sep-2019 12:09:04
Advertisements