guohongjin
2024-05-15 5b7639f0bd9e056738ec15100ed0532e965c6cd5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
 * Copyright [2020-2030] [https://www.stylefeng.cn]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Guns源码头部的版权声明。
 * 3.请保留源码和相关描述文件的项目出处,作者声明等。
 * 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
 * 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
 * 6.若您的项目无法满足以上几点,可申请商业授权
 */
package cn.stylefeng.roses.kernel.log.db;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.log.api.LogRecordApi;
import cn.stylefeng.roses.kernel.log.api.constants.LogConstants;
import cn.stylefeng.roses.kernel.log.api.pojo.record.LogRecordDTO;
import cn.stylefeng.roses.kernel.log.api.threadpool.LogManagerThreadPool;
import cn.stylefeng.roses.kernel.log.db.entity.SysLog;
import cn.stylefeng.roses.kernel.log.db.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
 
/**
 * 数据库存储方式的日志记录器
 *
 * @author luojie
 * @date 2020/11/2 15:50
 */
@Slf4j
public class DbLogRecordServiceImpl implements LogRecordApi {
 
    /**
     * 日志记录 service接口
     */
    private final SysLogService sysLogService;
 
    /**
     * 异步记录日志用的线程池
     */
    private final LogManagerThreadPool logManagerThreadPool;
 
    /**
     * 日志刷新管理器
     */
    private final LogRefreshManager logRefreshManager;
 
 
    public DbLogRecordServiceImpl(LogManagerThreadPool logManagerThreadPool, SysLogService sysLogService) {
        this.logManagerThreadPool = logManagerThreadPool;
        this.sysLogService = sysLogService;
        this.logRefreshManager = new LogRefreshManager();
        this.logRefreshManager.start();
    }
 
    public DbLogRecordServiceImpl(LogManagerThreadPool logManagerThreadPool, SysLogService sysLogService, long sleepTime, int maxCount) {
        this.logManagerThreadPool = logManagerThreadPool;
        this.sysLogService = sysLogService;
        this.logRefreshManager = new LogRefreshManager(sleepTime, maxCount);
        this.logRefreshManager.start();
    }
 
    @Override
    public void add(LogRecordDTO logRecordDTO) {
        if (logRecordDTO == null) {
            return;
        }
 
        // 输出日志
        addBatch(CollectionUtil.list(false, logRecordDTO));
    }
 
    @Override
    public void addBatch(List<LogRecordDTO> logRecords) {
 
        if (ObjectUtil.isEmpty(logRecords)) {
            return;
        }
 
        List<SysLog> sysLogList = logRecords.stream().map(logRecordDTO -> {
            SysLog sysLog = new SysLog();
            // 复制logRecordDTO对象属性到sysLog
            BeanUtil.copyProperties(logRecordDTO, sysLog);
 
            // 日志名称为空的话则获取默认日志名称
            if (StrUtil.isEmpty(sysLog.getLogName())) {
                sysLog.setLogName(LogConstants.LOG_DEFAULT_NAME);
            }
 
            // 服务名称为空的话则获取默认服务名称
            if (StrUtil.isEmpty(sysLog.getAppName())) {
                sysLog.setAppName(LogConstants.LOG_DEFAULT_APP_NAME);
            }
 
            return sysLog;
        }).collect(Collectors.toList());
 
        // 插入到数据库
        sysLogService.saveBatch(sysLogList);
    }
 
    @Override
    public void addAsync(LogRecordDTO logRecordDTO) {
        logManagerThreadPool.executeLog(new TimerTask() {
            @Override
            public void run() {
                logRefreshManager.putLog(logRecordDTO);
            }
        });
    }
 
    /**
     * 日志刷新管理器
     * <p>
     * 该类暂存所有将要写出到磁盘的日志,使用内存缓冲区减少对磁盘IO的操作
     * <p>
     * 该类维护一个最大日志数和一个刷新日志间隔,满足任意一个条件即可触发从内存写出日志到磁盘的操作
     *
     * @author majianguo
     * @date 2020/10/31 15:05
     */
    class LogRefreshManager extends Thread {
 
        /**
         * 刷新日志间隔(默认3秒),单位毫秒
         */
        private final long sleepTime;
 
        /**
         * 满足多少条就强制刷新一次(默认300条),该值只是一个大约值,实际记录并不会一定等于该值(可能会大于该值,不可能小于该值)
         */
        private final int maxCount;
 
        /**
         * 刷新数据时间标志,每次刷新都记录当前的时间戳,方便定时刷新准确判断上次刷新和本次刷新的时间间隔
         */
        private final AtomicLong refreshMark = new AtomicLong();
 
        public LogRefreshManager() {
            this.sleepTime = 3000;
            this.maxCount = 300;
        }
 
        public LogRefreshManager(long sleepTime) {
            this.sleepTime = sleepTime;
            this.maxCount = 300;
        }
 
        public LogRefreshManager(int maxCount) {
            this.sleepTime = 3000;
            this.maxCount = maxCount;
        }
 
        public LogRefreshManager(long sleepTime, int maxCount) {
            this.sleepTime = sleepTime;
            this.maxCount = maxCount;
        }
 
        /**
         * 未处理日志的消息队列
         */
        private final Queue<LogRecordDTO> queue = new ConcurrentLinkedQueue<>();
 
        /**
         * 消息总数,队列的size方法会遍历一遍队列,所以自己维护大小
         */
        public AtomicInteger count = new AtomicInteger(0);
 
        /**
         * 往队列内新增一条日志数据
         *
         * @param logRecordDTO 日志对象
         * @author majianguo
         * @date 2020/10/31 14:59
         */
        public void putLog(LogRecordDTO logRecordDTO) {
 
            int queueDataCount = count.get();
 
            // 如果是第一条消息,刷新一次refreshMark
            if (queueDataCount == 0) {
                refreshMark.getAndSet(System.currentTimeMillis());
            }
 
            // 如果后续写入磁盘的操作有异常(磁盘满了),为了防止日志刷不出去导致OOM,内存中最大只保留maxCount数一倍的日志,后续日志将丢弃
            if (queueDataCount >= (maxCount * 2)) {
                return;
            }
 
            queue.offer(logRecordDTO);
            count.incrementAndGet();
        }
 
        /**
         * 刷新日志到磁盘的操作
         *
         * @author majianguo
         * @date 2020/10/31 15:48
         */
        private void refresh() {
 
            // 让睡眠线程本次不要再调本方法,睡眠至下次看refreshMark的值再决定要不要调用本方法
            refreshMark.getAndSet(System.currentTimeMillis());
 
            // 获取总数
            int num = count.getAndSet(0);
 
            // 再队列中读取num条数据,放入list
            List<LogRecordDTO> cacheAll = new ArrayList<>(num);
            for (int i = 0; i < num; i++) {
                LogRecordDTO item = queue.poll();
                if (null == item) {
                    break;
                }
                cacheAll.add(item);
            }
 
            // 调用方法刷新到磁盘
            addBatch(cacheAll);
        }
 
        /**
         * 日志数据定时执行器
         * <p>
         * 用于定时检测日志数据是否可以写入数据
         *
         * @author majianguo
         * @date 2020/10/31 15:57
         */
        private void timing() {
            long currentTimeMillis = System.currentTimeMillis();
 
            // 如果是激活状态,且消息数大于零,且符合上次调用refresh方法到目前时间的间隔,那就调用一次refresh方法
            if ((refreshMark.get() + sleepTime) <= currentTimeMillis && count.get() > 0) {
                refresh();
            }
        }
 
        /**
         * 日志数据监听器
         * <p>
         * 用于监听日志消息队列,达到设定的数就开始执行刷入硬盘的操作
         *
         * @author majianguo
         * @date 2020/11/2 9:32
         */
        private void listener() {
            // 判断如果队列里面的数据大于等于设定的最大消息数,就调用refresh方法刷新一次数据
            if (count.get() >= maxCount) {
                refresh();
            }
        }
 
        @Override
        @SuppressWarnings("InfiniteLoopStatement")
        public void run() {
            try {
                for (; ; ) {
                    // 消息监听器
                    listener();
                    // 定时任务监听器
                    timing();
                    TimeUnit.MILLISECONDS.sleep(10);
                }
            } catch (InterruptedException e) {
 
                if (log.isDebugEnabled()) {
                    e.printStackTrace();
                }
                log.error(e.getMessage());
            }
        }
    }
 
}