log4j Introduction and examples of using log4j in Java projects and Javaweb projects __web

Source: Internet
Author: User
Tags log4j
Log4j is an open source project for Apache, by using log4j, we can control the destination of log information delivery is console, file, GUI component, even interface server, NT Event recorder, UNIX syslog daemon, etc. We can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully. 

Log4j is composed of three important components: priority of log information, output destination of log information, and output format of log information. Log information priority from high to low have error, WARN, INFO, DEBUG, respectively, to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or file, and the output format controls the display of the log information.

You can actually configure the LOG4J environment in your code without using a configuration file at all. However, using a configuration file will make your application more flexible.   LOG4J supports two configuration file formats, one in XML format and one in properties format. Here we introduce the method of using the properties format as a configuration file:  example:  log4j.rootlogger=info, a1  log4j.appender.a1= org.apache.log4j.consoleappender  log4j.appender.a1.layout=org.apache.log4j.patternlayout  LOG4J.APPENDER.A1.LAYOUT.CONVERSIONPATTERN=%-4R%-5p [%t]%37c%3x-%m%n  1. Configure the root logger, whose syntax is:  log4j.rootlogger = [level], Appendername, Appendername, ...  where the level is the priority of the log record, divided into off, FATAL, E Rror, WARN, INFO, DEBUG, all, or the level you define. LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application. For example, if the info level is defined here, all debug-level log information in the application will not be printed.   Appendername is where to specify the output of the log information. You can specify multiple output destinations at the same time.   2. Configuration log information output destination Appender, its syntax is:  log4j.appender.appenderName = fully.qualified.name.of.appender.class  Log4j.appender.appenderName.option1 = value1  ...  log4j.appender.appenderName.option = valuen  of which, The appender provided by log4j have the following kinds of:  Org.apache.log4j.ConsoleAppender (console),  org.apache.log4j.FileAppender (file),  Org.apache.log4j.DailyRollingFileAppender (produces a log file every day),  Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches a specified size),  Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)   (1). Consoleappender Options   Threshold=warn: Specifies the lowest level of output for log messages.   Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.   Target=system.err: By default: System.out, specify output console   (2). Fileappender Options   Threshold=warn: Specifies the lowest level of output for log messages.   Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.   file=mylog.txt: Specify message output to Mylog.txt file.   Append=false: The default value is true to add the message to the specified file, false to overwrite the specified file contents.   (3). Dailyrollingfileappender Options   Threshold=warn: Specifies the lowest level of output for log messages.   Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.   file=mylog.txt: Specify message output to Mylog.txt file.   Append=false: The default value is true to add the message to the specified file, false to overwrite the specified file contents.   datepattern= '. ' YYYY-WW: Scrolls the file once a week, that is, a new file is generated each week. Of course, you can specify the month, week, day, time, and minutes. That corresponds to the format below:    1) '. ' YYYY-MM: Monthly     2) '. ' YYYY-WW: Weekly   &NBSp 3) '. ' YYYY-MM-DD: Daily     4) '. ' Yyyy-mm-dd-a: Two times a day     5) '. ' YYYY-MM-DD-HH:     6 per hour) '. ' YYYY-MM-DD-HH-MM:   (4) per minute. Rollingfileappender Options   Threshold=warn: Specifies the lowest level of output for log messages.   Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.   file=mylog.txt: Specify message output to Mylog.txt file.   Append=false: The default value is true to add the message to the specified file, false to overwrite the specified file contents.   MAXFILESIZE=100KB: The suffix can be kb, MB, or GB. When the log file reaches that size, it scrolls automatically, moving the original content to the Mylog.log.1 file.   maxbackupindex=2: Specifies the maximum number of scrolling files that can be produced.   3. Configures the layout of the log information, whose syntax is:  log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class  Log4j.appender.appenderName.layout.option1 = value1  ...  log4j.appender.appenderName.layout.option = Valuen   Among them, the layout provided by log4j has the following:  org.apache.log4j.HTMLLayout (layout in HTML form),  Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),  org.apache.log4j.SimpleLayout (The level and information string that contains the log information),  Org.apache.log4j.TTCCLayout (contains information about time, thread, category, etc.)   4, output formatting   can be passed through Log4j.appender in configuration file. A1.layout.ConversionPattern to set the log output format.   Parameters: %p: Output log information priority, that is, debug,info,warn,error,fatal, %d: the date or time of the output log point, the default format is ISO8601, or the format can be specified thereafter, for example:%d{ YYY MMM DD Hh:mm:ss,sss}, Output is similar: October 18, 2002 22:10:28,921 %r: Output from the application boot to the output of the log information the number of milliseconds  %c: output log information to the class, This is usually the full name of the class  %t: Output the thread name  %l that generated the log event: the location of the output log event, equivalent to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of lines in the code. For example: Testlog4.main (testlog4.java:10)  %x: Output is associated with the current line threads relative NDC (nested diagnostic environment), especially in multiple client multi-threaded applications such as Java Servlets.  %: Output A "%" character  %F: output log message produced when the file name  %l: Output code in the line number  %M: output code specified in the message, the resulting log specific information  %n: output a carriage return line feed, Windows platform is "\ r \ n", the UNIX platform is "\ n" output log message wrapping   You can control its minimum width, maximum width, and text alignment by adding modifiers between% and pattern characters. such as:  1)%20c: Specifies the name of the output category, the minimum width is 20, and if the category name is less than 20, the default is right-aligned.   2)%-20c: Specifies the name of the output category, the minimum width is 20, and if category's name is less than 20, the "-" number specifies left-aligned.   3)%.30c: Specifies the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more characters truncated, but less than 30 words will not have spaces.   4%20.30c: If the name of the category is less than 20 to fill the space, and the right alignment, if its name is longer than 30 characters, from the left side of the exported characters are cut off.

log4j Application Example

Test the project structure of the log4j

The log4j.properties path is src/config/log4j

Contents of log4j.properties File

The following defines the log output level as INFO and has 2 output destinations configured, one is A3, one is CONSOLE Log4j.rootlogger = info,a3,console//log lowest output level  
Log4j.appender.a3.threshold=info Log4j.appender.a3.encoding=utf-8//daily produces a file Dailyrollingfileappender Log4j.appender.A3 = Org.apache.log4j.DailyRollingFileAppender//file property specifies the location where the log file is to be saved and the file name, which is configured under Windows//c:/ Logtest/logtest.log,//company project under the Linux configuration is/app/weblogic/applications/logs/sxvip_logs log4j.appender.a3.file=c:/ Logtest/logtest.log//When there is log output immediately, the default is True Log4j.appender.a3.immediateflush=true log4j.appender.a3.datepattern= ' _ '
YYYY-MM-DD//Log layout mode Log4j.appender.a3.layout=org.apache.log4j.patternlayout//log format in log file Log4j.appender.a3.layout.conversionpattern=%-d{yyyy/mm/dd HH:mm:ss} OSS%-5p [%c]-%m%n//
Here you use Org.apache.log4j.ConsoleAppender to specify that you want to output the log to the console Log4j.appender.console=org.apache.log4j.consoleappender Log4j.appender.threshold=info//Output target is console log4j.appender.console.target=system.out log4j.appender.console.layout= Org.apache.log4j.PatternLayout Log4j.appender.CONSOLE.layout.ConversionPAttern=%-d{yyyy/mm/dd HH:mm:ss} OSS%-5p [%c]-%m%n 

Web.xml using spring configuration in Web applications log4j

Add a configuration
<!--Configure the path to the log4j configuration file in Web.xml, either XML or properties (this parameter must be matched)--> is 
used below Classpath parameter specifies the location of the Log4j.properties file so that the log4j configuration file does not have to be placed under src
<context-param>
   <param-name> Log4jconfiglocation</param-name>
 <param-value>classpath:config/log4j/log4j.properties</ param-value>
</context-param> 
Use the spring listener to read the log4j configuration file when the application starts
<listener>
< Listener-class>org.springframework.web.util.log4jconfiglistener</listener-class>
</listener >

Using log4j in Java

Import Org.apache.commons.logging.Log;
Import org.apache.commons.logging.LogFactory; 
public class Myserviceparamaction extends baseadmaction{

private static final log = 
Logfactory.getlog ( Myserviceparamaction.class);


Public Actionforward Ngcallserviceinfo (actionmapping mapping, actionform form,
    httpservletrequest request, HttpServletResponse response) {
    //Get login user information, no login prompt user needs to log
    in Log.info ("My service query starts .....................................");
    UserBean user = (UserBean) request.getsession (). getattribute ("User_info");
    Log.info ("Get login user from session                 " +user);
    if (user!= null) {
        log.info ("user.getmisisdn ()            " +user.getmsisdn ()); 
. . . 
}

When the application is started, the log files are generated under the log4j configuration (log4j.appender.a3.file=c:/logtest/logtestxxx.log) under C disk

When you access a project's resources, you add log information to the file

2013/12/05 11:46:33 OSS INFO [com.sinovatech.myservice.action.MyServiceParamAction]-My service query started ....

2013/12/05 11:46:33 OSS INFO [com.sinovatech.myservice.action.MyServiceParamAction]-Get login user null from session

2013/12/05 11:46:33 OSS INFO [com.sinovatech.myservice.action.MyServiceParamAction]-VIP My service query end ...

Note When you test in the main method of the Java class, you do not add log information to the log file

application in the Javaweb project


Import Org.apache.log4j.Logger; Import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.stereotype.Service; Import Com.hsinghsu.testSSH.dao.UserDao; Import Com.hsinghsu.testSSH.model.User; Import Com.hsinghsu.testSSH.service.UserService;

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.