Log4j: How to configure simplest possible file logging?

后端 未结 4 837
无人及你
无人及你 2020-11-29 20:21

My story:

I want to make a thing which is as simple as a simplest possible log4j logger that logs rows to a file. I have found several examples with some fun

4条回答
  •  广开言路
    2020-11-29 21:07

    Here is a log4j.properties file that I've used with great success.

    logDir=/var/log/myapp
    
    log4j.rootLogger=INFO, stdout
    #log4j.rootLogger=DEBUG, stdout
    
    log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n
    log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
    log4j.appender.stdout.File=${logDir}/myapp.log
    log4j.appender.stdout.append=true
    

    The DailyRollingFileAppender will create new files each day with file names that look like this:

    myapp.log.2017-01-27
    myapp.log.2017-01-28
    myapp.log.2017-01-29
    myapp.log  <-- today's log
    

    Each entry in the log file will will have this format:

    01/30/2017 12:59:47 AM|INFO |Component1   | calling foobar(): userId=123, returning totalSent=1
    01/30/2017 12:59:47 AM|INFO |Component2   | count=1 > 0, calling fooBar()
    

    Set the location of the above file by using -Dlog4j.configuration, as mentioned in this posting:

    java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp
    

    In your Java code, be sure to set the name of each software component when you instantiate your logger object. I also like to log to both the log file and standard output, so I wrote this small function.

    private static final Logger LOGGER = Logger.getLogger("Component1");
    
    public static void log(org.apache.log4j.Logger logger, String message) {
    
        logger.info(message);
        System.out.printf("%s\n", message);
    }
    
    public static String stackTraceToString(Exception ex) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        return sw.toString();
    }
    

    And then call it like so:

    LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex)));
    

提交回复
热议问题