How do I make my jar application generate a crash log file? - java

I've made an application and exported it as jar file.
If the jar-application crashes for some reason I want it to generate a crash-log text file with the error.
If I run the application in Eclipse, then eclipse always tells me where it crashed, can I get the same kind of message in a text-file instead when running the application as a jar?
I run my jar-file by typing this:
java -jar MyApplication.jar
Can I add something to this command in order to generate a crash-log if a crash occurs?
Thanks!

I used this solution in the end, which works exactly like I want it to.
Everytime the application crashes it saves the exception in a text file in a subfolder named "crashlogs" with the date and time as filename.
Just added this code at the start of my main function
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String filename = "crashlogs/"+sdf.format(cal.getTime())+".txt";
PrintStream writer;
try {
writer = new PrintStream(filename, "UTF-8");
writer.println(e.getClass() + ": " + e.getMessage());
for (int i = 0; i < e.getStackTrace().length; i++) {
writer.println(e.getStackTrace()[i].toString());
}
} catch (FileNotFoundException | UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});

you can use logging framework like log4j
simple example
Java
import org.apache.log4j.Logger;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class log4jExample{
/* Get actual class name to be printed on */
static Logger log = Logger.getLogger(
log4jExample.class.getName());
public static void main(String[] args)
throws IOException,SQLException{
log.debug("Hello this is an debug message");
log.info("Hello this is an info message");
}
}
log4j.properties
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
If you want to do it without loging

Related

My logging.properties custom formatter is not working

