Search code examples
javaexceptionlog4jstack-traceprintstream

printStackTrace vs Logger Frameworks in Java


In Java, exception handling can be done in multiple ways. Let's differentiate exception handling using Logging framework as log4j or sl4j, where both of these could either redirect the logs to a file in addition to handle the exception.

If, instead of Logger framework, we use exception class method printStackTrace() to handle the exception and to get the exception call stack by redirecting it to a file rather than to standard error output/console, now, following are the questions:

  1. Would the later implementation handle the exception at all OR will simply print the exception to file?
  2. On what grounds does implementing Logger framework is prefered over printStacktrace() in Production environment?

Thanks in advance!


Solution

  • To 2) The logging frameworks aren't better file handler but, for example, extract the configuration of the logging out of the code. So when you change the configuration (e.g. other detail level of logs for development and production) you don't have to change the code - you just use other logging framework configurations for each test stage. If you want to change the log file names, the log file size (rotation) or the specific log detail of different packages or classes, you can easily do that by modifying the configuration.