sqle icon indicating copy to clipboard operation
sqle copied to clipboard

解决dms/sqle日志过量的问题

Open taolx0 opened this issue 1 year ago • 1 comments

背景

std.log目前没有轮转机制,如果长期不轮转,可能会导致硬盘空间被占用过多.

预期

期望可以对std.log进行轮转

方案(1)

通过 linux 自带的 logrotate 工具实现,可以根据日志size和保留日志份数参数实现

优点

  • dms/sqle 启动代码不需要调整

缺点

  • 依赖了系统命令logrotate【可能命令不存在】
  • 业务日志和std.log轮转方式不同

方案(2)

sqle/dms业务日志轮转使用了rotate包, std.log日志也使用rotate包进行轮转

优点

  • 业务日志和std日志使用了同一种轮转方式
  • 不依赖外部工具

缺点

  • 在dms/sqle启动时增加一段日志重定向代码
参考代码
package main

import (
	"fmt"
	"io"
	"log"
	"os"
)

func main() {
	fn := logOutput()
	defer fn()
	var words = "Hello Doctor Name Continue Yesterday Tomorrow"
	for i := 0; i < 10; i++ {
		log.Println(i)
		fmt.Println(i)
		fmt.Println(words)
	}
}

func logOutput() func() {
	logfile := `logfile`
	// open file read/write | create if not exist | clear file at open if exists
	f, _ := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)

	// save existing stdout | MultiWriter writes to saved stdout and file
	//out := os.Stdout
	//mw := io.MultiWriter(out, f)

	// get pipe reader and writer | writes to pipe writer come out pipe reader
	r, w, _ := os.Pipe()

	// replace stdout,stderr with pipe writer | all writes to stdout, stderr will go through pipe instead (fmt.print, log)
	os.Stdout = w
	os.Stderr = w

	// writes with log.Print should also write to mw
	// log.SetOutput(w)

	//create channel to control exit | will block until all copies are finished
	exit := make(chan bool)

	go func() {
		// copy all reads from pipe to multiwriter, which writes to stdout and file
		_, _ = io.Copy(f, r)
		// when r or w is closed copy will finish and true will be sent to channel
		exit <- true
	}()

	// function to be deferred in main until program exits
	return func() {
		// close writer then block on exit channel | this will let mw finish writing before the program exits
		_ = w.Close()
		<-exit
		// close file after all writes have finished
		_ = f.Close()
	}
}

taolx0 avatar Feb 05 '24 07:02 taolx0

目前看来,我们的日志量可能会很大。需要确认如下问题:

  1. 现有的日志是否有需要收敛的内容(减少不必要的日志内容)
  2. 旧的日志文件是否需要压缩处理
  3. 如果重定向标准输出,那容器方式部署的话,容器挂了,可能也无法查看std日志

ColdWaterLW avatar Apr 22 '24 05:04 ColdWaterLW

问题确认

  1. 没发现可以缩减日志的地方
  2. 实现日志轮转的情况下,已经可以解决大部份问题,不需要压缩处理
  3. 如果容器挂了,重定向后可能无法查看std.log日志,可以通过docker 挂载命令映射出std.log到宿主机或者 docker cp 日志文件到宿主机查看

taolx0 avatar May 11 '24 09:05 taolx0

sqle version: 4a5e6c84549f209380ba4cfaba41c364158b19b2 dms version:7ebf3da28e3f0558d120fd1fd04c24a071f174e3 验证点: sqle/plugins文件夹下存放几个插件,启动sqle观察插件日志

  1. 是否会出现在控制台中
  2. 是否会出现在sqled.log日志文件中

验证: 控制台中没有插件日志内容 image sqled.log文件出现插件日志 image

hasa1K avatar May 27 '24 05:05 hasa1K