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/…
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 error in java exception handling.? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
LOG.error("Error message "+e.getMessage());
@Tom Why is this on hold as opinion-based? The first case gives the logging framework all information needed, and the logging framework then can decide what info to actually log. The later approaches only give to the logging framework the message, and make it impossible to manage what is logged centrally via logging configuration.
You want to know which approach is the best, so everyone answer that with what he or she thinks is best. Therefore it is opinion-based.
4 Answers 4
Why do you not just try it out? You are the only one who knows which information do you need in your logging. Depending on the thrown exception you might want the stacktrace or not.
See below a small example to show the different outputs
private void logTest() < try < Files.readAllBytes(Paths.get("foobar")); >catch (IOException e) < logger.error("Error message ", e); logger.error("Error message " + e); logger.error("Error message " + e.getMessage()); >>
logger.error(«Error message «, e);
2015-10-07 13:42:11,239 [main] ERROR sub.optimal.Main - Error message java.nio.file.NoSuchFileException: foobar at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230) at java.nio.file.Files.newByteChannel(Files.java:361) at java.nio.file.Files.newByteChannel(Files.java:407) at java.nio.file.Files.readAllBytes(Files.java:3152) at sub.optimal.Main.logTest(Main.java:43) at sub.optimal.Main.main(Main.java:53)
logger.error(«Error message » + e);
2015-10-07 13:42:11,243 [main] ERROR sub.optimal.Main - Error message java.nio.file.NoSuchFileException: foobar
logger.error(«Error message » + e.getMessage());
2015-10-07 13:42:11,243 [main] ERROR sub.optimal.Main - Error message foobar
Thanks @SubOptimal I tried it but i am confused that which one is good practice for production and effective development.
As I said it depends. If you know the exception itself contains all information you need to know for sport the error, like java.nio.file.NoSuchFileException: foobar then you might not want to clutter the log with the stacktrace. If you catch an exception where you don’t know what could be the cause or which information you might need to spot the origin, log as much as possible (means include the stacktrace).
@SubOptimal why not leave the decision of what to log on the apender’s layout? If you use error(String, Throwable), you can decide in the layout whether you want the message, the exception message, and the stack trace to be present in the log (and often you can change it even without recompiling). While if you use any of the other proposed forms, there’s no way to configure the logger to print the stacktrace.
@JiriTousek Dependent on the logger implementation this might be an option not all implementation might provide this feature (I’m not aware of this functionality in log4j before version 2). There might be a problem if different exception handlers in one class should log different level of exception information.
Use LOG.error(«Error message «,e); — that way you won’t lose the stack trace of the exception (note that you also need to make sure your logging framework’s output layout is set up so that it prints the stack traces).
Stack traces are a valuable part of the exception report since they tell you how the offending code was called, and therefore may help you understand what state your program was in when the error occurred.
If you for some reason want to log only the message and not the stack trace, I would still recommend using the above form and then configuring the logging framework to not print the stack trace (in Log4j, this is done by configuring the Appender). That way, if you change your mind later, you can add the stack trace to the logs by changing the configuration only, without the need to change the actual logging code. The choice of what info should be put in the log should be responsibility of the appender configuration, not the code that logs the entry.
java: log exception being thrown
The problem is that now my method must declare it throws throwable. On the other hand, if I log the exception in a finally block, how do I know what exception is being thrown (and if any exception is being thrown at all).
5 Answers 5
You could at least write a catch for unchecked and n catch blocks for checked exceptions.
try< .. >catch(RuntimeException e)< log(e); throw e; >catch(ExceptionException ..)
This will not change the signature of your method. Catching Errors is a bit of a smell. Well, logging and throwing exception is a smell, too. This will duplicate error messages.
Advance exception handling is a feature that was removed from project coin in JDK 7.
This seems to be the wrong place to log the exception. Either log it within doRiskyThing() when throwing it, or log it where it is supposed to be captured.
try < doRiskyThing(); >catch(RuntimeException e) < log.warn("too bad"); throw e; >catch(Exception e) < log.warn("too bad"); throw new RuntimeException(e); >catch(Error e)
But it’s ugly and I’d rather have a single catch block that catches everything and logs it at the top level of the app, with no re-throwing. The stack trace lets you pinpoint the problem anyway.
Catching Throwable in itself is already bad practice (and flagged as such by many code quality checking tools). Wrapping it in a RuntimeException and rethrowing it? Terrible! The whole point of having an exception hierarchy is undermined by this.
The ‘trend’ away from checked exceptions is actually a bit more subtle. Between architectural layers (or for example at a framework API boundary) it is common practice to define one or more meaningful exception types and wrap any implementation-specific errors in them (take a look at Spring or Hibernate for example).
Making exceptions checked or not is a matter of style. If there is a good chance that the caller will be willing and able to handle the error condition then I make it checked (e.g. concurrent update detected), otherwise unchecked (e.g. database connection error). Unchecked exceptions should ‘bubble’ up through your application code (i.e. not be caught) and handled at a high level by displaying some sort of error page/screen.