I'm actually adding java logging (can't use other framework) to my project. I build my app on a .war, and deployed it over Weblogic, the logger is working with my logging.properties config, except for the formatter i don't know why the app is ignoring it.
This is my class where i prepare the logger;
public class CtgLogger {
private static final String LOAD_ERROR = "Properties could not be loaded.";
private static final Map<String, Level> LEVEL_MAP;
private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
static {
final InputStream inputStream = CtgLogger.class.getResourceAsStream("/logging.properties");
try {
LogManager.getLogManager().readConfiguration(inputStream);
} catch (Exception e) {
Logger.getAnonymousLogger().severe(LOAD_ERROR);
Logger.getAnonymousLogger().severe(e.getMessage());
}
// and I add the LEVEL_MAP to the logger...
And this is my properties...
handlers = java.util.logging.FileHandler
java.util.logging.FileHandler.pattern=logsfolder/CTGLOG_%g.log
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.limit=3000
java.util.logging.FileHandler.count=6
#java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
#If I use the SimpleFormatter, apps goes well with it format.
java.util.logging.FileHandler.formatter = com.package.my.log.JsonCustomFormatter
#If I use my custom formatter, the weblogic works with a XMLFormatter (default)
I know the .properties is working, because logger is working with the pattern, limit and count I setted.
PD: If i run my app with JUnit, logs are working with my custom formatter, but do not at weblogic! Don't know why!
Weblogic is going to have multiple class loaders. The standard LogManager can only see classes loaded via the system class loader. Check the Server Log for errors related to not finding your custom class. If that is the case, you have to move your formatter to the system classloader. Otherwise you have have to use code to install your formatter from your web app which is running in a child classloader.
There are also bugs in the LogManager.readConfiguration and alternative methods to use in JDK9 and later.
Using Eclipse and java standard logger may be painful. I found something to produce similar output to Log4J:
"%d{HH:mm:ss,SSS} %-5p %m (%F:%L) in %t%n" in Log4J : you can click on reference and you are there log was issued
21:36:37,9 INFO process model event Digpro2021a/digpro.Digpro(Digpro.java:358) in processModelEvent
21:36:37,9 INFO start polling Digpro2021a/digpro.Digpro(Digpro.java:398) in processEventAutoreload
21:36:37,9 INFO reload now Digpro2021a/digpro.Digpro(Digpro.java:370) in processModelEvent
public class Digpro {
protected static final Logger L = Logger.getLogger("Digpro");
//logger conf
static {
L.setLevel(Level.FINE);
Handler handler = Logger.getLogger("").getHandlers()[0];
handler.setLevel(Level.FINE); // Default console handler
handler.setFormatter(new Formatter() {
#Override
public String format(LogRecord r) {
Date d = new Date(r.getMillis());
String srcClassLong = r.getSourceClassName();
String[] aClass = srcClassLong.split("\\$")[0].split("\\.");
String srcClass = aClass[aClass.length - 1];
StackTraceElement elem = (new Throwable()).getStackTrace()[7];
int line = elem.getLineNumber();
String modulName = elem.getModuleName();
return String.format("%tH:%tM:%tS,%tl %.7s %s %s/%s(%s.java:%d) in %s\n", d, d, d, d, //
r.getLevel(), r.getMessage(), // LEVEL and message
modulName, srcClassLong, srcClass, line, r.getSourceMethodName()); //ref to click on
}
});
}
...
public static class TestDigpro extends Digpro {
//TESTING:
#Test
public void testLogFormat() {
L.info("poll info");
L.fine("got fine");
}
}
}
produses:
21:51:20,9 INFO poll info Digpro2021a/digpro.Digpro$TestDigpro(Digpro.java:723) in testLogFormat
21:51:20,9 FINE got fine Digpro2021a/digpro.Digpro$TestDigpro(Digpro.java:724) in testLogFormat

Make java logging at the same folder of the JAR

How to make java logging at the same folder of the JAR?
Thank you!
import java.util.logging.*;
public class Worker {
private static final Logger logger = Logger.getLogger(Worker.class.getName());
public static void main(String[] args) {
logger.info("Logging begins...");
try {
throw new Exception("Simulating an exception");
} catch (Exception ex){
logger.log(Level.SEVERE, ex.getMessage(), ex);
}
logger.info("Done...");
}
}
Add a Handler for the Logger you're using. FileHandler is particularly good here:
Handler h = new FileHandler("my-log.log");
h.setFormatter(new SimpleFormatter()); //set format to what you normally see
logger.addHandler(h);
It will use the system property java.util.logging.SimpleFormatter.format for formatting the text, so you can either adjust the property to your use, or implement Formatter and set one yourself.
An example using the property would be:
"[%1$tH:%1$tM:%1$tS] %4$s: %5$s%n"
Which is a format I commonly see.

Java opening File Streams in one class and closing/deletion of file in another class

I want to delete the file which is opened and done writing but not closed. Please refer to code below:
Class A (can't be changed):
import java.io.FileOutputStream;
public class A {
public void run(String file) throws Exception {
FileOutputStream s = new FileOutputStream(file);
}
}
Class B:
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class B {
public static void main(String[] args) throws Exception {
String path = "D:\\CONFLUX_HOME\\TestClient\\Maps\\test\\newTest.txt";
A a = new A();
a.run(path);
File f = new File(path);
Files.delete(Paths.get(f.getAbsolutePath()));
}
}
In Class A , just open the stream without closing the file.
In class B , calling A's run method and then try to delete the file.
Since the file is still opened. I'm unable to delete the file.
Error is :
The process cannot access the file because it is being used by another process.
Actual Scenario is :
We are loading the jars dynamically. Classes inside jar are creating the file. When there is an exception, a file gets created whose size will be 0 bytes. We need to delete this file. Since the file is not closed during the exception, we can't delete the file.
We could fix the issue if we could close the streams in the jar classes, but we can't modify the jars that create the files as they are client specific jars.
Please suggest how to delete the opened file, without modifying the code in class A.
Make sure you close the file, even if there was an Exception when writing to it.
E.g.
public void run(String file) throws Exception {
FileOutputStream s = null;
try {
s = new FileOutputStream(file);
} finally {
try {
s.close();
} catch(Exception e) {
// log this exception
}
}
}
You have to close the file before any delete operation as firstly its a bad practice and second is it will lead to memory leaks.
If you are using Tomcat, it is possible to set AntiLockingOption and antiJARLocking in $CATALINA_HOME/conf/context.xml for Windows:
<Context antiJARLocking="true" antiResourceLocking="true" >
Important note:
The antiResourceLocking option can stop JSPs from redeploying when they are edited requiring a redeploy.
Read more about this option:
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html
antiResourceLocking:
If true, Tomcat will prevent any file locking. This will significantly impact startup time of applications, but allows full webapp hot deploy and undeploy on platforms or configurations where file locking can occur. If not specified, the default value is false.
Pass the resource as a parameter and it becomes the caller's responsibility to clear up the resources
public void run(FileOutputStream stream) throws Exception {
...
}
caller:
try(FileStream stream = new FileStream(path)){
A a = new A();
a.run(stream);
}catch(Exception e){
.. exception handling
}
Updated according to OPs comment.
Another approach could be to subclass A and override run().
public static void main(String[] args) throws Exception {
String path = "D:\\CONFLUX_HOME\\TestClient\\Maps\\test\\newTest.txt";
A a = new A() {
#Override
public void run(String file) throws Exception {
FileOutputStream s = new FileOutputStream(file);
s.close();
}
};
a.run(path);
File f = new File(path);
Files.delete(Paths.get(f.getAbsolutePath()));
System.out.println("foo");
}
I don't think you'll find a pure java solution to this problem. One option is to install Unlocker (being careful to hit "Skip" on all the junkware) and invoke it from your code.
If you have UAC enabled, you'll also need to be running your java in an elevated process (e.g. start command prompt as Administrator). Then, assuming unlocker is in C:\Program Files\Unlocker:
Process p = new ProcessBuilder("c:\\Program Files\\Unlocker\\Unlocker.exe",path,"-s").start();
p.waitFor();
And after that you can delete the file as before. Or you could use "-d" instead of "-s" and Unlocker will delete the file for you.

generating logs of simple java class with log4j api

I have one query is that if I write a simple Java class and I want to see the logs that are executed at the behind, such that are executed at the backend by the JVM. I have log4j JAR with me. Could you please give me advice to how to achieve this?
I would to see the same logs that are generated in case of a WebApp, so I can reuse it for a Java App.
try looking at log4j api/demo here http://www.vaannila.com/log4j/log4j-tutorial/log4j-tutorial.html
you can generate log for any class and any application afaik using log4j , which needs not necessarily be a web app
Here is a very simple example that you should be able to adapt to what you are trying to achieve.
Step 1:Import log4j jar file in your project
Step 2:-Create a Log java file
public Log(Class className) {
logger = Logger.getLogger(className.getClass());
logger.getClass();
final String LOG_PROPERTIES_FILE_NAME = "log4j.properties";
props = loadLogFile(LOG_PROPERTIES_FILE_NAME, className);
//props =getPropsFile(LOG_PROPERTIES_FILE_NAME, className);
PropertyConfigurator.configure(props);
}
public static Properties loadLogFile(String propertyFile, Class className) {
//String filePath="";
try {
Properties ps = null;
ResourceBundle bundle = ResourceBundle
.getBundle("resource.DbProperties");
String logPath = bundle.getString("logs.path");
File filePath = new File(logPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
props.clone();
props = getPropsFile(propertyFile, className);
props.setProperty("info_file_path", filePath.toString());
// PropertyConfigurator.configure(props);
} catch (Exception e) {
e.printStackTrace();
}
return props;
}
public void info(String message) {
logger.info(message);
}
public void warn(String message) {
logger.warn(message);
}
public void error(String message) {
logger.error(message);
}
public void fatal(String message) {
logger.fatal(message);
}
public void printStackTrace(Throwable ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
logger.error("\n" + sw.toString());
}
log4j.properties
log4j.rootCategory=LOGFILE
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=${info_file_path}\\info_Pension_application.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.Threshold=INFO
log4j.appender.LOGFILE.Threshold=DEBUG
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
If your "simple Java class" happens to be in a Java EE container (like a .jsp or servlet in Tomcat, JBoss or WebSphere), then all you need to do is:
1) import org.apache.log4j.Logger;
2) declare a static instance in your class:
EXAMPLE: `static Logger logger = Logger.getLogger ("MyApp");`
3) Use your logger
EXAMPLE: `logger.info ("something interesting happened");`
4) If you include log4j.java and your own log4j.properties in your CLASSPATH, then you don't need to do anything else.
Here's a bit more info on using log4j with Tomcat or app servers:
http://tomcat.apache.org/tomcat-5.5-doc/logging.html
http://logging.apache.org/log4j/1.2/manual.html
http://www.tutorialspoint.com/log4j/log4j_quick_guide.htm
Here's a very simple example program that "does logging", from the above tutorialspoint.com link:
import org.apache.log4j.Logger;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class log4jExample{
/* Get actual class name to be printed on */
static Logger log = Logger.getLogger(
log4jExample.class.getName());
public static void main(String[] args)
throws IOException,SQLException{
log.debug("Hello this is an debug message");
log.info("Hello this is an info message");
}
}

