Java API with its own log management, configurable file paths, and automatically create non-existent directories __java

Source: Internet
Author: User
Tags create directory log4j

Because the project needs to track the system information according to the log, easy to view the transmission data as well as the exception information, therefore intends to use the log4j to complete this log management function.

Unfortunately, in the use of the log4j found in the printing of exception information, and can not be like a console to print out the information in the tracking stack stacktrace to the configuration file specified in the log file.

May be my limited ability, online search a lot of information, tried a lot of methods are not.

Later found that the Java API with the log management Java.util.logging.Logger seems to be able to meet the requirements, and then tried a bit, the results were fulfilled, deeply gratified ah.

about how to use the Java self-brought log management, I believe there are many examples on the Internet, I do not repeat.

Here I just want to say that, when the configuration file path is loaded, if the path does not exist, the log management class Logmanager does not actively create a non-existent directory, but instead reports an exception as follows:

Can ' t load log handler ' Java.util.logging.FileHandler ' java.io.IOException:Couldn ' t get lock for c:/imessengerlogs/log% G.log java.io.IOException:Couldn ' t get lock for C:/imessengerlogs/log%g.log at Java.util.logging.FileHandler.openFiles (Unknown Source) at java.util.logging.filehandler.<init> (Unknown Source) at Sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native method) at Sun.reflect.NativeConstructorAccessorImpl.newInstance (Unknown Source) at Sun.reflect.DelegatingConstructorAccessorImpl.newInstance (Unknown Source) at Java.lang.reflect.Constructor.newInstance (Unknown source) at Java.lang.Class.newInstance0 (Unknown source) at Java.lang.Class.newInstance (Unknown source) at Java.util.logging.logmanager$3.run (Unknown source) at Java.security.AccessController.doPrivileged (Native method) at Java.util.logging.LogManager.loadLoggerHandlers ( Unknown source) at Java.util.logging.LogManager.initializeGlobalHandlers (Unknown source) at Java.util.logging.LogManager.access$1100 (Unknown source) at Java.util.logging.logmanager$rootlogger.gethandlers (Unknown source) at Java.util.logging.Logger.log (Unknown source) at Java.util.logging.Logger.doLog (Unknown source) at Java.util.logging.Logger.log (Unknown source) at Java.util.logging.Logger.info (Unknown source) at Com.log.LoggerTest.main (loggertest.java:13)

Therefore, you must read the directory of the log files in the configuration file before you load the configuration, determine if the directory exists, or create a directory if it does not exist.

The source code is as follows:

1.mylogmanager.java Log Management (read configuration file, create directory, load configuration file, get log object)

Package com.log;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties;
Import Java.util.logging.LogManager;

Import Java.util.logging.Logger;

	/** * * @author * * * */public class Mylogmanager {private static Logger Logger;
		static {InputStream is1 = null;
		InputStream is2 = null;
			try {//Read the configuration file, create the corresponding file directory String LogFilePath = "";
			Is1 = new FileInputStream ("D:\\workspace\\log\\src\\com\\log\\log.properties");
			Properties Properties = new properties ();
			Properties.load (IS1);
			String pattern = properties. GetProperty ("Java.util.logging.FileHandler.pattern");
			LogFilePath = pattern.substring (0, Pattern.lastindexof ("/"));
			File File = new file (LogFilePath);
			if (!file.exists ()) {file.mkdirs ();
			//Reinitialize Log properties and re-read log configuration Is2 = new FileInputStream ("D:\\workspace\\log\\src\\com\\log\\log.properties"); Logmanager Logmanager = logmanager.geTlogmanager ();

		Logmanager.readconfiguration (IS2);
		catch (SecurityException e) {e.printstacktrace ();
		catch (IOException e) {e.printstacktrace ();
				Finally {try {is1.close ();
			Is2.close ();
			catch (IOException e) {e.printstacktrace ();
		/** * Get Log Object * * @param clazz * @return/public static Logger GetLogger (class<?> clazz) {
		Logger = Logger.getlogger (Clazz.getname ());
	return logger;
 }
}

2.log.properties configuration file (with detailed comments)

#Level的五个等级SEVERE (highest), WARNING, INFO, CONFIG, FINE, Finer, FINEST (lowest value) #为 Handler Specify the default level (the default is Level.info). 
Java.util.logging.consolehandler.level=info # Specifies the name of the Formatter class to use (default is Java.util.logging.SimpleFormatter).
Java.util.logging.consolehandler.formatter=java.util.logging.simpleformatter # Specifies the default level for Handler (default is Level.ALL)
Java.util.logging.filehandler.level=info # Specifies the name of the Formatter class to use (default is Java.util.logging.XMLFormatter) Java.util.logging.filehandler.formatter=java.util.logging.simpleformatter # Specifies the approximate maximum amount (in bytes) to be written to any file, if the number is 0, 
There is no limit (default is unrestricted) java.util.logging.filehandler.limit=20480 # Specifies how many output files participate in the loop (default is 1). JAVA.UTIL.LOGGING.FILEHANDLER.COUNT=10 # Specifies a pattern for the generated output file name. For details see the following (default is "%h/java%u.log") # "/" Local pathname Separator # "%t" System temp Directory # "%h" "user.home" Value of System Properties # "%g" to differentiate circular log generation # "%u" the only resolution to resolve conflicts Number # "%" converts to a single percent symbol "%" # if the "%g" field is not specified and the file count is greater than 1, the build number is added after the decimal point at the end of the generated file name java.util.logging.filehandler.pattern=c:/ Testlogs/log%g.log # Specifies whether the Filehandler should be appended to any existing file (the default is False) java.util.logging. Filehandler.append=true # Specifies handler Handlers=java.util.logging.consolehandler,java.util.logging.filehandler

3.loggertest.java Log Test class

Package com.log;

Import Java.io.FileInputStream;
Import Java.util.logging.Level;
Import Java.util.logging.Logger;

public class Loggertest {

	private static Logger Logger = Mylogmanager.getlogger (loggertest.class);

	public static void Main (string[] args) {
		try {
			logger.info ("Print info");
			Nonexistent path
			String filePath = "C:\\workspace\\log\\src\\com\\log\\log.properties";
			/**
			 * Throws an exception:
			 * Java.io.filenotfoundexception:c:\workspace\log\src\com\log\log.properties (the system cannot find the specified path.) )
			 */
			new FileInputStream (FilePath);
		} catch (Exception e) {
			logger.log (level.severe, E.getmessage (), E);}}



4. Abnormal print information in the log file



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.