Java custom log output file
Log printing is essential in the program. If you need to print different logs to different places, you need to define different Appender, then define the log level, print form, and log output path of each Appender.
1 log4j output multiple custom log files
If an independent log file needs to be output in practical applications, how can we separate the required content from the original log to form a separate log file?
First look at a common log4j. properties file, which records logs in the console and test. log file:
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c.%M(%L) - %m%n
What if multiple log files need to be output in the same category? In fact, the truth is the same. First, we define it in Test. java:
The configuration in log4j. properties is as follows:
log4j.appender.test2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c.%M(%L) - %m%n
Different logs must use different logger (for example, logger1.info ("abc") for output to test1.log ")).
Another problem is that these custom logs are output to the logs configured by log4j. rootLogger at the same time by default. How can they only be output to the specified logs? Don't worry. Here is a switch:
It is used to set whether to output data to the logs configured by log4j. rootLogger at the same time. If it is set to false, the data will not be output to other places.
However, this method has a small defect, that is, the class name in the printed log can only be mylogger or mylogger2.
2. dynamic configuration path
If the Log Path required by the program needs to be constantly changed, and the configuration file cannot be changed every time, the environment variable can be used to solve the problem.
Log4j configuration is as follows:
log4j.appender.DEBUGLOG.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c.%M(%L) - %m%n
Before using log to print logs, you must use System to define the log output path and file name environment variables:
SetProperty("Log. dir", logDir );
SetProperty("Log.info. file ",InfoLogFileName);
SetProperty("Log. debug. file ",DebugLogFileName);
Appendix: Format meaning of the Pattern parameter