Writing duplicate data when using Log4j in Jboss webservice

I am using Log4j with Jboss EJB webservice. I am logging the application flow in the File.
This is the code I am using for logging
FileAppender fileappender;
File file = new File("jws_" + getCurrentDate("dd_MMM_yyyy") + ".log");
Logger log = null;
System.out.println(file.getAbsolutePath() );
try
{
log = Logger.getLogger(ConnMan.class);
fileappender = new FileAppender(new PatternLayout(),"f2cjws_" + getCurrentDate("dd_MMM_yyyy") + ".log");
log.addAppender(fileappender);
if (!theLogLevel.equalsIgnoreCase("error"))
{
if ("yes".equalsIgnoreCase(getProperties().getProperty("log")))
{
log.debug(getCurrentDate("dd MMM yyyy HH:mm:ss 1")+" "+theError);
}
}
else
{
log.debug(getCurrentDate("dd MMM yyyy HH:mm:ss 1")+" "+theError);
}
}
catch (IOException e)
{
System.out.println("Logger failed due to "+e.getMessage());
}
catch(Exception e)
{
System.out.println("Logger failed due to "+e.getMessage());
}
When I run the application, I am getting duplicate data in my file, i.e.., same data is written twice or thrice. The above code worked fine in webapplication deployed in tomcat.
So I feel I am missing something in related to JBoss.
This webservice now currently uses the log4j properties built in with the server. Can I know how to make it to use application's own properties file?
Please help me,
Thanks in advance,
You need to create your own log writer,
public final class LogWriter
{
private static Logger appLogger = null;
private static String className = LogWriter.class.getName() + ".";
static
{
try
{
appLogger = Logger.getLogger("Demologer");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void logDebug(String message)
{
appLogger.log(className, Level.DEBUG, LogWriter.getMessage(message), null);
}
public static void logInfo(String message)
{
appLogger.log(className, Level.INFO, LogWriter.getMessage(message), null);
}
public static void logError(String message)
{
appLogger.log(className, Level.ERROR, LogWriter.getMessage(message), null);
}
private static String getMessage(String message)
{
String retValue;
Calendar cale = Calendar.getInstance();
Date now = cale.getTime();
//retValue=now.getDate()+"/"+(now.getMonth()+1)+"/"+(now.getYear()+1900)+" "+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
retValue = now + "\n";
now = null;
cale = null;
return retValue + message;
}
}
You can use this one as you need.
If you have some thing like following in your log4j.properties you will see duplications in output:
log4j.rootLogger=error, myappender
log4j.logger.com.sample=warn, myappender
log4j.logger.com.sample.deeper.package=all, myappender
correct it to:
log4j.rootLogger=error, myappender
log4j.logger.com.sample=warn
log4j.logger.com.sample.deeper.package=all
Edit:
Following will write fatal and error level logs from every classes, fatal, error and warning level logs from com.sample.* classes and every logs from com.sample.deeper.package.* classes to /var/log/myappender/myappender.log file.
Save as log4j.properties in you root package:
# This appender is not used in this example.
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c - %m%n
# But this one is used.
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.DatePattern='.'yyyy-MM-dd
log4j.appender.myappender.File=/var/log/myappender/myappender.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%d{ABSOLUTE} %5p %c - %m%n
log4j.appender.myappender.Encoding=UTF-8
log4j.rootLogger=error, myappender
log4j.logger.com.sample=warn
log4j.logger.com.sample.deeper.package=all
In your every classes you need a logger:
private static Logger logger = Logger.getLogger(ThisClassName.class);
And you don't need the snippet code you have in you question any more.

Categories

Resources