Browse Source

init

master
Tobias Hübner 5 months ago
commit
71dff7bb06
13 changed files with 682 additions and 0 deletions
  1. +6
    -0
      .gitignore
  2. +8
    -0
      README.md
  3. +45
    -0
      build.gradle.kts
  4. +188
    -0
      gradlew
  5. +100
    -0
      gradlew.bat
  6. +1
    -0
      settings.gradle.kts
  7. +32
    -0
      src/main/logging/Delete.java
  8. +52
    -0
      src/main/logging/LogPoint.java
  9. +5
    -0
      src/main/logging/Log_level.java
  10. +35
    -0
      src/main/logging/Logger.java
  11. +94
    -0
      src/main/logging/loggers/FileLogger.java
  12. +55
    -0
      src/main/logging/loggers/GelfLogger.java
  13. +61
    -0
      src/test/logging/T_Logger.java

+ 6
- 0
.gitignore View File

@@ -0,0 +1,6 @@
.gradle
.idea
build
gradle
logs
*.log

+ 8
- 0
README.md View File

@@ -0,0 +1,8 @@
# Logging

Features:

* logging exceptions with full stacktraces
* Uncaught exception logging (any exception that dont get caught in a try catch)
* Automatic deletion of old logs
* Thread safe logging

+ 45
- 0
build.gradle.kts View File

@@ -0,0 +1,45 @@
import java.net.URI

plugins {
`java-library`
`maven-publish`
}

repositories {
jcenter()
mavenCentral()
}

publishing {

publications {
register("mavenJava", MavenPublication::class) {
from(components["java"])
}
}
}

dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.5.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.5.1")
}

java {
withJavadocJar()
withSourcesJar()
}

group= "tobi"
version = "0.0.5"

sourceSets["main"].java {
srcDir("src/main")
}

sourceSets["test"].java {
srcDir("src/test")
}
val test by tasks.getting(Test::class) {
useJUnitPlatform()
testLogging.showStandardStreams=true
}

+ 188
- 0
gradlew View File

@@ -0,0 +1,188 @@
#!/usr/bin/env sh

#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
echo "$*"
}

