Turn Off Apache Common Logging

前端 未结 4 586
抹茶落季
抹茶落季 2020-12-02 17:09

I am using Apache Common Logging library in my standalone application. After searching through the web, I try to turn off the logging by using

package javaap         


        
相关标签:
4条回答
  • 2020-12-02 17:37

    As others pointed out, your log instance is instantiated before system property is set, which is too early.

    Try passing -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog to your JVM to make sure it is set at the right time.

    0 讨论(0)
  • 2020-12-02 17:45

    The problem with your example is that the Log class is instantiated before the property is set. If you create the Log instance after the property is set the example works properly. For example if you move it into the main method:

    package javaapplication1;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    /**
     *
     * @author yccheok
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            System.setProperty("org.apache.commons.logging.Log",
                               "org.apache.commons.logging.impl.NoOpLog");
            Log log = LogFactory.getLog(Main.class);
    
            log.info("You do not want to see me");
        }
    
    }
    
    0 讨论(0)
  • 2020-12-02 17:53

    As others have pointed out, this is happening because you create the Log object before you set the property.

    One way around this would be to set the property in your Main class' static initialiser block - this will be run when the class is first loaded, and before the static final Log is created:

    public class Main {
    
       static {
          System.setProperty("org.apache.commons.logging.Log",
                             "org.apache.commons.logging.impl.NoOpLog");
       }
    
       // Rest of class as before
    }
    
    0 讨论(0)
  • 2020-12-02 17:54

    A different approach could be - while developing - to use the slf4j project to control logging.

    Using the commonds logging bridge to replace Apache COmmons logging with sljf4 and then use a suitable logging backend. E.g. the slf4j simple or NOP implementation would be reasonable for you. These are just a few jars you drop in your classpath.

    See http://www.slf4j.org/legacy.html#jcl-over-slf4j

    0 讨论(0)
提交回复
热议问题