Java Logging:logger

Source: Internet
Author: User

Table of Contents
    • Logging Messages
    • The log () Methods
    • The Logp () Methods
    • The LOGRB () Methods
    • The last Log Methods
    • Adding and removing handlers
    • Setting a Log Filter
    • Setting the Log level
    • Parent Logger
    • Additional Methods

The class is the main access point to the java.util.Logger Java logging API. Here's how do you create a logger:

Logger Logger = Logger.getlogger ("MyLogger");

  

The string passed as parameter to the factory method are the name of the the to getLogger() Logger create. You can choose the name freely, but the name implies where the are Logger located in the Logger hierarchy. Every. (dot) in the name of interpreted as a branch in the hierarchy. Look at these names:

MyAppmyApp.usermyApp.adminmyApp.admin.import.user

These names is all valid. They also imply a hierarchy. The name "MYAPP" is at the top of the hierarchy. The names "Myapp.user" and "myapp.admin" are children of the "MYAPP" name. The name "MyApp.admin.import.user" is a branch of the name "MyApp.admin.import", which is again a branch of the "Myapp.adm In "name.

The hierarchy is explored in and more detail with its Logger own text.

You can obtain the name of a Logger using getName() the The method, in case you need it. Here are an example:

String name = Logger.getname ();

  

IT is convention to use the class name of the class creating Logger the, including package name, as name for the Logger . Here are an example:

Logger Logger = Logger.getlogger (MyClass.class.getName ());

  

Logging Messages

To log a message using a Logger , the one call one of the its many logging methods. Among these is:

Log (level, string message, Object param1), log (level, string message, Ob Ject[] params); Log (level, string message, Throwable t); log (LogRecord record); Logp (level, String Sourcecla SS, String Sourcemethod, String msg); Logp (level, String Sourceclass, String Sourcemethod, String msg, Object par  AM1); Logp (level, String Sourceclass, String Sourcemethod, String msg, object[] params), Logp (level, string     Sourceclass, String Sourcemethod, String msg, Throwable t), LOGRB (level, String Sourceclass, String Sourcemethod, string bundle, String msg); Logrb (level, String Sourceclass, String Sourcemethod, string bundle, String msg, O Bject param1); LOGRB (Level level, String Sourceclass, String Sourcemethod, string bundle, String msg, object[] params); OGRB (Level level, String Sourceclass, String Sourcemethod, string bundle, String msg, Throwable t); Entering (string sour Ceclass, String SourcemeThod); Entering (string Sourceclass, String sourcemethod, Object param1), entering (string Sourceclass, String Sourcemethod, object[] params), exiting (string sourceclass, String sourcemethod), exiting (string Sourceclass, String Sourcemethod, Object result), fine (string message), finer (String message), finest (string message), config (string me ssage); info (string message), warning (string message), severe (string message), throwing (string sourceclass, string sour Cemethod, Throwable t);

  

I am not going to explain every single of these methods in detail. They is explained in the JavaDoc's for Java. But, I am going to explain their purpose. Knowing their purpose you can most likely figure out the rest, with help from the JAVADOC.

The log () Methods

The log() group of methods would log a message at a certain log level. The log level is passed as parameter. Use one of the Level constants as parameter. Log level was covered in more detail in its own text.

Some of the log() methods can take object parameters. These object parameters is inserted to the log message, before it is being logged. The merging of object parameters into the message was only performed if the message was not filtered out, either by a Filter , or because of too low log level. This improves performance in the cases where the message was filtered out.

Here is a log() example:

Logger Logger = Logger.getlogger ("MyLogger"); Logger.log (Level.severe, "Hello logging");

  

Logged to the console (default log destination):

08-01-2012 14:10:43 logging. Loggingexamples Mainsevere:hello Logging

  

Here's an example, inserts a parameter into the message:

Logger.log (Level.severe, "Hello logging: {0}", "P1");

  

And here are what's being logged:

08-01-2012 14:45:12 logging. Loggingexamples Mainsevere:hello LOGGING:P1

  

Notice how the object parameter value was inserted at the ' place ' in the ' P1 log ' message where the is {0} located. The is the index of the 0 object parameter to insert.

Here's an example, logs a message with multiple object parameters to being inserted into the log message:

Logger.log (Level.severe, "Hello logging: {0}, {1}",    new object[] {"P1", "P2"});

  

Here are being logged:

08-01-2012 14:45:12 logging. Loggingexamples Mainsevere:hello Logging:p1, P2

  

Notice again how the object parameters is inserted into the log message instead of the {0} and {1} tokens. As mentioned earlier, the number inside the token refers to the index of the object parameter to insert, in the object par Ameter array passed to the log() message.

Example that logs a Throwable :

Logger.log (Level.severe, "Hello logging",    new RuntimeException ("Error"));

  

Here are being logged (use the scrollbar to see it All):