die () {
echo
echo "$*"
echo
exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`

# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option

if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi

# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"

# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi

exec "$JAVACMD" "$@"

+ 100
- 0
gradlew.bat View File

@@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem

@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:init
@rem Get command-line arguments, handling Windows variants

if not "%OS%" == "Windows_NT" goto win9xME_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega

+ 1
- 0
settings.gradle.kts View File

@@ -0,0 +1 @@
rootProject.name = "log_point"

+ 32
- 0
src/main/logging/Delete.java View File

@@ -0,0 +1,32 @@
package logging;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class Delete {

public static int DELETE_LOGS_OLDER_THAN_DAYS = 30;

/**
* Deletes logs folder than {@link #DELETE_LOGS_OLDER_THAN_DAYS} from the specified directory and recursively its subdirs
*
* @param log_path directory
* @throws IOException
*/
public static void delete_old_logs(String log_path) throws IOException {
Files.find(Paths.get(log_path),
Integer.MAX_VALUE,
(filePath, fileAttr) -> {
if (filePath.endsWith(".log")) {
long days_since_creation = fileAttr.creationTime().toInstant().until(Instant.now(), ChronoUnit.DAYS);
return days_since_creation >= DELETE_LOGS_OLDER_THAN_DAYS;

}
return false;
})
.forEach(f -> f.toFile().delete());
}
}

+ 52
- 0
src/main/logging/LogPoint.java View File

@@ -0,0 +1,52 @@
package logging;

import java.util.HashSet;
import java.util.Set;

import static logging.Logger.stack_to_string;

public class LogPoint {


// Log all uncaught exceptions as uncaught
static {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
log(e, Log_level.Uncaught);
});
}
/**
* Needs to be volatile because:
* 1. Can change at any point
* 2. Log methods that depend on it could be called from any thread.
*/
private static volatile Logger logger ;

public static void initialize(Logger logger){
if(LogPoint.logger != null){
throw new IllegalStateException("LogPoint can only be initialized once!");
}
LogPoint.logger = logger;
}

public static void log(String... logtext) {
log(Log_level.Trace, logtext);
}

public static void log(Log_level ll, String... logtext) {
if(logger != null){
String format = logger.format(ll, logtext);
System.out.println(format);
logger.log(format);
}else{
System.out.println(ll.toString() + " - " + String.join(", ", logtext));
}
}

public static void log(Throwable e) {
log(e, Log_level.Error);
}

public static void log(Throwable e, Log_level ll) {
log(ll, stack_to_string(e));
}
}

+ 5
- 0
src/main/logging/Log_level.java View File

@@ -0,0 +1,5 @@
package logging;

public enum Log_level {
Error, Warning, Trace, Uncaught
}

+ 35
- 0
src/main/logging/Logger.java View File

@@ -0,0 +1,35 @@
package logging;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;

public interface Logger {

void log(String format);

String format(Log_level ll, String... messsages);

static String stack_to_string(Throwable e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
return errors.toString();
}

static String get_station(){
// determine station and user
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "unknown";
}

static String get_user(){
return System.getProperty("user.name") != null ? System.getProperty("user.name") : "unknown";
}


}

+ 94
- 0
src/main/logging/loggers/FileLogger.java View File

@@ -0,0 +1,94 @@
package logging.loggers;

import logging.Log_level;
import logging.Logger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;

public class FileLogger implements Logger {

private final String log_path;

private final LinkedBlockingQueue<String> write_queue = new LinkedBlockingQueue<>();

public FileLogger(String log_path) throws IOException {
this.log_path = log_path;
init_dir(log_path);

// this thread actually writes the logs. Since we are writing to disk
// there can be a delay. To avoid that the actual writing takes place in a
// seperate thread
Thread log_writer = new Thread(() ->{
while(true){
try {
String log = write_queue.take();
write(log, Paths.get(log_path, get_logfile_name()).toAbsolutePath().toString());
} catch (InterruptedException e) {
throw new IllegalStateException("Log Write Thread interrupted");
}
}
});
log_writer.setDaemon(true); // sonst verhindert logger beenden des programms
log_writer.start();

// write remaining logs on process exit
Runtime.getRuntime().addShutdownHook(new Thread(()->{
while(!write_queue.isEmpty()){
String log = write_queue.poll();
write(log, get_logfile_name());
}
}));
}

private static void init_dir(String log_path) throws IOException {
Files.createDirectories(Paths.get(log_path).toAbsolutePath());
}

private void write(String log, String file_path){
File file = new File(file_path);
try {
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
output.newLine();
output.write(log);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public String get_logfile_name() {
String datetime_format = "dd-MM-yy";
return String.format("%s@%s_%s.log", Logger.get_user(), Logger.get_station(), new SimpleDateFormat(datetime_format).format(new Date()));
}

@Override
public void log(String format) {
if(log_path != null && !write_queue.offer(format)){
throw new IllegalStateException("Log queue is full");
}
}

@Override
public String format(Log_level ll, String... text) {
return String.format(
"""
Level : %s\r
TS : %s\r
Thread : %s\r
{ %s }\r
""", ll.toString(), LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
Thread.currentThread().getName() + ":" + Thread.currentThread().getId(),
String.join("\n,", text));
}

}

+ 55
- 0
src/main/logging/loggers/GelfLogger.java View File

@@ -0,0 +1,55 @@
package logging.loggers;

import logging.Log_level;
import logging.Logger;

import java.io.IOException;
import java.net.*;

public class GelfLogger implements Logger {

private final DatagramSocket socket;

private final InetAddress host;
private final int port;

private final String program_name;

public GelfLogger(String program_name, String host, int port) throws SocketException, UnknownHostException {
this.host = InetAddress.getByName(host);
this.port = port;
this.program_name = program_name;
socket = new DatagramSocket();
}

@Override
public String format(Log_level ll, String... messsages) {
return String.format("""
{
"version": "1.1",
"host" : "%s",
"short_message" : "%s",
"user" : "%s",
"thread" : "%s",
"log_level" : "%s",
"program_name" : "%s"
}
""", Logger.get_station(), String.join("\n", messsages), Logger.get_user(),
Thread.currentThread().getName() + ":" + Thread.currentThread().getId(),
ll.toString(), program_name);
}

@Override
public void log(String format) {

var bytes = format.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, host, port);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}

}

+ 61
- 0
src/test/logging/T_Logger.java View File

@@ -0,0 +1,61 @@
package logging;

import logging.loggers.FileLogger;
import logging.loggers.GelfLogger;
import org.junit.jupiter.api.*;

import java.io.IOException;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;

//execute tests sequentially
@TestMethodOrder(MethodOrderer.Random.class)
public class T_Logger {

@Test
void log_file() throws InterruptedException, IOException {

FileLogger fl = new FileLogger("logs");
String message = "heyhohoho";

fl.log(fl.format(Log_level.Error, message));
Thread.sleep(2000);

String logfile = Files.readString(Paths.get("logs", fl.get_logfile_name()));

Assertions.assertTrue(logfile.contains(message) && logfile.contains("Error"));
}

// verify manually in graylog
@Test
void log_gelf() throws IOException {
GelfLogger gl = new GelfLogger("Test","bloc", 12201);

Set<Thread> threads = new HashSet<>();

for(int i = 0; i < 100; i++){
threads.add(new Thread(()->gl.log(gl.format(Log_level.Error, Logger.stack_to_string(new Exception("hey"))))));
}

threads.forEach(t -> t.start());
threads.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});

}

@Test
void log_point() throws IOException {
GelfLogger gl = new GelfLogger("Test","bloc", 12201);
LogPoint.initialize(gl);
LogPoint.log(new Exception("hey"));
}

}

Loading…
Cancel
Save