Java web

36 日志系统

2020-08-05  本文已影响0人  滔滔逐浪

package com.taotao.async_log.utils;

import java.util.concurrent.ArrayBlockingQueue;

/**
 *@author tom
 *Date  2020/8/3 0003 9:24
 *
 */
public class LogBlockingQueue {
    private static int maxCapacity = 256;
    private static ArrayBlockingQueue<String> logBlockingQueue = new ArrayBlockingQueue<String>(maxCapacity);

    /**
     * 像队列里存放日志内容
     * 业务线程
     * @param log
     */
    public  static boolean addLog(String log) {
        return logBlockingQueue.offer(log);

    }

    /**
     * 像队列取出日志内
     * 日志线程
     * * @return
     */
    public static String getLog() {
        return  logBlockingQueue.poll();
    }

}



package com.taotao.async_log.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 异步写日志文件
 */
public class LogException {
    private static final String path = "d://data/aa.log";

    public static void writeErrorMsg(String content) {
        writeErrorMsg(path, content);
    }


    /**
     * @param path
     * @throws IOException
     * @将错误信息输入到txt中
     */
    public static void writeErrorMsg(String path, String content) {

        File F = new File(path);
        //如果文件不存在,就动态创建文件
        if (!F.exists()) {
            try {
                F.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileWriter fw = null;
        String writeDate = "时间:" + getNowDate() + "---" + "error:" + content;
        try {
            //设置为:True,表示写入的时候追加数据
            fw = new FileWriter(F, true);
            //回车并换行
            fw.write(writeDate + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * @return
     * @获取系统当前时间
     */
    public static String getNowDate() {

        Calendar D = Calendar.getInstance();
        int year = 0;
        int moth = 0;
        int day = 0;
        year = D.get(Calendar.YEAR);
        moth = D.get(Calendar.MONTH) + 1;
        day = D.get(Calendar.DAY_OF_MONTH);
        String nowDate = String.valueOf(year) + "-" + String.valueOf(moth) + "-" + String.valueOf(day);
        return nowDate;
    }

    public static void main(String[] args) {
        writeErrorMsg("mayikt");
    }

}


package com.taotao.async_log.utils;

import ch.qos.logback.classic.AsyncAppender;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName StartListener
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
@Slf4j
@Component
public class StartListener implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("当前项目启动成功");
        start();
    }

    public void start() {
        Worker worker = new Worker();
        //单独开启一个线程异步写日志
        worker.start();
    }

    class Worker extends Thread {
        @Override
        public void run() {
            for (; ; ) {
                String mtLog = LogBlockingQueue.getLog();
                if (!StringUtils.isEmpty(mtLog)) {
                    //将日志内容写入到硬盘中
                    LogException.writeErrorMsg(mtLog);
                    log.info("采用日志队列异步写入日志:{}{}", mtLog);
                }
            }

        }
    }

}

package com.taotao.async_log.controller;

import com.taotao.async_log.utils.LogBlockingQueue;
import com.taotao.async_log.utils.LogException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *@author tom
 *Date  2020/8/3 0003 9:23
 *
 */
@RestController
@Slf4j
public class PayController {
    @RequestMapping("/topay")
    public  String toPay(String payId,String payMoney){
        //记录日志到硬盘
        String payLog=System.currentTimeMillis()+","+payId+","+payMoney;
       boolean result=LogBlockingQueue.addLog(payLog);
       if(!result) {
           //同步写日志
           //如果队列满了,用户线程自己写日志
           LogException.writeErrorMsg(payLog);
       }
        return  "success";

    }

}


pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.taotao</groupId>
    <artifactId>async_log</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>async_log</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
            <version>2.0.0.RELEASE</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


上一篇 下一篇

猜你喜欢

热点阅读