LOG4J Custom configuration file path

Source: Internet
Author: User
Tags log4j
an agreement better than the configuration

The Convention is better than configuration (Convention over config), also known as convention programming, is a software design paradigm designed to reduce the number of decisions that software developers need to make, and gain simple benefits without sacrificing flexibility. A large number of configuration files, it is true that the program to a certain degree of flexibility, but also to have a degree of limitations, not the more the better; it is helpful to reduce the number of configuration files by agreeing to some default configurations. Of course, it is not advisable to use all the conventions without supporting the configuration, so the contract is better than the configuration does not mean the configuration, but one to provide both the contract and the configuration two ways.

Rootappender Conventions:
Using log4j to print the log, you need to configure the output style and destination of the log instance, and so on, not must be configured.
Log4j the output of a log instance that does not have to be configured, provides a basic console appender, and all logs that are created by the log instance are printed according to this appender output.
You only need to call the default initialization before you create the log instance:

static {
    basicconfigurator.configure ();
    Logger = Logmanager.getlogger (Log4jonetest.class);

The console output format is as follows and does not output trace level logs:

the Convention for the configuration file path:
Log4j the location of the configuration file in the Classpath, without specifying the profile path in the program, LOG4J looks for the configuration under its specified default Classpath, which is the root path of the classpath:
Two how the configuration file is loaded

The

Sometimes contracts a lot of configuration files under the Classpaht root path, which causes the configuration file to have no hierarchy and is difficult to discover the functionality of the configuration file, so you need to customize the path to the log4j profile at this time.
looking for a profile:
Typically, log4j creates a log instance by calling Logmanager's GetLogger (String/class) method to analyze the Logmanager source code, Logmanager did the following at initialization:

static {//By default we use a defaultrepositoryselector which always returns ' H '.
        Hierarchy h = new Hierarchy (new Rootlogger (level) level.debug);

        Repositoryselector = new Defaultrepositoryselector (h);  /** Search for the properties file Log4j.properties in the CLASSPATH. *//Gets a VM variable named Log4j.defaultinitoverride that determines whether the initialization of the log is overloaded with String override = Optionconverter.getsystemprope

        Rty (Default_init_override_key, NULL); If there is no default init override, then get the resource//specified by the user or the default Config file
        . if (override = = NULL | | "false". Equalsignorecase (Override)) {///Default_configuration_key value is log4j.configuration, get the name Log4j.configurati On VM variable String configurationoptionstr = Optionconverter.getsystemproperty (Default_configu

            Ration_key, NULL); String Configuratorclassname = Optionconverter.getsystEmproperty (Configurator_class_key, NULL);

            URL url = null;  If the user has not specified the Log4j.configuration//property, we search first for the file "Log4j.xml"
            and then//"log4j.properties"//If log4j.configuration is not found in the VM system variable, Log4j.xml is first found in the Classpath root directory. Then look for the Log4j.properties file if (configurationoptionstr = = null) {URL = Loader.getresou
                Rce (Default_xml_configuration_file);
                if (url = = null) {URL = Loader.getresource (default_configuration_file);
                    }} else {//If the VM system variable log4j.configuration is configured, use the value of the variable as the classpath of the configuration file try {
                url = new URL (configurationoptionstr); } catch (Malformedurlexception ex) {//So, resource are not a URL://attempt to G
 ET the resource from the class path                   url = loader.getresource (CONFIGURATIONOPTIONSTR); }}//If We have a non-null URL and then delegate the rest of the//configuration to T
            He optionconverter.selectandconfigure//method.
                if (URL! = null) {loglog.debug ("Using url [" + URL + "] for automatic log4j configuration.");
                            try {optionconverter.selectandconfigure (URL, configuratorclassname,
                Logmanager.getloggerrepository ());
                } catch (Noclassdeffounderror e) {Loglog.warn ("Error during default initialization", E); }} else {//No configuration file found error Loglog.debug ("Could not find resource: [" + configurationoption
            Str + "]."); }} else {Loglog.debug ("Default initialization of overridden by" + Default_init_
      Override_key + "property.");  }
    } 

Therefore, the Logmanager is initialized:

1. Find the LOG4J.DEFAULTINITOVERRIDEVM system variable to confirm that initialization is overloaded;
2. If you do not want to be overloaded, look for the LOG4J.CONFIGURATIONVM system variable and confirm that you have customized the configuration file path;
3. Do not configure LOG4J.CONFIGURATIONVM system variables, order to find log4j.xml,log4j.properties under the root classpath

To use a configuration file:
Parsing Logmanager, after locating the configuration file, called:

Optionconverter.selectandconfigure (URL, Configuratorclassname, logmanager.getloggerrepository ());

To handle the configuration, where the URL is the configuration file.

static public void selectandconfigure (URL url, String clazz, loggerrepository hierarchy) {
        Configurator Configurator = null;
        String filename = Url.getfile (); Choose whether to use Domconfigurator or Propertyconfigurator depending on the profile name suffix to handle if (Clazz = = NULL && filename! = null &&
        Filename.endswith (". xml")) {clazz = "org.apache.log4j.xml.DOMConfigurator";
            } if (Clazz! = null) {loglog.debug ("Preferred Configurator class:" + Clazz); Configurator = (configurator) instantiatebyclassname (Clazz, Configurator.class, Nu
            ll);
                if (configurator = = null) {Loglog.error ("Could not instantiate Configurator [" + Clazz + "].");
            Return
        }} else {configurator = new propertyconfigurator ();
    }//Processing configuration configurator.doconfigure (URL, hierarchy); }

Finally, take a look at the Doconfigure method for Domconfigurator processing configuration files:

Public
  void doconfigure (final URL url, loggerrepository repository) {
      parseaction action = new Parseaction () {
  public Document Parse (final Documentbuilder parser) throws Saxexception, IOException {
              URLConnection uconn = Url.op Enconnection ();
              Uconn.setusecaches (false);
              InputStream stream = Uconn.getinputstream ();
              try {
                InputSource src = new InputSource (stream);
                Src.setsystemid (Url.tostring ());
                return Parser.parse (SRC);
              } finally {
                stream.close ();
              }
          }
          Public String toString () {
              return "url [" + url.tostring () + "]";
          }
      };
      Doconfigure (action, repository);
  }

You can see the contents of the configuration file read. Propertyconfigurator is the same. three custom configuration file Paths

Once you understand how log4j loads the configuration file, you can customize the profile path.

Set Value VM System variables:
Simply, by setting the value of the VM system variable log4j.configuration to the configuration file path before getting the Logmanager initialization value, you can achieve the purpose:

static {
    String Customizedpath = "Log/log4j.xml";
    System.setproperty ("Log4j.configuration", Customizedpath);
    Logger = Logmanager.getlogger (Log4jonetest.class);
}

propertyconfigurator or Domconfigurator:
Domconfigurator has a static version of the Doconfigure (), corresponding to the XML configuration, Propertyconfigurator also, corresponding to the properties configuration mode, You can also specify the configuration file location by calling this method:

static public void Configure (URL url) throws Factoryconfigurationerror {
        new Domconfigurator (). Doconfigure (URL, Logmanager.getloggerrepository ());
}

Specific as follows:

static {
    String Customizedpath = "Log/log4j.xml";
    Domconfigurator.configure (GetResource (Customizedpath));
    Logger = Logmanager.getlogger (Log4jonetest.class);
}

Reference: "About the initialization of log4j"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.