Browse Source

迭代优化日志代码

niujiuru 3 weeks atrás
parent
commit
0fe38475c8
3 changed files with 23 additions and 6 deletions
  1. 23 6
      baseapp/log.go
  2. BIN
      package/rtu_linux_modules_1.0.0.1.tar.gz
  3. BIN
      package/yfkj_ssh_client_1.0.0.1.tar.gz

+ 23 - 6
baseapp/log.go

@@ -19,6 +19,7 @@ package baseapp
 import "C"
 
 import (
+	"bytes"
 	"errors"
 	"fmt"
 	"io"
@@ -115,6 +116,20 @@ func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
 	return []byte(msg), nil
 }
 
+type systemdConsoleWriter struct{}
+
+func (w *systemdConsoleWriter) Write(p []byte) (int, error) {
+	msg := p
+
+	if idx := bytes.Index(msg, []byte("] ")); idx != -1 {
+		msg = msg[idx+2:]
+	}
+
+	_, _ = os.Stdout.Write(msg)
+
+	return len(p), nil
+}
+
 // 日志配置
 type config struct {
 	// 日志输出级别
@@ -246,7 +261,13 @@ func setLogTargetInternal(targetStr string) {
 
 	writers := make([]io.Writer, 0)
 	if (cfgLog.Target & TARGET_CONSOLE) != 0 {
-		writers = append(writers, os.Stdout)
+		isSystemd := os.Getenv("INVOCATION_ID") != "" || os.Getenv("JOURNAL_STREAM") != ""
+
+		if isSystemd {
+			writers = append(writers, &systemdConsoleWriter{})
+		} else {
+			writers = append(writers, os.Stdout)
+		}
 	}
 	if (cfgLog.Target & TARGET_FILE) != 0 {
 		logDir := LOG_DIR
@@ -371,11 +392,7 @@ func LogFromGo(level *C.char, file *C.char, line C.int, message *C.char) {
 	goLevel := C.GoString(level)
 	goMessage := C.GoString(message)
 
-	logMu.Lock()
-	lvl := cfgLog.Level
-	logMu.Unlock()
-
-	if (lvl == LEVEL_TRACE || lvl == LEVEL_DEBUG) && line > 0 {
+	if (cfgLog.Level == LEVEL_TRACE || cfgLog.Level == LEVEL_DEBUG) && line > 0 {
 		gofile := filepath.Base(C.GoString(file))
 		goline := int(line)
 		goMessage = fmt.Sprintf("(from %s:%d): %s", gofile, goline, goMessage)

BIN
package/rtu_linux_modules_1.0.0.1.tar.gz


BIN
package/yfkj_ssh_client_1.0.0.1.tar.gz