Commit 5e571899 authored by Daniel Eggert's avatar Daniel Eggert
Browse files

added user.home log file location fallback

parent 2c7f4738
......@@ -6,6 +6,9 @@ package de.potsdam.gfz.gms.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import org.slf4j.impl.SimpleLogger;
......@@ -16,6 +19,9 @@ import org.slf4j.impl.SimpleLogger;
*/
public class GmsProperties {
private static final String SYS_USERNAME_PROP_KEY = "user.name";
private static final String SYS_USERHOME_PROP_KEY = "user.home";
private static final String LOG_LEVEL_KEY = "module.log.level";
private static final String SIMPLE_LOG_PACKAGE_LEVEL_KEY = "org.slf4j.simpleLogger.log." + "de.potsdam.gfz.gms";
private static final String DEFAULT_MODULE_LOG_LEVEL = "info";
......@@ -66,9 +72,36 @@ public class GmsProperties {
* @param cls
*/
public static void setDefaultLoggerProperties(String loggerName, Properties props) {
// set log format
System.setProperty(SimpleLogger.SHOW_DATE_TIME_KEY, "true");
System.setProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, "yyyy.MM.dd HH:mm:ss");
System.setProperty(SimpleLogger.LOG_FILE_KEY, loggerName + ".log");
// set log filename and append current username
String username = System.getProperty(SYS_USERNAME_PROP_KEY);
String logfilename = loggerName + "-" + username + ".log";
Path logfile = Paths.get(logfilename);
if (!canWriteOrCreate(logfile)) {
// we can not write to the default path - try user home
System.err.println("unable to access logfile at '" + logfile.toAbsolutePath().toString() + "'.");
String userhome = System.getProperty(SYS_USERHOME_PROP_KEY);
logfile = Paths.get(userhome).resolve(logfile);
logfilename = logfile.toString();
if (!canWriteOrCreate(logfile)) {
// unable to write to this file either - use std.err
System.err.println("unable to access logfile at '" + logfile.toAbsolutePath().toString() + "'.");
logfilename = "System.err";
}
} else {
logfilename = logfile.toAbsolutePath().toString();
}
System.err.println("logging to '" + logfilename + "'");
System.setProperty(SimpleLogger.LOG_FILE_KEY, logfilename);
// set default log level (for all 3rd party classes) to warning
System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "warn");
......@@ -82,6 +115,19 @@ public class GmsProperties {
System.setProperty(SIMPLE_LOG_PACKAGE_LEVEL_KEY, moduleLogLevel);
}
private static boolean canWriteOrCreate(Path path) {
if (Files.notExists(path)) {
// the file does not yet exist
try {
Files.createFile(path);
} catch (Throwable t) {
return false;
}
}
return Files.isWritable(path);
}
/**
* Sets the logger properties via system properties.
*
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment