Best practices for Java log Management

Source: Internet
Author: User
Tags filter contains include log4j

Overview

For today's applications, the importance of journaling is self-evident. It is hard to imagine an application without any logging capabilities running in a production environment. The functions that a log can provide are varied, including error messages, status information, debugging information, and execution time information that is generated when the program is running. In a production environment, logs are an important basis for finding the source of a problem. All kinds of information generated when the application is running should be logged through the log API. Many developers are accustomed to using the Printstracktrace method of System.out.println, System.err.println, and exception objects to output relevant information. These are easy to use, but the resulting information does not provide effective help when problems arise. You should use the log APIs instead. The use of the log API does not add a lot of complexity, but the benefits offered are significant.

Although logging is an essential feature of application development, the initial version of the JDK does not include logging-related APIs and implementations. Related APIs (java.util.logging, June) and implementations were not added until JDK 1.4. So in this area of logging, communities contribute a lot of open source implementations. Among them the more popular includes log4j and its successor, Logback. In addition to the true logging implementation, there is a class of logging-related encapsulation APIs, such as Apache Commons Logging and slf4j. The role of such libraries is to provide a encapsulated API hierarchy based on the logging implementation, providing a unified interface to the users of the logging API, which allows them to switch between different logging implementations freely. For example, from the JDK default logging implementation June switch to log4j. This kind of encapsulation API library is more common in the implementation of the framework, because it needs to take into account the different needs of the framework users. Less is used in actual project development, as few projects switch different logging implementations in development. In this paper, both types of libraries will be introduced concretely.

Logging is just the first step in effectively using the log, and more importantly, how to process and analyze the logs generated by the program's runtime. A typical scenario involves triggering a notification mechanism, such as a message or SMS notification, when the log contains records that meet certain conditions, and can quickly locate potential source of problem when an error occurs in the program's operation. This ability to process and analyze is particularly important for the maintenance of the actual system. Logging is especially important when you run a system that contains too many components to diagnose errors.

This article first introduces the basic content of the log API.

Java Log API

Functionally, the functionality required by the log API itself is simple enough to record a single piece of text. The user of the API constructs the corresponding text information according to the current context information, and invokes the API to complete the record. In general, the log API consists of the following sections:

Logger (Logger): The user of the log API makes a logging request through the logger and provides the contents of the log. When logging is logged, you need to specify the severity level of the log.

Formatter (Formatter): Formats the text recorded by the logger and adds additional metadata.

Processor (Handler): Outputs formatted log records to different locations. Common log output targets include consoles, files, and databases.

Recorder

When logging is required in your program, you first need to obtain a logger object. The general logging APIs provide the appropriate factory method to create the Logger object. Each Logger object has a name. The general practice is to use the name of the current Java class or the name of the package that contains the name of the Logger object. The name of the logger is usually hierarchical and corresponds to the hierarchy of the Java package. For example, the name of the logger used in the Java class "Com.myapp.web.IndexController" is generally "com.myapp.web.IndexController" or "Com.myapp.web". In addition to using the class name or package name, you can select a different name by dividing it according to the function of the log record. For example, use "security" as the name of all the safety-related loggers. This naming method is useful for some crosscutting functions. Developers are generally accustomed to using the current class name as the log logger, so that they can quickly navigate to the Java class that generates the log. Using other names that make sense is also a good choice in many cases.

When logging through a Logger object, you need to specify the severity level of the log. Depending on the configuration of each logger object, log messages below a certain level may not be logged. This level is the user of the log API to decide for themselves based on the information contained in the log records. Different logging APIs are defined with varying levels. The logging encapsulation API also defines its own level and maps to the actual level corresponding to the underlying implementation. For example, the JDK standard log API uses levels such as off, SEVERE, WARNING, INFO, CONFIG, FINE, Finer, FINEST, and all, and log4j uses a level that includes off, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, and all. In general, the level of use is FATAL, ERROR, WARN, INFO, DEBUG, and TRACE. These 6 levels correspond to a different situation:

FATAL: A serious error that causes the program to end prematurely.

Error: Run-time exceptions and unexpected errors.

WARN: The expected run-time status is not necessarily the wrong case.

INFO: Events that occur at run time.

DEBUG: Detailed information related to the process at which the program is running.

TRACE: more specific details.

In these 6 levels, ERROR, WARN, INFO, and DEBUG are common.

Users of the logging API log messages through loggers. Log messages can only be saved as text after they are recorded. However, some implementations, such as log4j, allow any Java object to be used when logging. Objects that are not of type string are converted to string types. Because logging is usually used when an exception occurs, the logger can also record the resulting exception (the object of the Throwable class) when it logs the message.

Each logger object has a runtime-corresponding severity level. This level can be set by configuring the file or code. If the severity level is not explicitly specified, it is looked up based on the hierarchy of the logger name until a name with the severity level is found. For example, a logger object with the name "Com.myapp.web.IndexController", if it does not explicitly specify its severity level, then finds whether it has the name "Com.myapp.web", "Com.myapp", and "com" in turn. The specified severity level. If it is still not found, the value configured by the root logger is used.

When logging through a Logger object, only a log request is issued. Whether the request will complete depends on the severity level of the request and logger object. Log messages that are generated by the logger consumer below the Logger object severity level are not logged. Such a record request is ignored. In addition to filtering based on severity levels, the logging framework supports other, custom filtering methods. For example, June can filter by implementing the Java.util.logging.Filter interface. Log4j can be filtered by inheriting the Org.apache.log4j.spi.Filter class.

Related Article

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.