Java error log windows

How to write error log or exception into file in java

Is there any other way to log the errors or exception? can any body provide me wwith sample example of Log4j?

6 Answers 6

First read log4j Manual, it’s easy to configure a rolling log file. You do not have to do any explicit file operations.

#SET LEVEL of ROOT-LOGGER, you will like to have Debug in local, but in prod you may just want WARN and ABOVE. This setting is done here! log4j.rootLogger=debug, stdout, R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. (basically, format of log) log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n # THIS IS WHERE YOU WILL HAVE ALL THE LOG WRITTEN log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=/var/log/applogs/example.log # Maximum size of log file, usually we keep 10MB log4j.appender.R.MaxFileSize=100KB # Keep one backup file, usually we keep 10 log4j.appender.R.MaxBackupIndex=1 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n 

Second, whenever you catch an exception, do like this

public class MyClass < private static Logger logger = Logger.getLogger(MyClass.class); public ReturnType myMethod(Param p, Param2 p2) < . . try < .. >catch(MyException e) < logger.log("Exceptions happen!", e); //this will put all the details in log file configured earlier >. > . > 

It worth reading the manual. Even better read Complete log4j Manual

and what do I do when unchecked exceptions appear? How can I be sure that EVERYTHING will be sent to the logger?

Use Throwable to catch everything. Not advisable though. You may want to read these posts: 1. stackoverflow.com/questions/6115896/… 2. stackoverflow.com/questions/2274102/…

Читайте также:  Что делает format в питоне

You can add the exception as a parameter to your log4j statement, e.g.

Provided you’ve got a file appender running OK, this will output the complete stack trace of the exception.

Using log4j you can log exceptiosn quite easily:

try < System.setErr(new PrintStream(new FileOutputStream(System.getProperty("user.home")+"/error.log"))); >catch (FileNotFoundException ex)

Now all error output is written into this file

While technically correct, how is this better than using a logging framework (log4j, juli, commons-logging etc)?

1: No support for different log levels 2: No support for diagnostic contexts (thread, class, method, etc) 3: No support for output formatting I could go on. You can hammer a nail in with a screwdriver, but why wouldn’t you use a hammer if you have one?

Jeah, but if you ONLY want to write all errors into a file, you can use this simple line of code. If you want to have all these features, choose a framework. If you want to dig a little hole, you take a shovel, if you want to dig a big hole you take a power shovel.

You call them «features», I call them bare-minimum requirements for application logging. Different ambitions, I guess.

You can also make search about «RollingFileAppender» or «File appender».

You configure your logger to send its message to an appender. This appender can forward message towards the console (stdin), towards a file (FileAppender, RollingFileAppender. ).

Use this to perform error log:

You can Log data using log4j dependency. Go this link

https://logging.apache.org/log4j/2.x/manual/configuration.html Pom dependency ==> org.apache.logging.log4j log4j-api 2.11.2  org.apache.logging.log4j log4j-core 2.11.2  Properties File eg ==> status = error dest = err name = PropertiesConfig property.filename = target/rolling/rollingtest.log filter.threshold.type = ThresholdFilter filter.threshold.level = debug appender.console.type = Console appender.console.name = STDOUT appender.console.layout.type = PatternLayout appender.console.layout.pattern = %m%n appender.console.filter.threshold.type = ThresholdFilter appender.console.filter.threshold.level = error appender.rolling.type = RollingFile appender.rolling.name = RollingFile appender.rolling.fileName = $ appender.rolling.filePattern = target/rolling2/test1-%d- %i.log.gz appender.rolling.layout.type = PatternLayout appender.rolling.layout.pattern = %d %p %C [%t] %m%n appender.rolling.policies.type = Policies appender.rolling.policies.time.type = TimeBasedTriggeringPolicy appender.rolling.policies.time.interval = 2 appender.rolling.policies.time.modulate = true appender.rolling.policies.size.type = SizeBasedTriggeringPolicy appender.rolling.policies.size.size=100MB appender.rolling.strategy.type = DefaultRolloverStrategy appender.rolling.strategy.max = 5 logger.rolling.name = com.example.my.app // Change this to your own package name otherwise will not work logger.rolling.level = debug logger.rolling.additivity = false logger.rolling.appenderRef.rolling.ref = RollingFile rootLogger.level = info rootLogger.appenderRef.stdout.ref = STDOUT Java code ==> private static final Logger logger = LogManager.getLogger(MyClass.class.getName()); logger.info("Entering application."); logger.trace("Entering application."); logger.debug("Debugg application."); logger.error("Did it again!"); 

Источник

How to log exceptions in Java?

There’s a common problem I’ve come across a few times when logging exceptions in Java. There seem to be various different types to deal with. E.g. some wrap other exceptions and some don’t have a message at all — only a type. Most code I’ve seen logs an exception by using either getMessage() or toString() . But these methods don’t always capture all the information needed to pinpoint the problem — other methods such as getCause() and getStackTrace() sometimes provide additional info. For example, the exception I’m looking at right now in my Eclipse Inspect window is an InvocationTargetException . The exception itself has no cause, no message, no stacktrace . but the target from getCause() is InvalidUseOfMatchersException , with these details populated. So my question is: Given an exception of any type as an input, please provide a single method that will output a nicely formatted string containing all relevant information about the Exception (e.g. possibly recursively calling getCause() amongst other things?) Before posting, I was nearly going to have a stab at it myself but really don’t want to reinvent the wheel — surely such a thing must have been done many times before.

7 Answers 7