08-01-2012 14:54:29 logging. Loggingexamples Mainsevere:hello loggingjava.lang.RuntimeException:Errorat logging. Loggingexamples.main (loggingexamples.java:18) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (nativemethodaccessorimpl.java:39) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (DELEGATINGMETHODACCESSORIMPL.JAVA:25) at Java.lang.reflect.Method.invoke (method.java:597) at Com.intellij.rt.execution.application.AppMain.main ( APPMAIN.JAVA:120)

  

The Logp () Methods

logp()the methods work log() as the methods, except each method take an extra, and sourceClass sourceMethod parameters:the Er.

These, parameters is intended to tell, from what class and method the log message originated. In other words, which class and method is the "source" of the log message.

The LOGRB () Methods

logrb()The methods work like log() the methods too, except they can obtain the log messages from a resource bundle. A resource bundle is a set of texts containing keys, value pairs, like a property file. Each file contains the same set of keys, with values in different languages. Resource Bundles is an internationalization feature, and I won ' t cover it in great detail here.

Here is a logrb() example:

LOGGER.LOGRB (Level.severe, "logging. Loggingexamples "," main ",        " Resources.myresources "," Key1 ");

  

This example looks-a message in the resource bundle named by the resources.myresources key key1 . If The resource bundle does not contain a key key1 with the so name (), the value itself is logged as a message. In this example then the value "Key1" would has been logged as message, if no key named "Key1" had existed in the RESOURC E bundle.

Here are what have logged:

08-01-2012 17:14:39 logging. Loggingexamples mainsevere:this is message 1

  

The resource bundle (property file) looks like:

Key1:this is a message 1key2:this is message 2

  

The Java Doc says nothing on how do you localize the messages using a Locale . How ResourceBundle to select the language of the and the other words.

The last Log Methods

The Logger also have the following methods for logging:

Entering (string sourceclass, String sourcemethod), entering (string sourceclass, String sourcemethod, Object param1); Entering (string sourceclass, String Sourcemethod, object[] params); exiting (string sourceclass, string sourcemethod); Exiting (string sourceclass, String sourcemethod, Object result), fine    (String message), finer   (String message); Finest (string message); Config (string message);  Info (string message);    Warning (string message); severe  (String message);

  

Each of the These methods corresponds to a log level. For instance,,,,, and all corresponds to one of the finest() finer() fine() info() warning() severe() log levels. Logging message using one of these methods corresponds to calling the log() method

Adding and removing handlers

You can add Handler ' s to the Logger using the addHandler() method. Here are an example:

Logger Logger = Logger.getlogger ("MyLogger"); Logger.addhandler (new Consolehandler ()); LOGGER.LOGRB (Level.severe, " Logging. Loggingexamples "," main ",        " Resources.myresources "," Key1 ");

  

A Logger can has multiple Handler ' s. When logging, messages is forwarded to all Handler ' s.

You can obtain all Handler ' s of a Logger using getHandlers() the method, like this:

handler[] handlers = Logger.gethandlers ();

  

You can remove a Handler using the removeHandler() method. Here are an example:

Logger Logger = Logger.getlogger ("MyLogger"); Handler Handler = new Consolehandler (); Logger.addhandler (Handler); Logger.remove (Handler)

  

Setting a Log Filter

You can set filters on a which filters off what's the forwarded to the Logger LogRecords Handler ' s of the Logger . You set Filter Logger setFilter() the to a using the method, like this:

Filter filter = new Myfilterimpl (); Logger.setfilter (filter);

  

The class MyFilterImpl should be your own implementation of the Filter interface. See the text in Filters to learn more about implementing your own Filter .

You can obtain Filter the ' in ' by calling getFilter() the method, like this:

Filter filter = Logger.getfilter ();

  

Setting the Log level

You can set the minimum log level of messages to is forwarded to the Handler ' s. Here is a code example:

Logger Logger = Logger.getlogger ("MyLogger"); Logger.setlevel (Level.info);

  

This example sets the minimum logs level of messages to is forwarded, to Level.INFO . To see the hierarchy of log levels, read the text on log levels.

You can obtain the log level of a Logger using the getLevel() method:

Logger.getlevel ();

  

You can also the check if a given log level would is logged, if you tried logging a message with this log level. isLoggable()the using the method, like this:

Boolean isinfologgable = Logger.isloggable (Level.info);

  

Parent Logger

As mentioned elsewhere in this tutorial, the Logger ' s is organized into a hierarchy. That's means, that a Logger can has a parent in the Logger hierarchy. You can obtain the parent of Logger a given Logger using the getParent() method. Here are an example:

Logger parent = Logger.getparent ();

  

You can also tell the Logger "use" or not "use the Parent " logger when logging. You do setUseParentHandlers() so using the-a, like this:

Logger.setuseparenthandlers (FALSE);

  

This example switched off the forwarding of log messages to the parent Logger ' s Handler .

You can check if a Logger forwards logs messages to its parent Logger using the method getUseParentHandlers() . Here are an example:

Boolean useparentlogger = Logger.getuseparenthandlers ();

  

Additional Methods

The Logger class has a few more methods this I haven ' t covered here. These is minor features, like obtaining the ResourceBundle Logger . You should check out the JAVADOC's for the complete list of utility methods.

Java Logging:logger

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.