Java Print Log

Source: Internet
Author: User
Tags html form log log log4j

Previously developed Kjava game, did not develop how long, and then turn to Android, contact with Android are aware that Android has log print log, recently due to job needs, not print log ...

Although before there are some information to print, System.out.println (); Discovery is a bit of use, but when you program big, did not add some other data is very troublesome, such as printing a function, and then how many lines of error, System.out have a way to achieve, you can not put your corresponding function also printed in it ... In case of adding code, you have to change the function, and will kill you, this is the use of the log to reflect the big powerful ... Say more nonsense ~

1. Dependent Package

Log4j.jar Download Address: http://labs.mop.com/apache-mirror/logging/log4j/1.2.17/log4j-1.2.17.zip

Commons-logging-1.0.4.jar Download Address:http://www.java2s.com/Code/Jar/c/Downloadcommonslogging104jar.htm

2, the configuration root logger, its syntax is:
Log4j.rootlogger = [level], Appendername, Appendername, ...
Where level is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels 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 you specify the output of the log information. You can specify multiple output destinations at the same time.

3, the 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
Among them, LOG4J provides the following appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (a log file is generated every day),
Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the 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: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.
(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: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.
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. The corresponding format is as follows:
1) '. ' YYYY-MM: Monthly
2) '. ' YYYY-WW: Weekly
3) '. ' YYYY-MM-DD: Every day
4) '. ' Yyyy-mm-dd-a: two times a day
5) '. ' YYYY-MM-DD-HH: Per hour
6) '. ' YYYY-MM-DD-HH-MM: Per minute
(4). 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: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.
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.

4, configure the layout of the log information, the 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, LOG4J provides the following layout:
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 the time, thread, category, and so on that the log was generated)

5, output format settings
The log output format can be set by Log4j.appender.A1.layout.ConversionPattern in the configuration file.
Parameters:
%p: Output log information priority, i.e. Debug,info,warn,error,fatal,
%d: the date or time of the output log point-in-time, 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: The number of milliseconds to output from the application boot to the output of this log information
%c: The class that the output log information belongs to, usually the full name of the class in which it is located
%t: Output The name of the thread that generated the log event
%l: 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. Example: Testlog4.main (testlog4.java:10)
%x: The NDC (nested diagnostics environment) associated with the current line threads relative, especially in multiple client multi-threaded applications such as Java Servlets.
Percent%: output a "%" character
%F: The name of the file where the output log message was generated
%l: line number in output code
%M: The message specified in the output code, the resulting log specific information
%n: Output a carriage return line break, Windows platform for "\ r \ n", Unix platform for "\ n" Output log message Wrapping
You can control the minimum width, the maximum width, and the alignment of text 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, if the category 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.

6, in the application of the program
Before you use log4j in your program, you first import Commons-logging.jar and Logging-log4j-1.2.9.jar into classpath and place log4j.properties in the src root directory. The next step is to use.

7. Get Recorder
Using log4j, the first step is to get the logger, which will be responsible for controlling log information. Its syntax is:
public static Logger GetLogger (String name),
Gets the logger by the specified name and, if necessary, creates a new logger for that name. Name generally takes the names of this class, such as:
static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ());
Note: It is recommended to use commons-logging combined with log4j for logging
private static Log logger = Logfactory.getlog (Yourclass.class);

8. Insert record information (format log information)
When the two necessary steps are completed, you can easily insert any of the different priority logging statements into the places you want to log, with the following syntax:
Logger.debug (Object message);
Logger.info (Object message);
Logger.warn (Object message);
Logger.error (Object message);

9, configuration file log4j.properties: This is a simple one I deserve.

# Apply to console

Log4j.rootlogger=info, stdout
#output model style
log4j.appender.stdout= Org.apache.log4j.ConsoleAppender
#output Layout
log4j.appender.stdout.layout= Org.apache.log4j.PatternLayout
#output form
log4j.appender.stdout.layout.conversionpattern=%d%5p%c [%t] ( %F:%L)-%m%n


Keep a daily copy of

Log4j.appender.file = Org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=log./log
Log4j.appender.file.datepattern= '. ' Yyyy-mm-dd '. Log '
log4j.appender.file.layout=org.apache.log4j.patternlayout

Java files:

/**
 * @Title:
 * @Description: TODO (describe the file in a word)
 * @author Potter
 * @date 2013-1-11 afternoon 03:40:37
 * Version V1.0
 *
/public class Logdemo {

	static Log log=logfactory.getlog (Logdemo.class);
	
	public void log () {
	  propertyconfigurator.configure ("/config./log4j.properties");
		
	  Log.debug ("DSAFSD");
	  
      Log.info ("222");

      Log.warn ("333");

      Log.error ("4444");

      Log.fatal ("5555");
	}
	
	public static void Main (string[] args) {
		propertyconfigurator.configure ("./config/log4j.properties");
		Log.info ("Start");
		
		CCC C=new CCC ();
	}

CCC Category:

Class ccc{Public
	CCC () {
		LogDemo.log.warn ("CCC cu");
	}


Run Result:

2013-01-11 21:09:16,313 INFO Logdemo [main] (logdemo.java:33)-Start
2013-01-11 21:09:16,314 WARN Logdemo [main] (ccc.java:10)-CCC CU

It's much more comfortable to look at the information now.

Add:

1, in fact, a closer look of friends will find: Log=logfactory.getlog (logdemo.class);

So I just want to see the output of the following log, that the position of that class, is not fixed into Logdemo ... Oh. See the result is not fixed, oh, not fixed too good, we do not need to go every time. GetLog (Class), define a static, and then the whole program calls this log to print our OK

2, the best also put this log4j.properties configurable: I created a config folder and src folder in the same directory, and then dynamic acquisition, then packaged the program, do not have to repackage can also configure this log configuration file ... I don't know, please read this article: http://blog.csdn.net/aa4790139/article/details/8480395

Refer to the article:

Http://www.cnblogs.com/suman/archive/2010/10/23/1858864.html

http://blog.csdn.net/wirelessqa/article/details/7649845


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.