用 SpringBoot 构建轻量级日志查看器,省时又省力

SpringBoot接入轻量级分布式日志框架(GrayLog) 00、为什么需要分布式日志组件? 在文章正式开始之前,我分享下我以前负责过的一个系统,它的架构如下: 每次当我查问题的时候,我可能能把问题初步定位在逻辑层,但为了能给业务方交代,我需要给证据业务方看(日志信息就是铁证)。 一个请求肯定是被这8台机器内的某一台处理,但具体是哪一台,我不知道。所以,我需要上每台机器上grep一把日志,然后才能找出对应的日志证明我的分析。 有的时候,可能接入层也需要一起参与进去,就排查一个问题,人都傻了了(翻看日志的时间占用了太久了)。 后来啊,... 阅读详情

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入「芋道快速开发平台」知识星球。下面是星球提供的部分资料: 

👉这是一个或许对你有用的开源项目

国产Star破10w的开源项目,前端包括管理后台、微信小程序,后端支持单体、微服务架构

RBAC权限、数据权限、SaaS多租户、商城、支付、工作流、大屏报表、ERP、CRM、AI大模型、IoT物联网等功能:

  • 多模块:https://gitee.com/zhijiantianya/ruoyi-vue-pro

  • 微服务:https://gitee.com/zhijiantianya/yudao-cloud

  • 视频教程:https://doc.iocoder.cn

【国内首批】支持 JDK17/21+SpringBoot3、JDK8/11+Spring Boot2双版本 

来源:风象南


生产环境出问题时,你还在用 tail -f 查日志吗?还在为了下载几个G的日志文件而苦恼吗?本文将手把手教你实现一个轻量级的日志管理系统,让日志查询变得简单而高效。

前言:为什么要自建日志查询系统?

在实际项目中,我们经常遇到这样的场景:

  • 生产环境出现问题,需要快速定位错误日志

  • 日志文件太大,下载耗时且占用带宽

  • 需要根据时间、关键字、日志级别等条件筛选日志

  • 多人协作时,都需要登录服务器查看日志

虽然有 ELK、Splunk 等成熟方案,但对于中小型项目来说,部署成本高、资源消耗大。今天我们用 Spring Boot + 纯前端技术栈,打造一个轻量级、开箱即用的日志管理系统。

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro

  • 视频教程:https://doc.iocoder.cn/video/

系统设计

整体架构
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   前端界面      │    │   Spring Boot   │    │   日志文件      │
│  (HTML+JS)     │◄──►│     后端        │◄──►│   (logback)     │
│                │    │                 │    │                 │
│ • 日志查询      │    │ • 文件读取      │    │ • app.log       │
│ • 条件筛选      │    │ • 内容解析      │    │ • error.log     │
│ • 在线预览      │    │ • 分页处理      │    │ • access.log    │
│ • 文件下载      │    │ • 下载服务      │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘
核心功能模块
  1. 日志文件管理: 扫描、列举日志文件

  2. 内容解析: 按行读取、正则匹配、分页处理

  3. 条件筛选: 时间范围、关键字、日志级别

  4. 在线预览: 实时显示、语法高亮

  5. 文件下载: 支持原文件和筛选结果下载

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud

  • 视频教程:https://doc.iocoder.cn/video/

后端实现

1. 项目结构
src/main/java/com/example/logviewer/
├── LogViewerApplication.java
├── config/
│   └── LogConfig.java
├── controller/
│   └── LogController.java
├── service/
│   └── LogService.java
├── dto/
│   ├── LogQueryRequest.java
│   └── LogQueryResponse.java
└── util/
    └── LogParser.java
2. 核心依赖 (pom.xml)
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.11.0</version>
    </dependency>
</dependencies>
3. 配置类
@Configuration
@ConfigurationProperties(prefix = "log.viewer")
@Data
publicclass LogConfig {
    
    /**
     * 日志文件根目录
     */
    private String logPath = "./logs";
    
    /**
     * 允许访问的日志文件扩展名
     */
    private List<String> allowedExtensions = Arrays.asList(".log", ".txt");
    
    /**
     * 单次查询最大行数
     */
    privateint maxLines = 1000;
    
    /**
     * 文件最大大小(MB)
     */
    privatelong maxFileSize = 100;
    
    /**
     * 是否启用安全检查
     */
    privateboolean enableSecurity = true;
}
4. 数据传输对象
@Data
publicclass LogQueryRequest {
    
    @NotBlank(message = "文件名不能为空")
    private String fileName;
    
    /**
     * 页码,从1开始
     */
    @Min(value = 1, message = "页码必须大于0")
    privateint page = 1;
    
    /**
     * 每页行数
     */
    @Min(value = 1, message = "每页行数必须大于0")
    @Max(value = 1000, message = "每页行数不能超过1000")
    privateint pageSize = 100;
    
    /**
     * 关键字搜索
     */
    private String keyword;
    
    /**
     * 日志级别过滤
     */
    private String level;
    
    /**
     * 开始时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime startTime;
    
    /**
     * 结束时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime endTime;
    
    /**
     * 是否倒序
     */
    privateboolean reverse = true;
}

