Search code examples
javaerror-handlingfatal-errorerror-logging

How to add the timestamp of the fatal error occurrence to Java fatal error log filename


Background

  • You can use java -XX:ErrorFile=/path/to/file to specify the path of fatal error log file.
  • You can use the -XX:OnError option to execute a command when an error causes on a Java VM.
  • To maintain the fatal error logs, I want to add the timestamp of the fatal error occurrence to the filename.

Problem

I have tried to set the Java VM option like this:

java -XX:ErrorFile=/path/to/error.log -XX:OnError="mv /path/to/error.log /path/to/error_store/error_$(date +%F-%H%M%S).log" -jar /path/to/application.jar

But when an error occurs on Java VM, the timestamp on the filename is the time of the Java VM's startup, rather than the time of occurrence of the fatal error.

Question

Is there any way to add the timestamp of the fatal error occurrence to the Java fatal error log filename?


Solution

  • I found a solution. To make the command expansion works later, you have to pass $ as a literal (use \$(...)) like:

    java -XX:ErrorFile=/path/to/error.log -XX:OnError="mv /path/to/error.log /path/to/error_store/error_\$(date +%F-%H%M%S).log" -jar /path/to/application.jar
    

    and when a fatal error occurred, the following command was executed:

    # An error report file with more information is saved as:
    # /path/to/error.log
    #
    # -XX:OnError="mv /path/to/error.log /path/to/error_store/error_$(date +%F-%H%M%S).log"
    #   Executing /bin/sh -c "mv /path/to/error.log /path/to/error_store/error_$(date +%F-%H%M%S).log" ...
    Aborted