log4j系统动态配置程序日志
- 指定文件大小的滚动日志【文件大小到达指定尺寸的时候产生一个新的文件】
1 package com.byttersoft.util.log4j; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.Writer; 6 7 import org.apache.log4j.FileAppender; 8 import org.apache.log4j.Layout; 9 import org.apache.log4j.helpers.CountingQuietWriter; 10 import org.apache.log4j.helpers.LogLog; 11 import org.apache.log4j.helpers.OptionConverter; 12 import org.apache.log4j.spi.LoggingEvent; 13 14 public class RollingFileAppender extends FileAppender { 15 protected long maxFileSize = 10485760L; 16 17 protected int maxBackupIndex = 1; 18 19 private long nextRollover = 0L; 20 21 22 public RollingFileAppender() { 23 } 24 25 public RollingFileAppender(Layout layout, String filename, boolean append) 26 throws IOException { 27 super(layout, filename, append); 28 } 29 30 public RollingFileAppender(Layout layout, String filename) 31 throws IOException { 32 super(layout, filename); 33 } 34 35 public int getMaxBackupIndex() { 36 return this.maxBackupIndex; 37 } 38 39 public long getMaximumFileSize() { 40 return this.maxFileSize; 41 } 42 43 public void rollOver() { 44 if (this.qw != null) { 45 long size = ((CountingQuietWriter) this.qw).getCount(); 46 LogLog.debug("rolling over count=" + size); 47 48 this.nextRollover = (size + this.maxFileSize); 49 } 50 LogLog.debug("maxBackupIndex=" + this.maxBackupIndex); 51 52 boolean renameSucceeded = true; 53 54 int lastIndex=this.fileName.lastIndexOf("."); 55 String fileNameBegin=this.fileName; 56 String fileNameEnd=""; 57 if(lastIndex!=-1){ 58 fileNameBegin=this.fileName.substring(0,lastIndex); 59 fileNameEnd=this.fileName.substring(lastIndex); 60 } 61 if (this.maxBackupIndex > 0) { 62 File file = new File(fileNameBegin + "(" + this.maxBackupIndex + ")" + fileNameEnd); 63 if (file.exists()) { 64 renameSucceeded = file.delete(); 65 } 66 67 for (int i = this.maxBackupIndex - 1; (i >= 1) && (renameSucceeded); i--) { 68 file = new File(fileNameBegin + "(" + i + ")" + fileNameEnd); 69 if (file.exists()) { 70 File target = new File(fileNameBegin + "(" + (i+1) + ")" + fileNameEnd); 71 LogLog.debug("Renaming file " + file + " to " + target); 72 renameSucceeded = file.renameTo(target); 73 } 74 } 75 76 if (renameSucceeded) { 77 File target = new File(fileNameBegin + "(" + 1 + ")" + fileNameEnd); 78 79 closeFile(); 80 81 file = new File(this.fileName); 82 LogLog.debug("Renaming file " + file + " to " + target); 83 renameSucceeded = file.renameTo(target); 84 85 if (!renameSucceeded) { 86 try { 87 setFile(this.fileName, true, this.bufferedIO, 88 this.bufferSize); 89 } catch (IOException e) { 90 LogLog.error("setFile(" + this.fileName 91 + ", true) call failed.", e); 92 } 93 94 } 95 96 } 97 98 } 99 100 if (renameSucceeded) { 101 try { 102 setFile(this.fileName, false, this.bufferedIO, this.bufferSize); 103 this.nextRollover = 0L; 104 } catch (IOException e) { 105 LogLog.error("setFile(" + this.fileName 106 + ", false) call failed.", e); 107 } 108 } 109 } 110 111 public synchronized void setFile(String fileName, boolean append, 112 boolean bufferedIO, int bufferSize) throws IOException { 113 super.setFile(fileName, append, this.bufferedIO, this.bufferSize); 114 if (append) { 115 File f = new File(fileName); 116 ((CountingQuietWriter) this.qw).setCount(f.length()); 117 } 118 } 119 120 public void setMaxBackupIndex(int maxBackups) { 121 this.maxBackupIndex = maxBackups; 122 } 123 124 public void setMaximumFileSize(long maxFileSize) { 125 this.maxFileSize = maxFileSize; 126 } 127 128 public void setMaxFileSize(String value) { 129 this.maxFileSize = OptionConverter.toFileSize(value, 130 this.maxFileSize + 1L); 131 } 132 133 protected void setQWForFiles(Writer writer) { 134 this.qw = new CountingQuietWriter(writer, this.errorHandler); 135 } 136 137 protected void subAppend(LoggingEvent event) { 138 super.subAppend(event); 139 if ((this.fileName != null) && (this.qw != null)) { 140 long size = ((CountingQuietWriter) this.qw).getCount(); 141 if ((size >= this.maxFileSize) && (size >= this.nextRollover)) 142 rollOver(); 143 } 144 } 145 }
- 按天滚动生成日志 DailyRollingFileAppender 【每天产生一个日志文件】
1 package com.byttersoft.util.log4j; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.text.SimpleDateFormat; 6 import java.util.Date; 7 import java.util.Locale; 8 import java.util.TimeZone; 9 10 import org.apache.log4j.FileAppender; 11 import org.apache.log4j.Layout; 12 import org.apache.log4j.helpers.LogLog; 13 import org.apache.log4j.spi.LoggingEvent; 14 15 public class DailyRollingFileAppender extends FileAppender { 16 static final int TOP_OF_TROUBLE = -1; 17 static final int TOP_OF_MINUTE = 0; 18 static final int TOP_OF_HOUR = 1; 19 static final int HALF_DAY = 2; 20 static final int TOP_OF_DAY = 3; 21 static final int TOP_OF_WEEK = 4; 22 static final int TOP_OF_MONTH = 5; 23 private String datePattern = "'.'yyyy-MM-dd"; 24 private String scheduledFilename; 25 private String formatName; 26 private long nextCheck = System.currentTimeMillis() - 1L; 27 28 Date now = new Date(); 29 SimpleDateFormat sdf; 30 RollingCalendar rc = new RollingCalendar(); 31 32 int checkPeriod = -1; 33 34 static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT"); 35 36 37 //添加按 38 39 public DailyRollingFileAppender() { 40 } 41 42 public DailyRollingFileAppender(Layout layout, String filename, 43 String datePattern) throws IOException { 44 super(layout, filename, true); 45 this.datePattern = datePattern; 46 activateOptions(); 47 } 48 49 public DailyRollingFileAppender(Layout layout, String filename, boolean append) 50 throws IOException { 51 super(layout, filename, append); 52 } 53 54 public DailyRollingFileAppender(Layout layout, String filename) 55 throws IOException { 56 super(layout, filename); 57 } 58 59 public void setDatePattern(String pattern) { 60 this.datePattern = pattern; 61 } 62 63 public String getDatePattern() { 64 return this.datePattern; 65 } 66 67 public void activateOptions() { 68 super.activateOptions(); 69 if ((this.datePattern != null) && (this.fileName != null)) { 70 this.now.setTime(System.currentTimeMillis()); 71 this.sdf = new SimpleDateFormat(this.datePattern); 72 int type = computeCheckPeriod(); 73 printPeriodicity(type); 74 this.rc.setType(type); 75 File file = new File(this.fileName); 76 this.formatName=this.sdf.format(new Date( 77 file.lastModified())); 78 this.scheduledFilename = (this.fileName + this.formatName); 79 } else { 80 LogLog.error("Either File or DatePattern options are not set for appender [" 81 + this.name + "]."); 82 } 83 } 84 85 void printPeriodicity(int type) { 86 switch (type) { 87 case 0: 88 LogLog.debug("Appender [" + this.name 89 + "] to be rolled every minute."); 90 break; 91 case 1: 92 LogLog.debug("Appender [" + this.name 93 + "] to be rolled on top of every hour."); 94 95 break; 96 case 2: 97 LogLog.debug("Appender [" + this.name 98 + "] to be rolled at midday and midnight."); 99 100 break; 101 case 3: 102 LogLog.debug("Appender [" + this.name 103 + "] to be rolled at midnight."); 104 105 break; 106 case 4: 107 LogLog.debug("Appender [" + this.name 108 + "] to be rolled at start of week."); 109 110 break; 111 case 5: 112 LogLog.debug("Appender [" + this.name 113 + "] to be rolled at start of every month."); 114 115 break; 116 default: 117 LogLog.warn("Unknown periodicity for appender [" + this.name + "]."); 118 } 119 } 120 121 int computeCheckPeriod() { 122 RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, 123 Locale.ENGLISH); 124 125 Date epoch = new Date(0L); 126 if (this.datePattern != null) { 127 for (int i = 0; i <= 5; i++) { 128 SimpleDateFormat simpleDateFormat = new SimpleDateFormat( 129 this.datePattern); 130 simpleDateFormat.setTimeZone(gmtTimeZone); 131 String r0 = simpleDateFormat.format(epoch); 132 rollingCalendar.setType(i); 133 Date next = new Date(rollingCalendar.getNextCheckMillis(epoch)); 134 String r1 = simpleDateFormat.format(next); 135 136 if ((r0 != null) && (r1 != null) && (!r0.equals(r1))) { 137 return i; 138 } 139 } 140 } 141 return -1; 142 } 143 144 void rollOver() throws IOException { 145 if (this.datePattern == null) { 146 this.errorHandler 147 .error("Missing DatePattern option in rollOver()."); 148 return; 149 } 150 String formatNameNew = this.sdf.format(this.now); 151 String datedFilename = this.fileName + formatNameNew; 152 153 if (this.scheduledFilename.equals(datedFilename)) { 154 return; 155 } 156 157 closeFile(); 158 159 //修改滚存文件 160 int lastIndex=this.fileName.lastIndexOf("."); 161 String fileNameBegin=this.fileName; 162 String fileNameEnd=""; 163 if(lastIndex!=-1){ 164 fileNameBegin=this.fileName.substring(0,lastIndex); 165 fileNameEnd=this.fileName.substring(lastIndex); 166 } 167 168 File target = new File(fileNameBegin+this.formatName+fileNameEnd); 169 if (target.exists()) { 170 target.delete(); 171 } 172 173 File file = new File(this.fileName); 174 boolean result = file.renameTo(target); 175 if (result) 176 LogLog.debug(this.fileName + " -> " + fileNameBegin+this.formatName+fileNameEnd); 177 else { 178 LogLog.error("Failed to rename [" + this.fileName + "] to [" 179 + fileNameBegin+this.formatName+fileNameEnd + "]."); 180 } 181 182 int maxBackupIndex=getMaxBackupIndex(); 183 for(int i=1;i<=maxBackupIndex;i++){ 184 target = new File(fileNameBegin+this.formatName+"("+i+")"+fileNameEnd); 185 if (target.exists()) { 186 target.delete(); 187 } 188 189 file = new File(fileNameBegin+"("+i+")"+fileNameEnd); 190 if(file.exists()){ 191 result = file.renameTo(target); 192 if (result) 193 LogLog.debug(fileNameBegin+"("+i+")"+fileNameEnd + " -> " + fileNameBegin+this.formatName+"("+i+")"+fileNameEnd); 194 else { 195 LogLog.error("Failed to rename [" + fileNameBegin+"("+i+")"+fileNameEnd + "] to [" 196 + fileNameBegin+this.formatName+"("+i+")"+fileNameEnd + "]."); 197 } 198 } 199 } 200 201 202 try { 203 setFile(this.fileName, false, this.bufferedIO, this.bufferSize); 204 } catch (IOException e) { 205 this.errorHandler.error("setFile(" + this.fileName 206 + ", false) call failed."); 207 } 208 this.scheduledFilename = datedFilename; 209 this.formatName = formatNameNew; 210 } 211 212 public int getMaxBackupIndex() { 213 return 0; 214 } 215 216 protected void subAppend(LoggingEvent event) { 217 long n = System.currentTimeMillis(); 218 if (n >= this.nextCheck) { 219 this.now.setTime(n); 220 this.nextCheck = this.rc.getNextCheckMillis(this.now); 221 try { 222 rollOver(); 223 } catch (IOException ioe) { 224 LogLog.error("rollOver() failed.", ioe); 225 } 226 } 227 228 super.subAppend(event); 229 } 230 }
- 按天及固定大小滚动生成日志 DailyRollingAllFileAppender【日期和滚存同时进行】
1 package com.byttersoft.util.log4j; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.Writer; 6 7 import org.apache.log4j.Layout; 8 import org.apache.log4j.helpers.CountingQuietWriter; 9 import org.apache.log4j.helpers.LogLog; 10 import org.apache.log4j.helpers.OptionConverter; 11 import org.apache.log4j.spi.LoggingEvent; 12 13 public class DailyRollingAllFileAppender extends DailyRollingFileAppender { 14 protected long maxFileSize = 10485760L; 15 16 protected int maxBackupIndex = 1; 17 18 private long nextRollover = 0L; 19 20 21 public DailyRollingAllFileAppender() { 22 } 23 24 public DailyRollingAllFileAppender(Layout layout, String filename, 25 String datePattern) throws IOException { 26 super(layout, filename, datePattern); 27 } 28 29 public DailyRollingAllFileAppender(Layout layout, String filename, boolean append) 30 throws IOException { 31 super(layout, filename, append); 32 } 33 34 public DailyRollingAllFileAppender(Layout layout, String filename) 35 throws IOException { 36 super(layout, filename); 37 } 38 39 public int getMaxBackupIndex() { 40 return this.maxBackupIndex; 41 } 42 43 public long getMaximumFileSize() { 44 return this.maxFileSize; 45 } 46 47 public void rollOverOther() { 48 if (this.qw != null) { 49 long size = ((CountingQuietWriter) this.qw).getCount(); 50 LogLog.debug("rolling over count=" + size); 51 52 this.nextRollover = (size + this.maxFileSize); 53 } 54 LogLog.debug("maxBackupIndex=" + this.maxBackupIndex); 55 56 boolean renameSucceeded = true; 57 58 int lastIndex=this.fileName.lastIndexOf("."); 59 String fileNameBegin=this.fileName; 60 String fileNameEnd=""; 61 if(lastIndex!=-1){ 62 fileNameBegin=this.fileName.substring(0,lastIndex); 63 fileNameEnd=this.fileName.substring(lastIndex); 64 } 65 if (this.maxBackupIndex > 0) { 66 File file = new File(fileNameBegin + "(" + this.maxBackupIndex + ")" + fileNameEnd); 67 if (file.exists()) { 68 renameSucceeded = file.delete(); 69 } 70 71 for (int i = this.maxBackupIndex - 1; (i >= 1) && (renameSucceeded); i--) { 72 file = new File(fileNameBegin + "(" + i + ")" + fileNameEnd); 73 if (file.exists()) { 74 File target = new File(fileNameBegin + "(" + (i+1) + ")" + fileNameEnd); 75 LogLog.debug("Renaming file " + file + " to " + target); 76 renameSucceeded = file.renameTo(target); 77 } 78 } 79 80 if (renameSucceeded) { 81 File target = new File(fileNameBegin + "(" + 1 + ")" + fileNameEnd); 82 83 closeFile(); 84 85 file = new File(this.fileName); 86 LogLog.debug("Renaming file " + file + " to " + target); 87 renameSucceeded = file.renameTo(target); 88 89 if (!renameSucceeded) { 90 try { 91 setFile(this.fileName, true, this.bufferedIO, 92 this.bufferSize); 93 } catch (IOException e) { 94 LogLog.error("setFile(" + this.fileName 95 + ", true) call failed.", e); 96 } 97 98 } 99 100 } 101 102 } 103 104 if (renameSucceeded) { 105 try { 106 setFile(this.fileName, false, this.bufferedIO, this.bufferSize); 107 this.nextRollover = 0L; 108 } catch (IOException e) { 109 LogLog.error("setFile(" + this.fileName 110 + ", false) call failed.", e); 111 } 112 } 113 } 114 115 public synchronized void setFile(String fileName, boolean append, 116 boolean bufferedIO, int bufferSize) throws IOException { 117 super.setFile(fileName, append, this.bufferedIO, this.bufferSize); 118 if (append) { 119 File f = new File(fileName); 120 ((CountingQuietWriter) this.qw).setCount(f.length()); 121 } 122 } 123 124 public void setMaxBackupIndex(int maxBackups) { 125 this.maxBackupIndex = maxBackups; 126 } 127 128 public void setMaximumFileSize(long maxFileSize) { 129 this.maxFileSize = maxFileSize; 130 } 131 132 public void setMaxFileSize(String value) { 133 this.maxFileSize = OptionConverter.toFileSize(value, 134 this.maxFileSize + 1L); 135 } 136 137 protected void setQWForFiles(Writer writer) { 138 this.qw = new CountingQuietWriter(writer, this.errorHandler); 139 } 140 141 protected void subAppend(LoggingEvent event) { 142 super.subAppend(event); 143 if ((this.fileName != null) && (this.qw != null)) { 144 long size = ((CountingQuietWriter) this.qw).getCount(); 145 if ((size >= this.maxFileSize) && (size >= this.nextRollover)) 146 rollOverOther(); 147 } 148 } 149 }
- 滚动日历
1 package com.byttersoft.util.log4j; 2 3 import java.util.Date; 4 import java.util.GregorianCalendar; 5 import java.util.Locale; 6 import java.util.TimeZone; 7 8 class RollingCalendar extends GregorianCalendar 9 { 10 private static final long serialVersionUID = -3560331770601814177L; 11 int type = -1; 12 13 RollingCalendar() 14 { 15 } 16 17 RollingCalendar(TimeZone tz, Locale locale) { 18 super(tz, locale); 19 } 20 21 void setType(int type) { 22 this.type = type; 23 } 24 25 public long getNextCheckMillis(Date now) { 26 return getNextCheckDate(now).getTime(); 27 } 28 29 public Date getNextCheckDate(Date now) { 30 setTime(now); 31 32 switch (this.type) { 33 case 0: 34 set(13, 0); 35 set(14, 0); 36 add(12, 1); 37 break; 38 case 1: 39 set(12, 0); 40 set(13, 0); 41 set(14, 0); 42 add(11, 1); 43 break; 44 case 2: 45 set(12, 0); 46 set(13, 0); 47 set(14, 0); 48 int hour = get(11); 49 if (hour < 12) { 50 set(11, 12); 51 } else { 52 set(11, 0); 53 add(5, 1); 54 } 55 break; 56 case 3: 57 set(11, 0); 58 set(12, 0); 59 set(13, 0); 60 set(14, 0); 61 add(5, 1); 62 break; 63 case 4: 64 set(7, getFirstDayOfWeek()); 65 set(11, 0); 66 set(12, 0); 67 set(13, 0); 68 set(14, 0); 69 add(3, 1); 70 break; 71 case 5: 72 set(5, 1); 73 set(11, 0); 74 set(12, 0); 75 set(13, 0); 76 set(14, 0); 77 add(2, 1); 78 break; 79 default: 80 throw new IllegalStateException("Unknown periodicity type."); 81 } 82 return getTime(); 83 } 84 }
- 工具类
1 package com.byttersoft.util.log4j; 2 3 import java.io.IOException; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import org.apache.log4j.Appender; 8 import org.apache.log4j.FileAppender; 9 import org.apache.log4j.Level; 10 import org.apache.log4j.LogManager; 11 import org.apache.log4j.Logger; 12 import org.apache.log4j.PatternLayout; 13 14 import com.byttersoft.framework.exception.BtRuntimeException; 15 import com.byttersoft.util.StringUtil; 16 17 /** 18 * log4j日志管理Util类 19 * @author zhengg 20 * 21 */ 22 public class Log4jManageUtil { 23 24 public static Map<String,String> LOG_TYPE=new HashMap<String, String>(); 25 26 static{ 27 LOG_TYPE.put("DATE_SIZE", "com.byttersoft.util.log4j.DailyRollingAllFileAppender");//日期和滚存同时进行 28 LOG_TYPE.put("DATE", "com.byttersoft.util.log4j.DailyRollingFileAppender");//明天生成一个日志文件 29 LOG_TYPE.put("SIZE", "com.byttersoft.util.log4j.RollingFileAppender");//根据大小生成文件 30 } 31 32 /** 33 * 通过日志别称获取日志对象 34 * @param logName 35 * @return 36 */ 37 public static Logger getLogger(String logName){ 38 Logger log=LogManager.getLogger(logName); 39 if(log==null){ 40 throw new BtRuntimeException("日志("+logName+")不存在。"); 41 } 42 return log; 43 } 44 45 /** 46 * 通过类class获取日志对象 47 * @param logName 48 * @return 49 */ 50 public static Logger getLogger(Class<?> clazz){ 51 return LogManager.getLogger(clazz); 52 } 53 54 /** 55 * 通过日志别称设置日志级别 56 * @param logName 日志别称 57 * @param level 日志级别(ERROR,WARN,INFO,DEBUG) 58 */ 59 public static void setLevel(String logName,String level){ 60 getLogger(logName).setLevel(Level.toLevel(level,Level.DEBUG)); 61 } 62 63 /** 64 * 通过类class设置日志级别 65 * @param clazz 66 * @param level 日志级别(ERROR,WARN,INFO,DEBUG) 67 */ 68 public static void setLevel(Class<?> clazz,String level){ 69 getLogger(clazz).setLevel(Level.toLevel(level,Level.DEBUG)); 70 } 71 72 /** 73 * 获取生成日志方式类 74 * @param logName 75 * @param appName 76 * @return 77 */ 78 public static FileAppender getFileAppender(String logName,String appName){ 79 Appender appender=getLogger(logName).getAppender(appName); 80 if(appender==null){ 81 throw new BtRuntimeException("日志Appender("+appName+")不存在。"); 82 } 83 return (FileAppender) appender; 84 } 85 86 /** 87 * 设置日志记录格式 88 * @param logName 89 * @param className 只支持(DailyRollingFileAppender、RollingFileAppender、DailyRollingAllFileAppender)三种格式 90 * @param file 文件地址 91 * @param conPattern 设置输出方式 92 * @param datePattern 设置日期添加格式和生成日期格式 93 * @param maxFileSize 设置文件滚存大小 94 * @param maxBackupIndex 设置最大文件个数 95 * @throws IOException 96 */ 97 public static void setAppender(String logName,String className,String file,String conPattern,String datePattern,String maxFileSize,Integer maxBackupIndex) throws IOException{ 98 Logger log=LogManager.getLogger(logName); 99 FileAppender app=(FileAppender)log.getAppender(logName); 100 if(!StringUtil.isBlank_new(className)||app==null){//更改记录日志类型 101 PatternLayout layout=new PatternLayout(); 102 layout.setConversionPattern(conPattern); 103 if(String.valueOf(className).indexOf(".DailyRollingFileAppender")!=-1){ 104 app=new DailyRollingFileAppender(layout, file, datePattern); 105 }else if(String.valueOf(className).indexOf(".RollingFileAppender")!=-1){ 106 app=new RollingFileAppender(layout, file); 107 }else{ 108 app=new DailyRollingAllFileAppender(layout, file, datePattern); 109 } 110 if(app!=null){ 111 log.removeAllAppenders(); 112 app.setName(logName); 113 log.addAppender(app); 114 } 115 } 116 app.setFile(file);//设置文件地址 117 if(!StringUtil.isBlank_new(conPattern)){//ConversionPattern设置输出方式 118 PatternLayout layout=new PatternLayout(); 119 layout.setConversionPattern(conPattern); 120 app.setLayout(layout); 121 } 122 String classNameNew=app.getClass().toString(); 123 if(!StringUtil.isBlank_new(datePattern) 124 &&(classNameNew.indexOf(".DailyRollingAllFileAppender")!=-1 125 ||classNameNew.indexOf(".DailyRollingFileAppender")!=-1)){//设置日志添加日期格式和生成日志格式 126 DailyRollingFileAppender drfApp=(DailyRollingFileAppender)app; 127 drfApp.setDatePattern(datePattern); 128 } 129 if(!StringUtil.isBlank_new(maxFileSize)){//设置文件大小 130 if(classNameNew.indexOf(".DailyRollingAllFileAppender")!=-1){ 131 DailyRollingAllFileAppender drafApp=(DailyRollingAllFileAppender)app; 132 drafApp.setMaxFileSize(maxFileSize); 133 }else if(classNameNew.indexOf(".RollingFileAppender")!=-1){ 134 RollingFileAppender rfApp=(RollingFileAppender)app; 135 rfApp.setMaxFileSize(maxFileSize); 136 } 137 } 138 if(maxBackupIndex!=null){//设置最大文件个数 139 if(classNameNew.indexOf(".DailyRollingAllFileAppender")!=-1){ 140 DailyRollingAllFileAppender drafApp=(DailyRollingAllFileAppender)app; 141 drafApp.setMaxBackupIndex(maxBackupIndex); 142 }else if(classNameNew.indexOf(".RollingFileAppender")!=-1){ 143 RollingFileAppender rfApp=(RollingFileAppender)app; 144 rfApp.setMaxBackupIndex(maxBackupIndex); 145 } 146 } 147 } 148 149 /** 150 * 设置日志文件地址 151 * @param logName 152 * @param file 153 * @throws IOException 154 */ 155 public static void setFile(String logName,String file) throws IOException{ 156 setAppender(logName, null, file, null, null, null,null); 157 } 158 159 public static void main(String[] args) { 160 Logger log=LogManager.getLogger("VPAYSendDataLog"); 161 162 // log.setLevel(level) 163 // Appender app=new dailyRollinga 164 // log.getAppender(name); 165 Appender app=log.getAppender("VPAYSendDataLog"); 166 String className=app.getClass().toString(); 167 System.out.println(app.getClass().toString()); 168 if(className.indexOf("DailyRollingAllFileAppender")!=-1){ 169 DailyRollingAllFileAppender dra=(DailyRollingAllFileAppender) app; 170 dra.getMaxBackupIndex(); 171 dra.setFile("D:\\ss/s/\\ss"); 172 } 173 // for(int i=0;i<4;i++){ 174 // Layout layout=new PatternLayout("%d - %m%n"); 175 // Appender app=new DailyRollingFileAppender(layout, "D:\\tj\\logs/"+i+"ss.txt","'.'yyyy-MM-dd'.txt'"); 176 // log.addAppender(app); 177 // } 178 // app.set 179 //// RollingFileAppender fa= 180 // log.addAppender(app); 181 // Enumeration enu=log.getAllAppenders(); 182 // while(enu.hasMoreElements()){ 183 // Appender app=(Appender) enu.nextElement(); 184 // System.out.println(app.getName()); 185 // } 186 187 log.info("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 188 log.info("2ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 189 log.info("3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 190 log.info("4ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 191 log.info("5ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 192 log.info("6ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 193 log.info("7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 194 log.info("8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); 195 } 196 197 }
- 项目启动加载类。可自己扩展在项目页面中动态设置
1 package com.byttersoft.util.log4j; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 7 import javax.servlet.ServletContextEvent; 8 import javax.servlet.ServletContextListener; 9 10 import org.apache.log4j.LogManager; 11 import org.apache.log4j.Logger; 12 13 import com.byttersoft.admin.bean.ErpInterfaceLogTypeSearchBean; 14 import com.byttersoft.admin.service.ErpInterfaceLogTypeService; 15 import com.byttersoft.dataexchange.base.TaskBase; 16 import com.byttersoft.persistence.admin.entity.ErpInterfaceLogType; 17 import com.byttersoft.util.SpringContextUtil; 18 19 public class Log4jInit implements ServletContextListener { 20 21 private Logger log=LogManager.getRootLogger(); 22 23 public void contextDestroyed(ServletContextEvent arg0) { 24 log.info("==========log4j日志初始化信息进行销毁=========="); 25 } 26 27 public void contextInitialized(ServletContextEvent arg0) { 28 log.info("==========log4j日志系统初始化开始=========="); 29 ErpInterfaceLogTypeSearchBean searchBean=new ErpInterfaceLogTypeSearchBean(); 30 searchBean.setAvailableFlag(1); 31 ErpInterfaceLogTypeService service = (ErpInterfaceLogTypeService)SpringContextUtil.getBean("erpInterfaceLogTypeService");; 32 List<ErpInterfaceLogType> logTypeList=service.getErpInterfaceLogType(searchBean); 33 for(ErpInterfaceLogType logType:logTypeList){ 34 try { 35 String filePath=logType.getLogFile()+"/"+logType.getCode()+"/"+logType.getCode()+".log"; 36 File file=new File(filePath); 37 if(file.exists()){ 38 File file1=new File(logType.getLogFile()+"/"+logType.getCode()); 39 file1.mkdirs(); 40 file.createNewFile(); 41 } 42 Log4jManageUtil.setAppender(logType.getCode(), 43 Log4jManageUtil.LOG_TYPE.get(logType.getLogType()), 44 filePath, 45 logType.getConPattern(), 46 logType.getDatePattern(), 47 logType.getMaxFileSize(), 48 logType.getMaxBackupIndex()); 49 Log4jManageUtil.setLevel(logType.getCode(), logType.getLogLevel()); 50 } catch (IOException e) { 51 e.printStackTrace(); 52 log.error(e.getMessage()); 53 } 54 log.info("==========log4j日志系统初始化:"+logType.getName()+"("+logType.getCode()+")成功!"); 55 } 56 log.info("==========log4j日志系统初始化结束=========="); 57 log.info("==========允许定时任务启动开始设置=========="+TaskBase.isProcess); 58 TaskBase.isProcess=true; 59 log.info("==========允许定时任务启动结束设置=========="+TaskBase.isProcess); 60 61 } 62 63 }
- 数据库表【oracle】
此表存储要 打印的日志类名称、打印模板、日志文件大小、日志文件存储类型、日志级别
其他数据库及程序的查询,很简单。都自己实现吧
1 CREATE TABLE 2 ERP_INTERFACE_LOG_TYPE 3 ( 4 NAME VARCHAR2(50), 5 CODE VARCHAR2(50), 6 AVAILABLE_FLAG NUMBER DEFAULT 1, 7 UUID VARCHAR2(32) NOT NULL, 8 LOG_FILE VARCHAR2(100) DEFAULT 'D:/logs', 9 LOG_TYPE VARCHAR2(50) DEFAULT 'DATE_SIZE', 10 CON_PATTERN VARCHAR2(50) DEFAULT '%d - %m%n', 11 DATE_PATTERN VARCHAR2(50), 12 MAX_FILE_SIZE VARCHAR2(50) DEFAULT '20MB', 13 MAX_BACKUP_INDEX NUMBER DEFAULT 20, 14 LOG_LEVEL VARCHAR2(20) DEFAULT 'DEBUG' , 15 CONSTRAINT ERP_INTERFACE_LOG_PK_VALUE PRIMARY KEY (UUID) 16 ); 17 COMMENT ON TABLE ERP_INTERFACE_LOG_TYPE 18 IS 19 '接口类型信息记录'; 20 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.NAME 21 IS 22 '日志名称'; 23 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.CODE 24 IS 25 '日志别称'; 26 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.AVAILABLE_FLAG 27 IS 28 '是否可用(是:1,否:0)'; 29 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.UUID 30 IS 31 'ID'; 32 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.LOG_FILE 33 IS 34 '日志地址'; 35 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.LOG_TYPE 36 IS 37 'DATE_SIZE(明天生成一个文件且一天中感觉大小滚存),DATE明天生成一个文件,SIZE感觉大小滚存文件'; 38 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.CON_PATTERN 39 IS 40 '设置输出方式'; 41 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.DATE_PATTERN 42 IS 43 '设置日志添加日期格式和生成日志格式'; 44 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.MAX_FILE_SIZE 45 IS 46 '设置文件大小 KB/MB'; 47 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.MAX_BACKUP_INDEX 48 IS 49 '最多文件个数'; 50 COMMENT ON COLUMN ERP_INTERFACE_LOG_TYPE.LOG_LEVEL 51 IS 52 '日志级别:错误ERROR,警告WARN,信息INFO,调试DEBUG';