Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging java jar stdout & stderr to a file in linux

Tags:

java

bash

jar

I found a script that I can use for my jar file. My question is how can I modify it to log stdout and stderr to file.

As I understand that this line should be modified:

nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &

What does "/tmp" indicate? /dev/null means it is not directing anuthing to anywhere?

Here is the script I'm using:

#!/bin/sh
SERVICE_NAME=MyService
PATH_TO_JAR=/usr/local/MyProject/MyJar.jar
PID_PATH_NAME=/tmp/MyService-pid
case $1 in
    start)
        echo "Starting $SERVICE_NAME ..."
        if [ ! -f $PID_PATH_NAME ]; then
            nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &
                        echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is already running ..."
        fi
    ;;
    stop)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stoping ..."
            kill $PID;
            echo "$SERVICE_NAME stopped ..."
            rm $PID_PATH_NAME
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
    restart)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stopping ...";
            kill $PID;
            echo "$SERVICE_NAME stopped ...";
            rm $PID_PATH_NAME
            echo "$SERVICE_NAME starting ..."
            nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &
                        echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
esac

I would like to log everything to /var/log/myservice.log file. Any help is appreciated!

like image 492
lkallas Avatar asked Sep 18 '15 17:09

lkallas


1 Answers

I found this solution:

nohup java -jar $PATH_TO_JAR > /var/log/myservice.log  2>&1 &

When I deleted the log file while the servce was running it didn't create a new one altough it was streaming to stdout.

like image 137
lkallas Avatar answered Sep 23 '22 18:09

lkallas