@Data
publicclass LogQueryResponse {
    
    /**
     * 日志内容列表
     */
    private List<String> lines;
    
    /**
     * 总行数
     */
    privatelong totalLines;
    
    /**
     * 当前页码
     */
    privateint currentPage;
    
    /**
     * 总页数
     */
    privateint totalPages;
    
    /**
     * 文件大小(字节)
     */
    privatelong fileSize;
    
    /**
     * 最后修改时间
     */
    private LocalDateTime lastModified;
}
5. 日志解析工具类
@Component
publicclass LogParser {
    
    privatestaticfinal Pattern LOG_PATTERN = Pattern.compile(
        "(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\.\d{3})\s+(\w+)\s+(.*)")
    );
    
    /**
     * 解析日志行,提取时间和级别
     */
    public LogLineInfo parseLine(String line) {
        Matcher matcher = LOG_PATTERN.matcher(line);
        if (matcher.find()) {
            String timestamp = matcher.group(1);
            String level = matcher.group(2);
            String content = matcher.group(3);
            
            LocalDateTime dateTime = parseTimestamp(timestamp);
            returnnew LogLineInfo(dateTime, level, content, line);
        }
        
        // 如果不匹配标准格式,返回原始行
        returnnew LogLineInfo(null, null, line, line);
    }
    
    private LocalDateTime parseTimestamp(String timestamp) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            return LocalDateTime.parse(timestamp, formatter);
        } catch (Exception e) {
            returnnull;
        }
    }
    
    @Data
    @AllArgsConstructor
    publicstaticclass LogLineInfo {
        private LocalDateTime timestamp;
        private String level;
        private String content;
        private String originalLine;
        
        public boolean matchesFilter(LogQueryRequest request) {
            // 时间范围过滤
            if (timestamp != null) {
                if (request.getStartTime() != null && timestamp.isBefore(request.getStartTime())) {
                    returnfalse;
                }
                if (request.getEndTime() != null && timestamp.isAfter(request.getEndTime())) {
                    returnfalse;
                }
            }
            
            // 日志级别过滤
            if (StringUtils.isNotBlank(request.getLevel()) && 
                !StringUtils.equalsIgnoreCase(level, request.getLevel())) {
                returnfalse;
            }
            
            // 关键字过滤
            if (StringUtils.isNotBlank(request.getKeyword()) && 
                !StringUtils.containsIgnoreCase(originalLine, request.getKeyword())) {
                returnfalse;
            }
            
            returntrue;
        }
    }
}
6. 核心服务类
@Service
@Slf4j
publicclass LogService {
    
    @Autowired
    private LogConfig logConfig;
    
    @Autowired
    private LogParser logParser;
    
    /**
     * 获取日志文件列表
     */
    public List<Map<String, Object>> getLogFiles() {
        File logDir = new File(logConfig.getLogPath());
        if (!logDir.exists() || !logDir.isDirectory()) {
            return Collections.emptyList();
        }
        
        return Arrays.stream(logDir.listFiles())
            .filter(this::isValidLogFile)
            .map(this::fileToMap)
            .sorted((a, b) -> ((Long)b.get("lastModified")).compareTo((Long)a.get("lastModified")))
            .collect(Collectors.toList());
    }
    
    /**
     * 查询日志内容
     */
    public LogQueryResponse queryLogs(LogQueryRequest request) {
        File logFile = getLogFile(request.getFileName());
        validateFile(logFile);
        
        try {
            List<String> allLines = FileUtils.readLines(logFile, StandardCharsets.UTF_8);
            
            // 过滤日志行
            List<String> filteredLines = filterLines(allLines, request);
            
            // 倒序处理
            if (request.isReverse()) {
                Collections.reverse(filteredLines);
            }
            
            // 分页处理
            int totalLines = filteredLines.size();
            int totalPages = (int) Math.ceil((double) totalLines / request.getPageSize());
            int startIndex = (request.getPage() - 1) * request.getPageSize();
            int endIndex = Math.min(startIndex + request.getPageSize(), totalLines);
            
            List<String> pageLines = filteredLines.subList(startIndex, endIndex);
            
            LogQueryResponse response = new LogQueryResponse();
            response.setLines(pageLines);
            response.setTotalLines(totalLines);
            response.setCurrentPage(request.getPage());
            response.setTotalPages(totalPages);
            response.setFileSize(logFile.length());
            response.setLastModified(
                LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(logFile.lastModified()), 
                    ZoneId.systemDefault()
                )
            );
            
            return response;
            
        } catch (IOException e) {
            log.error("读取日志文件失败: {}", logFile.getAbsolutePath(), e);
            thrownew RuntimeException("读取日志文件失败", e);
        }
    }
    
    /**
     * 下载日志文件
     */
    public void downloadLog(String fileName, LogQueryRequest request, HttpServletResponse response) {
        File logFile = getLogFile(fileName);
        validateFile(logFile);
        
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", 
                "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            
            if (hasFilter(request)) {
                // 下载过滤后的内容
                List<String> allLines = FileUtils.readLines(logFile, StandardCharsets.UTF_8);
                List<String> filteredLines = filterLines(allLines, request);
                
                try (PrintWriter writer = response.getWriter()) {
                    for (String line : filteredLines) {
                        writer.println(line);
                    }
                }
            } else {
                // 下载原文件
                response.setContentLengthLong(logFile.length());
                try (InputStream inputStream = new FileInputStream(logFile);
                     OutputStream outputStream = response.getOutputStream()) {
                    IOUtils.copy(inputStream, outputStream);
                }
            }
            
        } catch (IOException e) {
            log.error("下载日志文件失败: {}", logFile.getAbsolutePath(), e);
            thrownew RuntimeException("下载日志文件失败", e);
        }
    }
    
    private List<String> filterLines(List<String> lines, LogQueryRequest request) {
        if (!hasFilter(request)) {
            return lines;
        }
        
        return lines.stream()
            .map(logParser::parseLine)
            .filter(lineInfo -> lineInfo.matchesFilter(request))
            .map(LogParser.LogLineInfo::getOriginalLine)
            .collect(Collectors.toList());
    }
    
    private boolean hasFilter(LogQueryRequest request) {
        return StringUtils.isNotBlank(request.getKeyword()) ||
               StringUtils.isNotBlank(request.getLevel()) ||
               request.getStartTime() != null ||
               request.getEndTime() != null;
    }
    
    private File getLogFile(String fileName) {
        // 安全检查:防止路径遍历攻击
        if (logConfig.isEnableSecurity()) {
            if (fileName.contains("..") || fileName.contains("/") || fileName.contains(".")) {
                thrownew IllegalArgumentException("非法的文件名");
            }
        }
        
        returnnew File(logConfig.getLogPath(), fileName);
    }
    
    private void validateFile(File file) {
        if (!file.exists()) {
            thrownew IllegalArgumentException("文件不存在");
        }
        
        if (!file.isFile()) {
            thrownew IllegalArgumentException("不是有效的文件");
        }
        
        if (!isValidLogFile(file)) {
            thrownew IllegalArgumentException("不支持的文件类型");
        }
        
        long fileSizeMB = file.length() / (1024 * 1024);
        if (fileSizeMB > logConfig.getMaxFileSize()) {
            thrownew IllegalArgumentException(
                String.format("文件过大,超过限制 %dMB", logConfig.getMaxFileSize())
            );
        }
    }
    
    private boolean isValidLogFile(File file) {
        String fileName = file.getName().toLowerCase();
        return logConfig.getAllowedExtensions().stream()
            .anyMatch(fileName::endsWith);
    }
    
    private Map<String, Object> fileToMap(File file) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", file.getName());
        map.put("size", file.length());
        map.put("lastModified", file.lastModified());
        map.put("readable", file.canRead());
        return map;
    }
}
7. 日志文件实时监控
/**
 * 日志实时监控服务
 * 监控日志文件变化,实时推送新增日志内容
 */
