Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write to a text file using to log4j?

Tags:

I'm wondering how to convert the following code to output those lines into a text file, and not to standard output:

import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator;  public class HelloWorld {      static final Logger logger = Logger.getLogger(HelloWorld.class);      public static void main(String[] args) {         PropertyConfigurator.configure("log4j.properties");         logger.debug("Sample debug message");         logger.info("Sample info message");         logger.warn("Sample warn message");         logger.error("Sample error message");         logger.fatal("Sample fatal message");     } } 

The properties file is :

log4j.rootLogger=DEBUG, CA log4j.appender.CA=org.apache.log4j.ConsoleAppender log4j.appender.CA.layout=org.apache.log4j.PatternLayout log4j.appender.FA.layout.ConversionPattern=%m%n 

Thanks.

like image 584
RanZilber Avatar asked Dec 17 '10 20:12

RanZilber


People also ask

Where does log4j write to?

The Log4j logging settings are stored in the file app_data /conf/server/log4j. properties, where app_data is the application data folder. You can edit this file directly on the server or open it by clicking Settings > Logging.

What to do for log4j in files?

To write your logging information into files on a daily basis, you would have to use org. apache. log4j. DailyRollingFileAppender class which extends the FileAppender class and inherits all its properties.


1 Answers

Change the ConsoleAppender to a FileAppender.

I find the org.apache.log4j.RollingFileAppender to be useful. If you use this, you must add a property for the fileName and may want to set the maxFileSize as well. Here is an example (put these in the log4j.properties file):

log4j.appender.NotConsole=org.apache.log4j.RollingFileAppender log4j.appender.NotConsole.fileName=/some/path/to/a/fileName.log log4j.appender.NotConsole.maxFileSize=20MB 

There are other appenders. DailyRollingFileAppender rolls based on time. FileAppender does not roll. If you use the RollingFileAppender, you will need to guess as to a good value for maxFileSize and then address the size at a future date if it is causing issues.

like image 97
DwB Avatar answered Sep 22 '22 17:09

DwB