Reputation: 212
I have a console app that interacts with hardware. My idea was to log all exceptions with their stacktraces so valuable information is not lost due to not having a pipe to a file.
But how to handle the location of that file? I cant ask for a path each time.
That is why i thought just put the file next to the executable. But cant be sure where the app will reside. And I have not found a distinct answer to "how to get the app path"
I found: new java.io.File("").getAbsolutePath();
But no explanation how this works.
And: getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
But the op said this only may work.
Is there another way to handle the errorlogging / a sure way to get the app path?
Upvotes: 0
Views: 128
Reputation: 10082
The standard approach to logging exceptions in all types of applications is to use one of the standard logging frameworks and defining its configuration externally to the application. Exceptions will be logged as ERROR
and handled appropriately.
One could suggest e.g. slf4j (logging interface) together with logback (the matching implementation), but other will do as well.
When writing the code, the interface needs to be available at compile time as the code is programmed and compiled against it:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyClass {
private static final Logger LOGGER = LoggerFactory.getLogger(Myclass.class);
public void method() {
try {
...
} catch (IOException ex) {
LOGGER.error("method failed to do what was expected: {}", ex);
throw ex;
}
A particular implementation needs to be provided at runtime (e.g. added to a jar while packaging) or added to the classpath at runtime.
Next, a configuration matching the particular implementation needs to be provided at runtime, which for logback may look like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>myapp.log</file>
<encoder>
<pattern>%logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="error">
<appender-ref ref="FILE"/>
</root>
</configuration>
Further details see under:
Upvotes: 1