25

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.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
RanZilber
  • 1,840
  • 4
  • 31
  • 42

5 Answers5

35

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.

DwB
  • 37,124
  • 11
  • 56
  • 82
  • what if i dont know the bound of the file size before runtime? – RanZilber Dec 17 '10 at 21:15
  • Thanks , but is it possible to change this size according to an input in runtime? My input is a program , and the more time it run, the larger the output file is. – RanZilber Dec 17 '10 at 21:33
  • 1
    You can configure you appender at runtime. I use the Log4j PropertyConfigurator and pass to the static configure() method a properties object that I build at runtime. – DwB Dec 17 '10 at 21:48
  • How do I use your example? Where do I put the 3 lines of code? – user2763361 Feb 19 '14 at 13:38
  • 2
    The lines I show above go in the log4j.properties configuration file. – DwB Feb 19 '14 at 15:08
  • @DwB, do you know how to provide a relative path? E.g. my java jar will be run on different machine, how I can specify to write into the current folder where the jar is run. e.g. into folder ~/CurrentFolder/filename.log ? – XYZ Jan 26 '21 at 08:55
  • @DwB, following your advice, I put a path to a text file, but when running the java program, the following error happens: `log4j:ERROR setFile(null,true) call failed.` `java.io.FileNotFoundException:` `"C:\Xiang\codes\Java_dev\HDFSOperation\hdfslog.txt" ` `(The filename, directory name, or volume label syntax is incorrect)` `at java.io.FileOutputStream.open0(Native Method)` – XYZ Jan 26 '21 at 09:22
  • Read the error message. It says that something is wrong in the path and/or the file name. do you have a directory named Java_dev or is it named Java.dev? – DwB Jan 26 '21 at 17:27
8

Shortly use FileAppender instead of ConsoleAppender.

Here is a simple example of configuration. It additionally configures the layout. You can omit it for the first approach.

log4j.appender.F=org.apache.log4j.FileAppender
log4j.appender.F.File=mylog.log
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%d{MM-dd@HH:mm:ss} %-5p (%13F:%L) %3x - %m%n
AlexR
  • 114,158
  • 16
  • 130
  • 208
4

The following would be helpful:

Class containing main method

    package abc;

    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;

    public class ClassOne {
        static Logger logger = Logger.getLogger(ClassOne.class);

        public static void main(String[] args) {
             PropertyConfigurator.configure("log4j.info"); //log4j.info file should be in the class path(same location as ClassOne.class)

             logger.info("Program started.... "); //Whenever you want to write something to the log text file use logger.info("Log Message")

        }
    }

log4j.info file

   log4j.rootLogger=INFO, FILE

   # Define the file appender
   log4j.appender.FILE=org.apache.log4j.FileAppender // Replacing ConsoleAppender with FileAppender gives text file logging

   # Set the name of the file
   log4j.appender.FILE.File=src/abc/log.out //Here you can specify either absolute or relative path

   # Set the immediate flush to true (default)
   log4j.appender.FILE.ImmediateFlush=true

   # Set the threshold to debug mode
   log4j.appender.FILE.Threshold=debug

   # Set the append to false, overwrite
   log4j.appender.FILE.Append=false

   # Define the layout for file appender
   log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
   log4j.appender.FILE.layout.conversionPattern=%d %m%n
harshainfo
  • 504
  • 7
  • 11
1

following configuration should aslo work

direct log messages to stdout ###

log4j.appender.stdout=org.apache.log4j.FileAppender
log4j.appender.stdout.fileName=error.log
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

Muhammad Abid
  • 801
  • 4
  • 12
0

in log4j.properties

# Define the root logger with file appender
log4j.logger.App = DEBUG ,CA

#set file text
log4j.appender.CA = org.apache.log4j.RollingFileAppender
log4j.appender.CA.File = D:\\database.log
log4j.appender.CA.maxFileSize = 20MB
log4j.appender.CA.MaxBackupIndex=10
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Thailand
  • 93
  • 1
  • 2
  • 10