The java.util.logging package is standard in Java SE. Its Logger includes an overloaded log method that accepts Throwable objects. It will log stacktraces of exceptions and their cause for you.

import java.util.logging.Level; import java.util.logging.Logger; [. ] Logger logger = Logger.getAnonymousLogger(); Exception e1 = new Exception(); Exception e2 = new Exception(e1); logger.log(Level.SEVERE, "an exception was thrown", e2); 
SEVERE: an exception was thrown java.lang.Exception: java.lang.Exception at LogStacktrace.main(LogStacktrace.java:21) Caused by: java.lang.Exception at LogStacktrace.main(LogStacktrace.java:20) 

Internally, this does exactly what @philipp-wendler suggests, by the way. See the source code for SimpleFormatter.java . This is just a higher level interface.

Keep in mind that if you use a custom formatter, you have to specifically support using Throwables (I just copied Oracle code) or else this will not work.

In addition to this idea, i checked how to do it using SL4J and founded this: baeldung.com/slf4j-log-exceptions

This answer was helpful. I was testing whether I could log exceptions in a way that included all the info about the error (including the error message of the deeply-nested original exception) and also allowed the program to continue to process more work. This worked well. The logged string included INFO: could not complete job for user Matt , com.mattwelke.Main$MathException: failed to do math , and Caused by: java.lang.IllegalArgumentException: you tried to divide 10.0 by 0. (meaning I got all the error context I needed in the logs). I imagine this would work well with SLF4J too.

What’s wrong with the printStacktrace() method provided by Throwable (and thus every exception)? It shows all the info you requested, including the type, message, and stack trace of the root exception and all (nested) causes. In Java 7, it even shows you the information about «supressed» exceptions that might occur in a try-with-resources statement.

Of course you wouldn’t want to write to System.err , which the no-argument version of the method does, so instead use one of the available overloads.

In particular, if you just want to get a String:

 Exception e = . StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionDetails = sw.toString(); 

If you happen to use the great Guava library, it provides a utility method doing this: com.google.common.base.Throwables#getStackTraceAsString(Throwable) .

Thanks for your answer but I think all printStacktrace() does is writes the stacktrace returned from getStacktrace() to the error stream? This isn’t really what I’m looking for. Also don’t think it would work in the case where the Exception wraps another Exception.

The overloads of printStackStrace write to another target, not to the error stream. And the printed information contains all causes, including their type, message, stack trace, and (nested) causes.

@flup Why would you consider this «rolling your own»? This way does use the standard Java method for this.

It should be quite simple if you are using LogBack or SLF4J. I do it as below

//imports import org.slf4j.Logger; import org.slf4j.LoggerFactory; //Initialize logger Logger logger = LoggerFactory.getLogger(.class); try < //try something >catch(Exception e) < //Actual logging of error logger.error("some message", e); >

A logging script that I have written some time ago might be of help, although it is not exactly what you want. It acts in a way like a System.out.println but with much more information about StackTrace etc. It also provides Clickable text for Eclipse:

private static final SimpleDateFormat extended = new SimpleDateFormat( "dd MMM yyyy (HH:mm:ss) zz" ); public static java.util.logging.Logger initLogger(final String name) < final java.util.logging.Logger logger = java.util.logging.Logger.getLogger( name ); try < Handler ch = new ConsoleHandler(); logger.addHandler( ch ); logger.setLevel( Level.ALL ); // Level selbst setzen logger.setUseParentHandlers( false ); final java.util.logging.SimpleFormatter formatter = new SimpleFormatter() < @Override public synchronized String format(final LogRecord record) < StackTraceElement[] trace = new Throwable().getStackTrace(); String clickable = "(" + trace[ 7 ].getFileName() + ":" + trace[ 7 ].getLineNumber() + ") "; /* Clickable text in Console. */ for( int i = 8; i < trace.length; i++ ) < /* 0 - 6 is the logging trace, 7 - x is the trace until log method was called */ if( trace[ i ].getFileName() == null ) continue; clickable = "(" + trace[ i ].getFileName() + ":" + trace[ i ].getLineNumber() + ") ->" + clickable; > final String time = " "; StringBuilder level = new StringBuilder("[" + record.getLevel() + "] "); while( level.length() < 15 ) /* extend for tabby display */ level.append(" "); StringBuilder name = new StringBuilder(record.getLoggerName()).append(": "); while( name.length() < 15 ) /* extend for tabby display */ name.append(" "); String thread = Thread.currentThread().getName(); if( thread.length() >18 ) /* trim if too long */ thread = thread.substring( 0, 16 ) + ". "; else < StringBuilder sb = new StringBuilder(thread); while( sb.length() < 18 ) /* extend for tabby display */ sb.append(" "); thread = sb.insert( 0, "Thread " ).toString(); >final String message = "\"" + record.getMessage() + "\" "; return level + time + thread + name + clickable + message + "\n"; > >; ch.setFormatter( formatter ); ch.setLevel( Level.ALL ); > catch( final SecurityException e ) < e.printStackTrace(); >return logger; > 

Notice this outputs to the console, you can change that, see http://docs.oracle.com/javase/1.4.2/docs/api/java/util/logging/Logger.html for more information on that.

Now, the following will probably do what you want. It will go through all causes of a Throwable and save it in a String. Note that this does not use StringBuilder , so you can optimize by changing it.

Throwable e = . String detail = e.getClass().getName() + ": " + e.getMessage(); for( final StackTraceElement s : e.getStackTrace() ) detail += "\n\t" + s.toString(); while( ( e = e.getCause() ) != null )

Источник

Оцените статью