Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

java - Write log file using org.apache.commons.logging

I'm writing an application where I need to write log to a file using org.apache.commons.logging library, but i don't know how to start.

Can anyone help me?

Thanks & best regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this sample, first you need two properties files likes this;

commons-logging.properties that put in your application's classpath. The contents of this file should look like:

    org.apache.commons.logging.Log=org.apache.commons.logging.impl.Jdk14Logger

You can also use Log4j logger besides Jdk14Logger.And need second custom properties file.For example log-config.properties looks like this:

    # The following creates two handlers
    handlers=java.util.logging.ConsoleHandler, java.util.logging.FileHandler
    # Set the default logging level for the root logger
    .level=SEVERE
    # log level for the "com.example" package
    sample.logging.level=FINE
    # Set the default logging level
    java.util.logging.ConsoleHandler.level=ALL
    java.util.logging.FileHandler.level=FINE
    # Set the default formatter
    java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
    java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
    # Specify the location and name of the log file
    java.util.logging.FileHandler.pattern=D:/temp/log/test.log

This is sample test class

     public class TestLog {

     private static Log log = LogFactory.getLog(TestLog.class);
     public static void main(String[] args) {
          log.info("Testing Info Message.");
              if (log.isDebugEnabled()) {
                  log.debug("Testing Debug Message.");
          }
        }
     }

This is sample package structure using eclipse;

enter image description here

And add TestLog class's Edit Configuration under VM arguments likes this;

  -Djava.util.logging.config.file=/D:/dev/workspace/LoggingTest/bin/log-config.properties(your properties file path)

enter image description here

And run then you can find your log file under D:/temp/log/test.log


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...