How to write error log or exception into file in java
Asked Answered
G

6

23

Is there any way to write error log or exception into a file in java. i have gone through Log4j. I googled about it but diidnt find a good solution. I have written a simple code

catch (Exception e) {
    PrintWriter pw = new PrintWriter(new FileOutputStream("Log"));     
    e.printStackTrace(pw);
} 

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

Guizot answered 20/2, 2012 at 14:15 Comment(0)
O
40

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

Orelie answered 20/2, 2012 at 14:26 Comment(3)
and what do I do when unchecked exceptions appear? How can I be sure that EVERYTHING will be sent to the logger?Trifoliate
Use Throwable to catch everything. Not advisable though. You may want to read these posts: 1. #6116396 2. #2274602Orelie
@Orelie Where will be the log file located?? Is it inside the apache folder?Voroshilovgrad
S
8

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

catch(Exception e)
{
    logger.error("Unexpected error", e);
}

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

Skylark answered 20/2, 2012 at 14:19 Comment(0)
B
5

Using log4j you can log exceptiosn quite easily:

try {
    ...
} catch(Exception e) {
    log.error("An exception! Oops!", e);
}
Balk answered 20/2, 2012 at 14:18 Comment(0)
K
3
try {
       System.setErr(new PrintStream(new FileOutputStream(System.getProperty("user.home")+"/error.log")));
} catch (FileNotFoundException ex) {
        ex.printStackTrace();
}

Now all error output is written into this file

Krongold answered 20/2, 2012 at 14:18 Comment(6)
While technically correct, how is this better than using a logging framework (log4j, juli, commons-logging etc)?Doggerel
Why using a framework, when you can solve it with javas own methodes?Krongold
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?Doggerel
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.Krongold
You call them "features", I call them bare-minimum requirements for application logging. Different ambitions, I guess.Doggerel
Fine for me, just want a simple one-line thing to slam in there for a very simple application.Obsecrate
G
1

Look this tutorial about "File Appender"

See official Log4j short introduction and the "Configuration" section.

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:

try{
    throw new Exception("bla bla bla...");
} catch( Exception e ){
     // log without stack trace
     mLogger.error("Your log message");

     // log with stack trace
     mLogger.error("Your log message", e);
}
Gemperle answered 20/2, 2012 at 14:25 Comment(0)
M
0

You can Log data using log4j dependency. Go this link

https://logging.apache.org/log4j/2.x/manual/configuration.html
Pom dependency ==>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>

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 = ${filename}
appender.rolling.filePattern = target/rolling2/test1-%d{MM-dd-yy-HH-mm-ss}- 
%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%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!");
Masera answered 5/3, 2019 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.