mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-05 07:26:36 +08:00
[优化] 使用 slog 替代 fmt 进行日志输出
This commit is contained in:
@@ -1,76 +1,20 @@
|
|||||||
package logging
|
package logging
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
type customTextHandler struct {
|
|
||||||
writer io.Writer
|
|
||||||
level slog.Level
|
|
||||||
attrs []slog.Attr
|
|
||||||
groups []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func Setup() {
|
func Setup() {
|
||||||
handler := &customTextHandler{
|
opts := &slog.HandlerOptions{
|
||||||
writer: os.Stdout,
|
AddSource: true,
|
||||||
level: parseLevel(os.Getenv("LOG_LEVEL")),
|
Level: parseLevel(os.Getenv("LOG_LEVEL")),
|
||||||
}
|
}
|
||||||
|
handler := slog.NewTextHandler(os.Stdout, opts)
|
||||||
slog.SetDefault(slog.New(handler))
|
slog.SetDefault(slog.New(handler))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *customTextHandler) Enabled(_ context.Context, level slog.Level) bool {
|
|
||||||
return level >= h.level
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *customTextHandler) Handle(_ context.Context, record slog.Record) error {
|
|
||||||
var builder strings.Builder
|
|
||||||
builder.WriteString(record.Time.Format("2006-01-02 15:04:05.000"))
|
|
||||||
builder.WriteString(" | ")
|
|
||||||
builder.WriteString(fmt.Sprintf("%-8s", levelLabel(record.Level)))
|
|
||||||
builder.WriteString(" | ")
|
|
||||||
builder.WriteString(sourceLocation(record.PC))
|
|
||||||
builder.WriteString(" - ")
|
|
||||||
builder.WriteString(record.Message)
|
|
||||||
|
|
||||||
attrs := make([]slog.Attr, 0, len(h.attrs)+record.NumAttrs())
|
|
||||||
attrs = append(attrs, h.attrs...)
|
|
||||||
record.Attrs(func(attr slog.Attr) bool {
|
|
||||||
attrs = append(attrs, attr)
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
if len(attrs) > 0 {
|
|
||||||
builder.WriteString(" | ")
|
|
||||||
builder.WriteString(formatAttrs(h.groups, attrs))
|
|
||||||
}
|
|
||||||
builder.WriteByte('\n')
|
|
||||||
_, err := io.WriteString(h.writer, builder.String())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *customTextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
||||||
cloned := *h
|
|
||||||
cloned.attrs = append(slices.Clone(h.attrs), attrs...)
|
|
||||||
return &cloned
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *customTextHandler) WithGroup(name string) slog.Handler {
|
|
||||||
if strings.TrimSpace(name) == "" {
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
cloned := *h
|
|
||||||
cloned.groups = append(slices.Clone(h.groups), name)
|
|
||||||
return &cloned
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseLevel(value string) slog.Level {
|
func parseLevel(value string) slog.Level {
|
||||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||||
case "debug":
|
case "debug":
|
||||||
@@ -83,51 +27,3 @@ func parseLevel(value string) slog.Level {
|
|||||||
return slog.LevelInfo
|
return slog.LevelInfo
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func levelLabel(level slog.Level) string {
|
|
||||||
switch {
|
|
||||||
case level <= slog.LevelDebug:
|
|
||||||
return "DEBUG"
|
|
||||||
case level < slog.LevelWarn:
|
|
||||||
return "INFO"
|
|
||||||
case level < slog.LevelError:
|
|
||||||
return "WARNING"
|
|
||||||
default:
|
|
||||||
return "ERROR"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func sourceLocation(pc uintptr) string {
|
|
||||||
if pc == 0 {
|
|
||||||
return "unknown:unknown:0"
|
|
||||||
}
|
|
||||||
frame, _ := runtime.CallersFrames([]uintptr{pc}).Next()
|
|
||||||
fileName := strings.TrimSuffix(filepath.Base(frame.File), filepath.Ext(frame.File))
|
|
||||||
if fileName == "" {
|
|
||||||
fileName = "unknown"
|
|
||||||
}
|
|
||||||
functionName := "unknown"
|
|
||||||
if frame.Function != "" {
|
|
||||||
parts := strings.Split(frame.Function, "/")
|
|
||||||
functionName = parts[len(parts)-1]
|
|
||||||
if dot := strings.LastIndex(functionName, "."); dot >= 0 && dot < len(functionName)-1 {
|
|
||||||
functionName = functionName[dot+1:]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%s:%s:%d", fileName, functionName, frame.Line)
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatAttrs(groups []string, attrs []slog.Attr) string {
|
|
||||||
parts := make([]string, 0, len(attrs))
|
|
||||||
for _, attr := range attrs {
|
|
||||||
key := attr.Key
|
|
||||||
if key == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if len(groups) > 0 {
|
|
||||||
key = strings.Join(append(slices.Clone(groups), key), ".")
|
|
||||||
}
|
|
||||||
parts = append(parts, fmt.Sprintf("%s=%v", key, attr.Value.Any()))
|
|
||||||
}
|
|
||||||
return strings.Join(parts, " ")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,22 +4,39 @@ package updater
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
func replaceAndRestart(execPath string, tmpPath string) error {
|
func replaceAndRestart(execPath string, tmpPath string) error {
|
||||||
backupPath := execPath + ".bak"
|
backupPath := execPath + ".bak"
|
||||||
os.Remove(backupPath)
|
err := os.Remove(backupPath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("remove backup binary failed", "path", backupPath, "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := os.Rename(execPath, backupPath); err != nil {
|
if err := os.Rename(execPath, backupPath); err != nil {
|
||||||
os.Remove(tmpPath)
|
err := os.Remove(tmpPath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("remove tmp binary failed", "path", tmpPath, "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
return fmt.Errorf("backup current binary: %w", err)
|
return fmt.Errorf("backup current binary: %w", err)
|
||||||
}
|
}
|
||||||
if err := os.Rename(tmpPath, execPath); err != nil {
|
if err := os.Rename(tmpPath, execPath); err != nil {
|
||||||
os.Rename(backupPath, execPath)
|
err := os.Rename(backupPath, execPath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("restore backup binary failed", "path", backupPath, "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
return fmt.Errorf("replace binary: %w", err)
|
return fmt.Errorf("replace binary: %w", err)
|
||||||
}
|
}
|
||||||
os.Remove(backupPath)
|
err = os.Remove(backupPath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("remove backup binary failed", "path", backupPath, "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := syscall.Exec(execPath, os.Args, os.Environ()); err != nil {
|
if err := syscall.Exec(execPath, os.Args, os.Environ()); err != nil {
|
||||||
return fmt.Errorf("exec restart: %w", err)
|
return fmt.Errorf("exec restart: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package common
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -20,10 +19,10 @@ var (
|
|||||||
var UploadPath = "upload"
|
var UploadPath = "upload"
|
||||||
|
|
||||||
func printHelp() {
|
func printHelp() {
|
||||||
fmt.Println("OpenFlare " + Version + " - Internal OpenResty Control Plane.")
|
slog.Info("OpenFlare " + Version + " - Internal OpenResty Control Plane.")
|
||||||
fmt.Println("Copyright (C) 2023 JustSong. All rights reserved.")
|
slog.Info("Copyright (C) 2023 JustSong. All rights reserved.")
|
||||||
fmt.Println("GitHub: https://github.com/Rain-kl/OpenFlare")
|
slog.Info("GitHub: https://github.com/Rain-kl/OpenFlare")
|
||||||
fmt.Println("Usage: openflare [--port <port>] [--log-dir <log directory>] [--version] [--help]")
|
slog.Info("Usage: openflare [--port <port>] [--log-dir <log directory>] [--version] [--help]")
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@@ -33,7 +32,7 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *PrintVersion {
|
if *PrintVersion {
|
||||||
fmt.Println(Version)
|
slog.Info(Version)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user