ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Examples - How do I perform Logging in Java?

Updated on June 11, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & reading books.

1. Introduction to Logging

The application running in the end user system may malfunction at specific conditions. This is a programming flaw. When this situation rises, application debugging as we do it the development machine is not possible. Because the application installer will not deploy the debugging information in the user machine.

The application developer uses Logging to capture the application activities from the deployed system. Logging avoids deploying the Debugging Symbols in the production machine. Have a look at the below depiction:

Debugging Symbols are additional information packed with the binary output of a program. These additional information will help in debugging the errors as we can easily map it to the source code.

Capturing Log at Production System
Capturing Log at Production System | Source

The logging goes as a binary component in the application itself. In most cases, the configuration file takes care of turning ON or turning OFF the logging. When misbehavior of the application or crash happens, the Logging System will be turned ON to produce the “Log File”. The Log file captured in the production will be shipped to the Application Development or Support for further research to know what happened on the production system.

Log Files are mostly an AscII format readable files which has application activities captured in it.

In the above model, in place of deploying the debug information along with binary, the logging system is deployed as a component to capture the application information. OK. Let us see how we can produce Log information using "java.util.logging" package. Note that in this example we will not create any log file. But, we will display the Log Information in the console window.

2. The LogManager

An Application can comprise only one "LogManager" instance. This single LogManager object maintains multiple Loggers, Handlers, etc. That means, once we have LogManager instance, we can claim other objects needed for the logging from it.

The LogManager Class has a static method called "getLogManager()". This method constructs the LogManager object and returns that to the caller. It is not possible for the application to change LogManager object after its retrieval.

3. The Logger

The "getLogger" method of the LogManager class returns the Logger object to its caller. While retrieving the Logger, we can give a name to it by sending a string as a parameter to the getLogger(). The naming follows a hierarchical notation which allows the parent-child relationship between Loggers when multiple Logger exists.

Application running in the production uses the Logger to capture the run-time conditions. Logging output can be delivered to a special receiver like Network Socket, Files or Console Window etc. Java uses "Handler" object to accomplish this.

Each logging call to the Logger goes with a “Logging Level” which supports message filtering. For Example, let us mention the Log Level is 1,2,3,4 where 1 is a high level (Critical) message and 4 is a low-level message (developer debug information). Let us further say, the LogLevel in the Logger is 1. Now, the logger will pump only the Critical Message to the Log Receiver (File, Console etc) and it rejects all other log request with a log level higher than 1.

In this example, we will see how we log a message. We will deal with the Logging Level in a distinct Example.

4. Simple Logging Example

To perform logging, we require Logger from the “java.util.logging” package. To use Logger we need to have the "LogManager". The below import statements imports the required classes to our example.

Listing 1: Package inclusion for Logging

//Snippet 01: Package inclusion
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.Level;

First, we get the application wide LogManager instance. We store that in the reference called "lgMan". We call the "getLogManager() static method" on the LogManager class. This retrieve the LogManager Class instance. Below is the code:

Listing 2: Get LogManager Instance

//Snippet 02: Get the Log Manager Instance
LogManager lgMan = LogManager.getLogManager();

After getting the LogManager, we are setting a name for our Logger using the GLOBAL_LOGGER_NAME constant from the Logger class. We are passing this global constant to the getLogger() method of the LogManager instance and the method returns a Logger instance. Note, it is also possible to pass our own logger name to the getLogger method. For this basic example, we used the name assigned by the system.

Now, the Logger is ready for logging the application specific information. Before we go for actual logging, we are setting the log level to the logger by calling the “setLevel()” method. The “Level.ALL” constant tells the logger not to filter any message. Below is the code

Listing 3: Get the Logger

//Snippet 03: Get Logger from Log Manager
String LoggerName = Logger.GLOBAL_LOGGER_NAME;
Logger Logr = lgMan.getLogger(LoggerName);
Logr.setLevel(Level.ALL);

The “log()” method of the Logger class performs the logging. In the below code fragment, we are logging two informational messages. While logging, we say that both the messages are information messages by sending a Constant “Level.INFO” as the first parameter. The second parameter is a string containing the actual information message we want to log.

Since we set Logger with the "Level.ALL" Logging Level, the logger will log any message sent to it. This is a Console Application, and the logged messages go to Console Output Window once log() method is called. Below is the code:

Listing 4: Perform Logging

//Snippet 04: Perform the Logging
Logr.log(Level.INFO, "First Log Entry");
Logr.log(Level.INFO, "Second Log Entry");

To send the logging information to a File, we need to set a suitable handler to our logger and we will see that in a separate example. Below are the Complete example and its output.

Listing 5: Complete Example

//Snippet 01: Package inclusion
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.Level;

public class Main
{
    public static void main(String[] args)
    {
        //Snippet 02: Get the Log Manager Instance
        LogManager lgMan = LogManager.getLogManager();

        //Snippet 03: Get Logger from Log Manager
        String LoggerName = Logger.GLOBAL_LOGGER_NAME;
        Logger Logr = lgMan.getLogger(LoggerName);
        Logr.setLevel(Level.ALL);

        //Snippet 04: Perform the Logging
        Logr.log(Level.INFO, "First Log Entry");
        Logr.log(Level.INFO, "Second Log Entry");
    }
}
Output of Logger Example
Output of Logger Example | Source

About the Program Output

Note that in the output we also get the Date and Time in which the information is logged. The purpose of Logging is to diagnose the behaviour of the application at a given time. This is the reason why the logger is appending the Date & Time for each and every logged message. It is marked as yellow in the output and the actual log messages are marked with a blue line. Light Blue?

What is your choice to perform Logging in Java Application?

See results

© 2018 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)