package com.hy.utils;

    import com.hy.config.ApplicationConfig;
    import com.hy.netty.SxzdDecoder;
    import org.apache.commons.lang.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;

    import javax.annotation.PreDestroy;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;

    /*
    文本记录日志

    @author qzf
    @update 2022-4-28 11:15:34
    1. 使用newSingleThreadExecutor线程写入文本日志;
    2. 支持二级目录,次级日志文件名

    */
    @Component
    public class MyLogUtil {
    private static final Logger log = LoggerFactory.getLogger(SxzdDecoder.class);
    private static String log_rootpath = ApplicationConfig.mylogRootPath;// 日志保存路径
    private static String log_rootname = ApplicationConfig.mylogRootName;// 日志文件名(前部分)
    private final static ExecutorService pool = Executors.newSingleThreadExecutor();
    @PreDestroy
    public void destroy(){
    System.out.print(“关闭mylog线程池”);
    log.info(“关闭mylog线程池”);
    shutdownPool();
    }
    private void shutdownPool(){
    //1、停止线程池接收新任务
    //2、等待一定时间,让现存的任务执行结束
    //3、取消当前运行的任务
    //4、如果当前线程也被中断的话,那么就再次关闭线程池,同时恢复中断状态

    1. try{<br /> pool.shutdown();<br /> if(!pool.awaitTermination(60,TimeUnit.SECONDS)){<br /> pool.shutdownNow();<br /> if(!pool.awaitTermination(60,TimeUnit.SECONDS)){<br /> System.out.println("Pool did not terminate");<br /> }<br /> }<br /> }catch(InterruptedException ie){<br /> pool.shutdownNow();<br /> Thread.currentThread().interrupt();<br /> }
    2. }<br /> private static boolean console_out = false;// 日志是否输出到控制台<br /> /*<br /> * yyyy-MM: 每个月更新一个log日志 yyyy-ww: 每个星期更新一个log日志 yyyy-MM-dd: 每天更新一个log日志<br /> * yyyy-MM-dd-a: 每天的午夜和正午更新一个log日志 yyyy-MM-dd-HH: 每小时更新一个log日志<br /> * yyyy-MM-dd-HH-mm: 每分钟更新一个log日志<br /> */<br /> private static String update_hz = "yyyy-MM-dd";// 更新日志的频率,每月更新一次<br /> private static long max_log_size = 1024 * 1024 * 5;// 单个日志文件最大大小 5M<br /> //private static long max_log_size = 1024 * 2;// 单个日志文件最大大小 5M
    3. public static String getFinalPath(String rootpath,String secondpath){<br /> rootpath = StringUtils.trim(rootpath);<br /> secondpath = StringUtils.trim(secondpath);<br /> if(StringUtil.isEmpty(secondpath)) return rootpath;<br /> if(secondpath.startsWith("/")){<br /> secondpath = secondpath.substring(1);<br /> }<br /> if(!secondpath.endsWith("/")){<br /> secondpath += "/";<br /> }<br /> return rootpath + secondpath;<br /> }<br /> public static String getFinalName(String rootname,String secondname){<br /> rootname = StringUtils.trim(rootname);<br /> secondname = StringUtils.trim(secondname);<br /> if(StringUtil.isEmpty(secondname)) return rootname;<br /> return rootname + "-" + secondname;<br /> }<br /> /**<br /> * @author: qzf<br /> * @date: 2022/5/7 11:42<br /> * @describe:<br /> * @param: log_secondpath 在根路径下面建立的二级路径,String log_secondname 在主文件名后面建立的二级文件名<br /> * @return:<br /> */<br /> public static void log(String msg,String log_secondpath,String log_secondname) {<br /> runWrite(msg, getFinalPath(log_rootpath,log_secondpath), getFinalName(log_rootname,log_secondname));<br /> }<br /> public static void log(String msg) {<br /> runWrite(msg, getFinalPath(log_rootpath,""), getFinalName(log_rootname,""));<br /> }<br /> public static void debug(String msg) {<br /> runWrite(msg, getFinalPath(log_rootpath,""), getFinalName(log_rootname,"") + "_debug");<br /> }<br /> public static void debug(String msg,String log_secondpath,String log_secondname) {<br /> runWrite(msg, getFinalPath(log_rootpath,log_secondpath), getFinalName(log_rootname,log_secondname) + "_debug");<br /> }
    4. public static void info(String msg) {<br /> runWrite(msg, getFinalPath(log_rootpath,""), getFinalName(log_rootname,"") + "_info");<br /> }<br /> public static void info(String msg,String log_secondpath,String log_secondname) {<br /> runWrite(msg, getFinalPath(log_rootpath,log_secondpath), getFinalName(log_rootname,log_secondname) + "_info");<br /> }
    5. public static void error(String msg) {<br /> runWrite(msg, getFinalPath(log_rootpath,""), getFinalName(log_rootname,"") + "_error");<br /> }<br /> public static void error(String msg,String log_secondpath,String log_secondname) {<br /> runWrite(msg, getFinalPath(log_rootpath,log_secondpath), getFinalName(log_rootname,log_secondname) + "_error");<br /> }
    6. /*public static void exception(Exception e) {<br /> String errorMessage = e.getMessage() + "";<br /> StackTraceElement[] eArray = e.getCause().getStackTrace();<br /> for (int i = 0; i < eArray.length; i++) {<br /> String className = e.getCause().getStackTrace()[i].getClassName();<br /> String MethodName = e.getCause().getStackTrace()[i].getMethodName();<br /> int LineNumber = e.getCause().getStackTrace()[i].getLineNumber();<br /> errorMessage = errorMessage + "\n\t---" + className + "." + MethodName + ",\tline:" + LineNumber;<br /> }<br /> logResult(errorMessage, log_rootpath, log_rootname + "_exception");<br /> }*/
    7. /**<br /> * 日志根目录<br /> *<br /> * @return<br /> */<br /> /*public static String getBasePath() {<br /> *//*String s = Thread.currentThread().getContextClassLoader().getResource("").getPath();<br /> s = s.substring(0, s.indexOf("WEB-INF")) + "log" + File.separator;*//*<br /> String s = ApplicationConfig.mylogPath;<br /> return s;<br /> }*/
    8. /**<br /> * 写日志<br /> *<br /> * @param sWord<br /> * 要写入日志里的文本内容<br /> */
    9. public static void logResult(String sWord, String logPath,String logName) {<br /> FileWriter writer = null;<br /> try {<br /> File dir = new File(logPath);<br /> if (!dir.exists()) {<br /> dir.mkdirs();<br /> }<br /> String dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());<br /> File f = new File(logPath + logName + "-" + new SimpleDateFormat(update_hz).format(new Date()) + "-log.txt");<br /> if (!f.exists()) {<br /> f.createNewFile();<br /> sWord = "日志开始\r\n"+"[" + dt + "] " + sWord ;
    10. } else {<br /> long logSize = f.length();<br /> // 文件大小超过xxM,备份<br /> if (logSize >= max_log_size) {<br /> String backLogName = logPath + logName<br /> + new SimpleDateFormat("-yyyy-MM-dd-HHmmssSSS").format(new Date()) + "-log.txt";<br /> f.renameTo(new File(backLogName));<br /> }<br /> }<br /> writer = new FileWriter(f, true);<br /> writer.write("[" + dt + "] " + sWord + "\r\n");<br /> if (console_out) {<br /> System.out.println("[" + dt + "]\t" + sWord);<br /> }<br /> } catch (Exception e) {<br /> System.out.println("记录日志异常:" + e.toString());<br /> e.printStackTrace();<br /> } finally {<br /> if (writer != null) {<br /> try {<br /> writer.close();<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }<br /> }<br /> }<br /> }
    11. public static void runWrite(final String sWord,final String logPath, final String logName) {<br /> /*new Thread() {<br /> public void run() {<br /> logResult(sWord, logPath, logName);<br /> }<br /> }.start();;*/<br /> //线程池管理<br /> try {<br /> pool.execute(new Runnable() {<br /> @Override<br /> public void run() {<br /> logResult(sWord, logPath, logName);<br /> }<br /> });<br /> }<br /> catch (Exception e){<br /> e.printStackTrace();<br /> log.error("MyLogUtil记录日志出错"+e.getMessage());<br /> }<br /> }
    12. public static void main(String[] args) {<br /> for (int i = 0; i <1000; i++) {<br /> //log(""+i,"2022-04","Recv");<br /> log(""+i);<br /> }<br /> }

    }