@Slf4j
@Service
publicclass LogMonitorService implements InitializingBean, DisposableBean {

    @Autowired
    private LogConfig logConfig;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private LogParser logParser;

    // 文件监控服务
    private WatchService watchService;
    
    // 线程池
    private ScheduledExecutorService executorService;
    
    // 存储每个文件的读取位置
    privatefinal Map<String, Long> filePositions = new ConcurrentHashMap<>();
    
    // 当前监控的文件
    privatevolatile String currentMonitorFile;
    
    // 监控状态
    privatevolatileboolean monitoring = false;

    @Override
    public void afterPropertiesSet() {
        try {
            watchService = FileSystems.getDefault().newWatchService();
            executorService = Executors.newScheduledThreadPool(2);
            
            // 注册日志目录监控
            Path logPath = Paths.get(logConfig.getLogPath());
            if (Files.exists(logPath)) {
                logPath.register(watchService, 
                    StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_CREATE);
                
                // 启动文件监控线程
                executorService.submit(this::watchFiles);
                log.info("日志文件监控服务已启动,监控目录: {}", logPath);
            }
        } catch (Exception e) {
            log.error("初始化日志监控服务失败", e);
        }
    }

    @Override
    public void destroy() {
        monitoring = false;
        if (watchService != null) {
            try {
                watchService.close();
            } catch (Exception e) {
                log.error("关闭文件监控服务失败", e);
            }
        }
        if (executorService != null) {
            executorService.shutdown();
        }
        log.info("日志监控服务已关闭");
    }

    /**
     * 开始监控指定文件
     * @param fileName 文件名
     */
    public void startMonitoring(String fileName) {
        if (fileName == null || fileName.trim().isEmpty()) {
            return;
        }
        
        currentMonitorFile = fileName;
        monitoring = true;
        
        // 初始化文件读取位置
        File file = new File(logConfig.getLogPath(), fileName);
        if (file.exists()) {
            filePositions.put(fileName, file.length());
        }
        
        log.info("开始监控日志文件: {}", fileName);
        
        // 发送监控开始消息
        messagingTemplate.convertAndSend("/topic/log-monitor", 
            Map.of("type", "monitor_started", "fileName", fileName));
    }

    /**
     * 停止监控
     */
    public void stopMonitoring() {
        monitoring = false;
        currentMonitorFile = null;
        
        log.info("停止日志文件监控");
        
        // 发送监控停止消息
        messagingTemplate.convertAndSend("/topic/log-monitor", 
            Map.of("type", "monitor_stopped"));
    }

    /**
     * 文件监控线程
     */
    private void watchFiles() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                WatchKey key = watchService.take();
                
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    
                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }
                    
                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();
                    
                    if (monitoring && currentMonitorFile != null && 
                        fileName.toString().equals(currentMonitorFile)) {
                        
                        // 延迟处理,避免文件正在写入
                        executorService.schedule(() -> processFileChange(currentMonitorFile), 
                            100, TimeUnit.MILLISECONDS);
                    }
                }
                
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            } catch (Exception e) {
                log.error("文件监控异常", e);
            }
        }
    }

    /**
     * 处理文件变化
     * @param fileName 文件名
     */
    private void processFileChange(String fileName) {
        try {
            File file = new File(logConfig.getLogPath(), fileName);
            if (!file.exists()) {
                return;
            }
            
            long currentLength = file.length();
            long lastPosition = filePositions.getOrDefault(fileName, 0L);
            
            // 如果文件被截断(如日志轮转),重置位置
            if (currentLength < lastPosition) {
                lastPosition = 0L;
            }
            
            // 如果有新内容
            if (currentLength > lastPosition) {
                String newContent = readNewContent(file, lastPosition, currentLength);
                if (newContent != null && !newContent.trim().isEmpty()) {
                    // 解析新日志行
                    String[] lines = newContent.split("\n");
                    for (String line : lines) {
                        if (!line.trim().isEmpty()) {
                            sendLogLine(fileName, line);
                        }
                    }
                }
                
                // 更新文件位置
                filePositions.put(fileName, currentLength);
            }
        } catch (Exception e) {
            log.error("处理文件变化失败: {}", fileName, e);
        }
    }

    /**
     * 读取文件新增内容
     * @param file 文件
     * @param startPosition 开始位置
     * @param endPosition 结束位置
     * @return 新增内容
     */
    private String readNewContent(File file, long startPosition, long endPosition) {
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            raf.seek(startPosition);
            
            long length = endPosition - startPosition;
            if (length > 1024 * 1024) { // 限制单次读取大小为1MB
                length = 1024 * 1024;
            }
            
            byte[] buffer = newbyte[(int) length];
            int bytesRead = raf.read(buffer);
            
            if (bytesRead > 0) {
                returnnew String(buffer, 0, bytesRead, "UTF-8");
            }
        } catch (Exception e) {
            log.error("读取文件内容失败: {}", file.getName(), e);
        }
        returnnull;
    }

    /**
     * 发送日志行到WebSocket客户端
     * @param fileName 文件名
     * @param logLine 日志行
     */
    private void sendLogLine(String fileName, String logLine) {
        try {
            // 解析日志行
            LogParser.LogLineInfo lineInfo = logParser.parseLine(logLine);
            
            // 构建消息
            Map<String, Object> message = Map.of(
                "type", "new_log_line",
                "fileName", fileName,
                "content", logLine,
                "timestamp", lineInfo.getTimestamp() != null ? lineInfo.getTimestamp().toString() : "",
                "level", lineInfo.getLevel() != null ? lineInfo.getLevel() : "",
                "rawContent", lineInfo.getContent() != null ? lineInfo.getContent() : logLine
            );
            
            // 发送到WebSocket客户端
            messagingTemplate.convertAndSend("/topic/log-monitor", message);
            
        } catch (Exception e) {
            log.error("发送日志行失败", e);
        }
    }

    /**
     * 获取当前监控状态
     * @return 监控状态信息
     */
    public Map<String, Object> getMonitorStatus() {
        return Map.of(
            "monitoring", monitoring,
            "currentFile", currentMonitorFile != null ? currentMonitorFile : "",
            "monitoredFiles", filePositions.size()
        );
    }
}
8. 控制器
@RestController
@RequestMapping("/api/logs")
@Slf4j
publicclass LogController {
    
    @Autowired
    private LogService logService;
    
    /**
     * 获取日志文件列表
     */
    @GetMapping("/files")
    public ResponseEntity<List<Map<String, Object>>> getLogFiles() {
        try {
            List<Map<String, Object>> files = logService.getLogFiles();
            return ResponseEntity.ok(files);
        } catch (Exception e) {
            log.error("获取日志文件列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 查询日志内容
     */
    @PostMapping("/query")
    public ResponseEntity<LogQueryResponse> queryLogs(@Valid @RequestBody LogQueryRequest request) {
        try {
            LogQueryResponse response = logService.queryLogs(request);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            log.warn("查询参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("查询日志失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 下载日志文件
     */
    @GetMapping("/download/{fileName}")
    public void downloadLog(
            @PathVariable String fileName,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String level,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            HttpServletResponse response) {
        
        try {
            LogQueryRequest request = new LogQueryRequest();
            request.setFileName(fileName);
            request.setKeyword(keyword);
            request.setLevel(level);
            request.setStartTime(startTime);
            request.setEndTime(endTime);
            
            logService.downloadLog(fileName, request, response);
            
        } catch (IllegalArgumentException e) {
            log.warn("下载参数错误: {}", e.getMessage());
            response.setStatus(HttpStatus.BAD_REQUEST.value());
        } catch (Exception e) {
            log.error("下载日志失败", e);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }
}

前端实现

1. HTML 结构 (static/index.html)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>日志查询系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .search-panel {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 02px10pxrgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .form-group {
            flex: 1;
            min-width: 200px;
        }
        
        .form-grouplabel {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
        }
        
        .form-groupinput,
        .form-groupselect {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .btn {
            padding: 10px20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a6fd8;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .result-panel {
            background: white;
            border-radius: 10px;
            box-shadow: 02px10pxrgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .result-header {
            background: #f8f9fa;
            padding: 15px20px;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .log-content {
            max-height: 600px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.4;
        }
        
        .log-line {
            padding: 5px15px;
            border-bottom: 1px solid #f0f0f0;
            white-space: pre-wrap;
            word-break: break-all;
        }
        
        .log-line:hover {
            background-color: #f8f9fa;
        }
        
        .log-line.error {
            background-color: #fff5f5;
            border-left: 3px solid #dc3545;
        }
        
        .log-line.warn {
            background-color: #fffbf0;
            border-left: 3px solid #ffc107;
        }
        
        .log-line.info {
            background-color: #f0f8ff;
            border-left: 3px solid #17a2b8;
        }
        
        .pagination {
            padding: 15px20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        
        .pagination-info {
            color: #666;
        }
        
        .pagination-controls {
            display: flex;
            gap: 10px;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin: 10px0;
        }
        
        .highlight {
            background-color: yellow;
            font-weight: bold;
        }
        
        @media (max-width:768px) {
            .form-row {
                flex-direction: column;
            }
            
            .result-header {
                flex-direction: column;
                gap: 10px;
            }
            
            .pagination {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📋 日志查询系统</h1>
            <p>轻量级日志在线查询、分析、下载工具</p>
        </div>
        
        <div class="search-panel">
            <div class="form-row">
                <div class="form-group">
                    <label for="fileSelect">选择日志文件</label>
                    <select id="fileSelect">
                        <option value="">请选择日志文件...</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="keyword">关键字搜索</label>
                    <input type="text" id="keyword" placeholder="输入搜索关键字...">
                </div>
                <div class="form-group">
                    <label for="level">日志级别</label>
                    <select id="level">
                        <option value="">全部级别</option>
                        <option value="ERROR">ERROR</option>
                        <option value="WARN">WARN</option>
                        <option value="INFO">INFO</option>
                        <option value="DEBUG">DEBUG</option>
                    </select>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="startTime">开始时间</label>
                    <input type="datetime-local" id="startTime">
                </div>
                <div class="form-group">
                    <label for="endTime">结束时间</label>
                    <input type="datetime-local" id="endTime">
                </div>
                <div class="form-group">
                    <label for="pageSize">每页行数</label>
                    <select id="pageSize">
                        <option value="50">50</option>
                        <option value="100" selected>100</option>
                        <option value="200">200</option>
                        <option value="500">500</option>
                    </select>
                </div>
            </div>
            
            <div class="form-row">
                <button class="btn btn-primary" onclick="searchLogs()">🔍 查询日志</button>
                <button class="btn btn-success" onclick="downloadLogs()">📥 下载日志</button>
                <label>
                    <input type="checkbox" id="reverse" checked> 倒序显示
                </label>
            </div>
        </div>
        
        <div class="result-panel" id="resultPanel" style="display: none;">
            <div class="result-header">
                <div class="result-info" id="resultInfo"></div>
                <div class="result-actions">
                    <button class="btn btn-primary" onclick="refreshLogs()">🔄 刷新</button>
                </div>
            </div>
            
            <div class="log-content" id="logContent"></div>
            
            <div class="pagination" id="pagination"></div>
        </div>
    </div>
    
    <script>
        // 全局变量
        let currentPage = 1;
        let totalPages = 1;
        let currentQuery = {};
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadLogFiles();
            
            // 绑定回车键搜索
            document.getElementById('keyword').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchLogs();
                }
            });
        });
        
        // 加载日志文件列表
        asyncfunction loadLogFiles() {
            try {
                const response = await fetch('/api/logs/files');
                const files = await response.json();
                
                const select = document.getElementById('fileSelect');
                select.innerHTML = '<option value="">请选择日志文件...</option>';
                
                files.forEach(file => {
                    const option = document.createElement('option');
                    option.value = file.name;
                    option.textContent = `${file.name} (${formatFileSize(file.size)}, ${formatDate(file.lastModified)})`;
                    select.appendChild(option);
                });
                
            } catch (error) {
                console.error('加载文件列表失败:', error);
                showError('加载文件列表失败,请检查服务器连接');
            }
        }
        
        // 搜索日志
        asyncfunction searchLogs(page = 1) {
            const fileName = document.getElementById('fileSelect').value;
            if (!fileName) {
                alert('请先选择日志文件');
                return;
            }
            
            const query = {
                fileName: fileName,
                page: page,
                pageSize: parseInt(document.getElementById('pageSize').value),
                keyword: document.getElementById('keyword').value,
                level: document.getElementById('level').value,
                startTime: document.getElementById('startTime').value,
                endTime: document.getElementById('endTime').value,
                reverse: document.getElementById('reverse').checked
            };
            
            // 保存当前查询条件
            currentQuery = query;
            currentPage = page;
            
            try {
                showLoading();
                
                const response = await fetch('/api/logs/query', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(query)
                });
                
                if (!response.ok) {
                    thrownewError(`HTTP ${response.status}`);
                }
                
                const result = await response.json();
                displayLogs(result);
                
            } catch (error) {
                console.error('查询日志失败:', error);
                showError('查询日志失败: ' + error.message);
            }
        }
        
        // 显示日志内容
        function displayLogs(result) {
            const resultPanel = document.getElementById('resultPanel');
            const resultInfo = document.getElementById('resultInfo');
            const logContent = document.getElementById('logContent');
            const pagination = document.getElementById('pagination');
            
            // 显示结果面板
            resultPanel.style.display = 'block';
            
            // 更新结果信息
            resultInfo.innerHTML = `
                📄 文件: ${currentQuery.fileName} | 
                📊 总计: ${result.totalLines} 行 | 
                📦 大小: ${formatFileSize(result.fileSize)} | 
                🕒 修改时间: ${formatDateTime(result.lastModified)}
            `;
            
            // 显示日志内容
            logContent.innerHTML = '';
            if (result.lines && result.lines.length > 0) {
                result.lines.forEach((line, index) => {
                    const lineDiv = document.createElement('div');
                    lineDiv.className = 'log-line ' + getLogLevel(line);
                    lineDiv.innerHTML = highlightKeyword(escapeHtml(line), currentQuery.keyword);
                    logContent.appendChild(lineDiv);
                });
            } else {
                logContent.innerHTML = '<div class="loading">没有找到匹配的日志记录</div>';
            }
            
            // 更新分页信息
            totalPages = result.totalPages;
            updatePagination(result);
        }
        
        // 更新分页控件
        function updatePagination(result) {
            const pagination = document.getElementById('pagination');
            
            const paginationInfo = `第 ${result.currentPage} 页,共 ${result.totalPages} 页`;
            
            const prevDisabled = result.currentPage <= 1 ? 'disabled' : '';
            const nextDisabled = result.currentPage >= result.totalPages ? 'disabled' : '';
            
            pagination.innerHTML = `
                <div class="pagination-info">${paginationInfo}</div>
                <div class="pagination-controls">
                    <button class="btn btn-primary" onclick="searchLogs(1)" ${result.currentPage <= 1 ? 'disabled' : ''}>首页</button>
                    <button class="btn btn-primary" onclick="searchLogs(${result.currentPage - 1})" ${prevDisabled}>上一页</button>
                    <button class="btn btn-primary" onclick="searchLogs(${result.currentPage + 1})" ${nextDisabled}>下一页</button>
                    <button class="btn btn-primary" onclick="searchLogs(${result.totalPages})" ${result.currentPage >= result.totalPages ? 'disabled' : ''}>末页</button>
                </div>
            `;
        }
        
        // 下载日志
        function downloadLogs() {
            const fileName = document.getElementById('fileSelect').value;
            if (!fileName) {
                alert('请先选择日志文件');
                return;
            }
            
            const params = new URLSearchParams();
            
            const keyword = document.getElementById('keyword').value;
            const level = document.getElementById('level').value;
            const startTime = document.getElementById('startTime').value;
            const endTime = document.getElementById('endTime').value;
            
            if (keyword) params.append('keyword', keyword);
            if (level) params.append('level', level);
            if (startTime) params.append('startTime', startTime);
            if (endTime) params.append('endTime', endTime);
            
            const url = `/api/logs/download/${encodeURIComponent(fileName)}?${params.toString()}`;
            
            // 创建隐藏的下载链接
            const link = document.createElement('a');
            link.href = url;
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 刷新日志
        function refreshLogs() {
            if (currentQuery.fileName) {
                searchLogs(currentPage);
            }
        }
        
        // 显示加载状态
        function showLoading() {
            const resultPanel = document.getElementById('resultPanel');
            const logContent = document.getElementById('logContent');
            
            resultPanel.style.display = 'block';
            logContent.innerHTML = '<div class="loading">🔄 正在加载日志...</div>';
        }
        
        // 显示错误信息
        function showError(message) {
            const resultPanel = document.getElementById('resultPanel');
            const logContent = document.getElementById('logContent');
            
            resultPanel.style.display = 'block';
            logContent.innerHTML = `<div class="error-message">❌ ${message}</div>`;
        }
        
        // 获取日志级别样式
        function getLogLevel(line) {
            if (line.includes('ERROR')) return'error';
            if (line.includes('WARN')) return'warn';
            if (line.includes('INFO')) return'info';
            return'';
        }
        
        // 高亮关键字
        function highlightKeyword(text, keyword) {
            if (!keyword) return text;
            
            const regex = newRegExp(`(${escapeRegex(keyword)})`, 'gi');
            return text.replace(regex, '<span class="highlight">$1</span>');
        }
        
        // 转义HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // 转义正则表达式特殊字符
        function escapeRegex(string) {
            return string.replace(/[.*+?^${}()|[]\]/g, '\$&');
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return'0 B';
            
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            returnparseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 格式化日期
        function formatDate(timestamp) {
            returnnewDate(timestamp).toLocaleDateString('zh-CN');
        }
        
        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            returnnewDate(dateTimeStr).toLocaleString('zh-CN');
        }
    </script>
</body>
</html>

配置文件

application.yml
server:
  port:8080
servlet:
    context-path:/

spring:
application:
    name:log-viewer
web:
    resources:
      static-locations:classpath:/static/

# 日志查看器配置
log:
viewer:
    log-path:./logs# 日志文件目录
    allowed-extensions:
      -.log
      -.txt
    max-lines:1000   # 单次查询最大行数
    max-file-size:100# 文件最大大小(MB)
    enable-security:true# 启用安全检查

# 日志配置
logging:
level:
    com.example.logviewer:DEBUG
pattern:
    file:"%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n"
file:
    name:./logs/app.log
logback:
    rollingpolicy:
      max-file-size:10MB
      max-history:30

部署与使用

1. 快速启动
# 克隆项目
git clone <your-repo-url>
cd log-viewer

# 编译打包
mvn clean package -DskipTests

# 启动应用
java -jar target/log-viewer-1.0.0.jar

# 访问系统
open http://localhost:8080
2. Docker 部署
FROM openjdk:11-jre-slim

VOLUME /app/logs
COPY target/log-viewer-1.0.0.jar app.jar

EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
# 构建镜像
docker build -t log-viewer .

# 运行容器
docker run -d \
  --name log-viewer \
  -p 8080:8080 \
  -v /path/to/logs:/app/logs \
log-viewer
3. 生产环境配置
# application-prod.yml
log:
viewer:
    log-path:/var/log/myapp
    max-file-size:500
    enable-security:true

logging:
level:
    root:WARN
    com.example.logviewer:INFO

功能特性

已实现功能
  • 日志文件列表展示

  • 关键字搜索

  • 时间范围过滤

  • 日志级别筛选

  • 分页浏览

  • 文件下载(原文件/筛选结果)

  • 语法高亮

  • 响应式设计

  • 安全防护(路径遍历攻击防护)

  • 实时日志监控(WebSocket)

后续可扩展功能
  • 日志统计分析

  • 多文件合并查看

  • 正则表达式搜索

  • 用户权限管理

  • 日志告警功能

性能优化建议

1. 大文件处理
// 使用 RandomAccessFile 实现大文件分页读取
public List<String> readFileByPage(File file, int page, int pageSize) {
    List<String> lines = new ArrayList<>();
    try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
        // 计算起始位置
        long startPos = calculateStartPosition(raf, page, pageSize);
        raf.seek(startPos);
        
        // 读取指定行数
        String line;
        int count = 0;
        while ((line = raf.readLine()) != null && count < pageSize) {
            lines.add(new String(line.getBytes("ISO-8859-1"), "UTF-8"));
            count++;
        }
    } catch (IOException e) {
        log.error("读取文件失败", e);
    }
    return lines;
}
2. 异步处理
@Async
public CompletableFuture<LogQueryResponse> queryLogsAsync(LogQueryRequest request) {
    return CompletableFuture.supplyAsync(() -> {
        return queryLogs(request);
    });
}

总结

本文实现了一个功能完整的日志查询系统,具有以下特点:

  • 轻量级: 无需复杂的部署,Spring Boot + 静态页面即可运行

  • 功能完整: 支持搜索、过滤、分页、下载等核心功能

  • 用户友好: 现代化的UI设计,响应式布局

  • 安全可靠: 包含安全检查和错误处理

  • 易于扩展: 模块化设计,便于添加新功能

这个系统特别适合中小型项目的日志管理需求,可以显著提升问题排查效率。

你可以根据实际需求进行定制和扩展,比如添加实时监控、统计分析等功能。

https://github.com/yuboon/java-examples/tree/master/springboot-logview


欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,“长按”或“扫描”下方二维码噢:

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
SpringBoot开发——构建轻量级日志查看器,省时又省力 阅读详情

相关推荐

frontend-design skills

frontend-design skills

开发者必备工具:用 SpringBoot 构建轻量级日志查看器,省时又省力

生产环境出现问题,需要快速定位错误日志日志文件太大,下载耗时且占用带宽需要根据时间、关键字、日志级别等条件筛选日志多人协作时,都需要登录服务器查看日志虽然有 ELK、Splunk 等成熟方案,但对于中小型项目来说,部署成本高、资源消耗大。今天我们用 Spring Boot + 纯前端技术栈,打造一个轻量级、开箱即用的日志管理系统。1. 轻量级:无需复杂的部署,Spring Boot + 静态页面即可运行2. 功能完整:支持搜索、过滤、分页、下载等核心功能3. 用户友好。

风象南的专栏 659

用于计算系统状态的卡尔曼最优增益和最小均方误差(MMSE)估计研究(Matlab代码实现)

内容概要:本文围绕用于计算系统状态的卡尔曼最优增益和最小均方误差(MMSE)估计展开研究,深入探讨了卡尔曼滤波在动态系统状态估计中的核心作用。文章系统阐述了卡尔曼滤波的数学基础,包括状态空间模型的建立、先验与后验状态估计、协方差矩阵的递推更新,以及最优增益矩阵的推导过程,确保在高斯白噪声环境下实现对系统状态的最小均方误差估计。结合Matlab代码实现,完整展示了算法从理论建模到仿真实验的全流程,涵盖系统建模、噪声设置、滤波迭代、状态更新与误差分析等环节,并通过仿真实验验证了算法在噪声干扰下对系统真实状态的高精度跟踪能力。该研究为控制工程、导航系统、信号处理及自动化领域中的状态估计问题提供了坚实的理论依据与高效的数值实现方案。; 适合人群:具备一定控制理论、概率统计基础和Matlab编程能力,从事自动化、电子信息、航空航天、机器人、导航定位等相关领域的科研人员、工程技术人员及高校研究生。; 使用场景及目标:①掌握卡尔曼滤波的基本原理及其在状态估计中的数学推导过程;②学习如何利用Matlab实现卡尔曼滤波算法并进行系统仿真与性能评估;③应用于目标跟踪、传感器融合、惯性导航、故障诊断、时间序列预测等实际工程中的动态状态估计问题。; 阅读建议:建议读者结合文中提供的Matlab代码进行动手实践,通过调整系统模型参数、过程噪声与观测噪声强度,观察滤波效果的变化,深入理解卡尔曼增益的自适应调节机制与MMSE估计的收敛特性。同时可进一步拓展学习扩展卡尔曼滤波(EKF)、无迹卡尔曼滤波(UKF)等非线性滤波方法,以应对更复杂的非线性系统状态估计挑战。

SpringBoot 构建轻量级日志查看器,省时又省力!

实现简单:基于SpringBoot和SSE技术,开发难度低实时性强:接近tail -f的实时查看体验易于部署:打包成jar包即可运行,无需额外依赖功能丰富:支持日志高亮、搜索、清空等实用功能扩展性好:可根据需要添加更多功能掌握了这个技术,相信你再面对日志查看需求时会更加从容不迫,让你的开发效率更上一层楼!源代码工程:公众号回复:【日志查看器】获取源码!今日思考:你们团队在日志查看方面有什么好的工具或方法?欢迎在评论区分享你的经验!

我爱娃哈哈的专栏 775

用Keil5给CH552G编程:手把手配置8051开发环境+LED闪烁实战

本文详细介绍了如何使用Keil5为CH552G单片机配置8051开发环境,并完成LED闪烁实战。从获取必要软件、安装WCH器件库到创建工程、编写程序及烧录,手把手指导开发者避开常见陷阱,特别适合从STC转向CH552G的开发者。

weixin_30733003的博客 539

万象RK3506-EG1800网关使用说明

摘要:HD-RK3506-EG1800是一款高性能工业物联网边缘计算网关,支持Buildroot和Ubuntu双系统。文档详细介绍了网关的网络配置(包括ETH0/ETH1的静态IP设置、WiFi连接)、时钟同步、HSL软件安装配置(含开机自启动服务)、系统日志优化以及刷机操作指南(Loader/Maskrom模式)。特别提供了基于lighttpd的网页管理方案,通过HTML界面实现网络参数可视化配置,包含身份验证、实时状态显示和表单提交功能。网关默认ETH0固定IP为192.168.1.10,提供完整的CL

tian_jiangnan的博客 180

轻量级日志分析平台Loki实战

Loki的第一个稳定版本于2019年11月19日发布,是Grafana Labs团队最新的开源项目,是一个水平可扩展,高可用性,多租户的日志聚合系统。Loki 是专门用于聚集日志数据,重点...

Docker的专栏 1408

服务器安装Ubuntu 18.04.2 LTS超详细步骤(小白图文详解)

服务器安装Ubuntu 18.04.2 LTS超详细步骤(小白图文详解) 本文不包括启动盘制作步骤,相关内容可自行百度 华为服务器 1 插入u盘,关机重启 2 初始化界面后进入到系统的BIOS设置界面 (华为服务器按Del键,不同品牌方法不同) 3 进入的时候,华为的服务器默认设置了BIOS密码,因此需要输入之前预设的密码。 注意密码大小写问题,若密码输错三次,则需重启 4 密码输入以后,进入...

crystalbang的博客 2万+

还在用ELK?Springboot 轻量级日志采集与可视化查询工具开源啦!

Java应用开发时,服务器上的日志往往是以日志文件的形式存在。在日常维护时,通常需要将日志信息实现可视化查询。 ELK、EFK 等是优秀的日志可视化查询解决方案。不过对于部分开发者来说,日志的采集配置与日志可视化配置是一个比较繁琐的过程。 为此我们希望通过一些低门槛的方式,实现日志的自动采集与日志可视化查询。 zero-observer 依托于 zero-log 的自动化日志采集插件,实现接收 Java 应用上报的日志数据,并提供开箱即用的日志可视化检索功能,极大降低了 Java 应用日志可视化检索的门槛。

专注分享原创技术干货。大厂资深架构师,多年技术架构与技术管理经验,多年面试官经验。一对一技术指导培训,带你从小白到入门到架构设计到技术管理。关注我,免费领取学习资料。一对一免费面试指导,快速拿offer。 1221

Opencv4.5.1 微信二维码识别功能 QRCode 编译与使用 C++

部分参考:https://mp.weixin.qq.com/s/2GZAJAUPHTXFOKDRv-D21Q 一、下载源码 https://github.com/opencv 二、源码编译 ① 在cmake中添加源码编译路径和生成路径,第一次点击configure。 ② 添加contrib路径 第一次configure后,找到OPENCV_EXTRA_MODULES_PATH,将contrib路径添加进来,注意要具体到modules/,继续configure。 ..

zaibeijixing的专栏 1万+

基于 Node.js + MongoDB 技术栈的小众开源短链接程序 —— Lynx

开源的短链接程序有很多,像 YOURLS、Shlink 等大多采用 PHP + MySQL 技术栈。但我之前的服务器配置一般,再加上自己写的小玩具使用的是 Node.js + MongoDB,这些环境已经装在服务器上了,因此更倾向于寻找一款同样基于这套技术栈的短链接程序。搜索了很久才找到这么一款基于的短链接程序——Lynx。这个开源项目非常小众,Star 数只有两百多。

zc_mk的博客 828

使用 Loki、Loki4j、Grafana 和 Spring Boot 搭建一个轻量级、简单、易用的 Java 日志系统

Loki:类似于 Prometheus 的日志系统,但 Loki 并不索引日志的内容,而是通过标签(label)进行索引,使用 PromQL 进行查询,轻量级且高效。Loki4j:一个适用于 Java 项目的日志库,可以将 Spring Boot 项目的日志直接推送到 Loki。Grafana:用于可视化 Loki 中存储的日志,并提供查询、分析和展示日志的功能。:作为 Java 应用框架,用于生成日志并集成 Loki4j 进行日志传输。Loki提供日志的存储和索引,轻量高效。Loki4j。

XiaoCai 3368

Ubuntu 22.04 “软件与更新”装了NVIDIA驱动,WiFi等设备不见了

在Win10装了Ubuntu22.04的双系统,台式机里面有NVIDIA 3080Ti的独立显卡,Ubuntu默认使用的nouveau驱动,需要更换成NVIDIA相应的驱动,在软件和更新里面一键安装了NVIDIA-driver-535-server之后,发现wifi、蓝牙等设备消失了。这个问题的根源据说跟这个nouveau驱动有关,希望linux社区可以解决这个问题。命令安装后 sudo reboot就可以重新看到WiFi以及蓝牙等设备图标了。然后用U盘拷贝到不能上网的Ubuntu22.04系统上,利用。

me_ysd的博客 5865

SpringBoot集成KoTime

koTime是一个开源免费的springboot项目性能分析工具,通过以及对应的快速定位性能瓶颈,除此之外,都可以有!

程序猿_杨Sir 877

PTGui使用教程

PTGui使用教程为啥使用ptgui开始使用ptgui 为啥使用ptgui ptgui是一个全景拼接软件,在海思hi3559上做视频拼接的时候,需要拼接参数,这是就需要使用到ptgui,这里可以在该网站下下载ptgui:下载地址 开始使用ptgui 第一步,加载图片,我这里添加了三幅图 然后添加控制点(可以先多对准几次图像,这样会自动生成一些控制点,但是不保证准确),建议控制点不要太密集 点开镜头设置,勾选以下几个选项以及配置好镜头类型,如下图 点开优化器,在高级界面中配置如下参数,最后点

what_wrong的博客 1万+

【WRF-Urban】使用 CGLC-MODIS-LCZ_100m 数据集运行 WRF 时的城市参数化问题

【WRF-Urban】使用 CGLC-MODIS-LCZ_100m 数据集运行 WRF 时的城市参数化问题

WW、forever的博客 716

SpringBoot与Loki轻量级日志系统

因为网上好多都没有通过Loki的API自己实现对日志监控系统,所以我就下定决心自己出一版关于loki与springboot的博文供大家参考,这个可以说是比较实用,很适合中小型企业。因此我酝酿了挺久了,对于loki的研究也比较久,希望各位读者能有新的收获。

qq_43843951的博客 21万+

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

springboot+logback实现系统日志记录

前言       最近在搞springboot项目,想给项目中加入日志。之前一直在使用log4j,首先想到怎么集成log4j,但查阅相关文档之后发现springboot默认日志框架为logback,而且logback比log4j更好用,于是果断抛弃log4j。正文        Spring Boot在所有内部日志中使用Commons Logging,但是默认配置也提供了对常用日志的支持,如:Ja...

Birds_Cerebrum的专栏 1877

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Springboot+elk实现分布式日志管理

本博文大部分内容来自http://blog.51cto.com/zero01/2079879,详细内容可参考此博文。 一:准备工作 1.准备三台机器: 10.2.0.151 主 10.2.0.152 数据中心 10.2.0.153 数据中心 机器上都安装上jdk 2.修改host文件 vim /etc/hosts 10.2.0.151 master-node 10.2.0.152 data-n...

Cosmos的博客 4593

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

springboot log日志系统详解

参: https://www.jianshu.com/p/5716eadbd12d?utm_campaign=hugo

josephhao的博客 192

Spring Boot 整合轻量级日志框架tinylog

tinylog(https://tinylog.org/v2/),与其他各种tiny开头的东西一样,是一个轻量级的开源日志解决方案。它本身只包含两个JAR文件(一个用于API,另一个用于实...

程序猿DD 959

Spring Boot搭建轻量级的博客系统

项目介绍 轻量级基于Spring Boot的博客系统 分为前端展示和后端管理 设计风格整体简约-采用Amaze UI 开源博客模板 文章发布设计两大编辑器,支持Markdown与普通富文本编辑 支持整体页面定制化操作,提供定制化操作模板配置管理页 个人资源支持本地上传与外链引入 文件服务器可选本地服务与第三方存储(已接入七牛云) 使用自动配置脚本,只需简单的数据库与文件服务器配置即...

qq_39559881的博客 7906

SpringBoot整合ELK日志收集

ELK简介 ELK是Elasticsearch+Logstash+Kibana简称 Elasticsearch 是一个分布式的搜索和分析引擎,可以用于全文检索、结构化检索和分析,并能将这三者结合起来。Elasticsearch 基于 Lucene 开发,现在是使用最广的开源搜索引擎之一。 Logstash 简单来说就是一根具备实时数据传输能力的管道,负责将数据信息从管道的输入端传输到管道...

papima的博客 1万+

Springboot项目搭配ELK日志平台

Springboot整合ELK日志平台,logback日志输出到logstash

tianyaleixiaowu的专栏 9092
上一篇: 从原理到实战:基于SpringAI的RAG应用探索
下一篇: 告别重复编码!SpringBoot + JSON Schema 动态表单开发
公众号-芋道源码
博客等级 码龄10年 1640粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值