package main import ( "context" "log/slog" "time" "gitea.cccvno1.com/chenchi/logx" ) func main() { // 创建一个新的日志记录器 logger := logx.New( logx.WithConsoleHandler(slog.LevelDebug), logx.WithFileHandler("app.log", 10, 5, 30, true, slog.LevelInfo), logx.WithContextExtractor(customContextExtractor), ) // 设置全局日志记录器 logx.SetGlobalLogger(logger) // 使用全局日志记录器 logx.Info("Application started") // 创建一个带有跟踪ID的上下文 ctx := context.WithValue(context.Background(), "trace_id", "abc123") // 使用带有上下文的日志记录器 contextLogger := logx.WithContext(ctx) contextLogger.Debug("This is a debug message with context") contextLogger.Info("This is an info message with context") contextLogger.Warn("This is a warning message with context") contextLogger.Error("This is an error message with context") // 使用不同的日志级别 logx.Debug("This is a debug message") logx.Info("This is an info message") logx.Warn("This is a warning message") logx.Error("This is an error message") // 使用结构化日志 logx.Info("User logged in", slog.String("username", "john_doe"), slog.Int("user_id", 12345), slog.Time("login_time", time.Now()), ) // 模拟一个错误情况 if err := simulateError(); err != nil { logx.Error("An error occurred", slog.String("error", err.Error())) } // 关闭日志记录器 if err := logger.Close(); err != nil { logx.Error("Failed to close logger", slog.String("error", err.Error())) } } func customContextExtractor(ctx context.Context) []slog.Attr { return []slog.Attr{ slog.String("trace_id", getTraceID(ctx)), slog.String("user_id", getUserID(ctx)), } } func getTraceID(ctx context.Context) string { if traceID, ok := ctx.Value("trace_id").(string); ok { return traceID } return "" } func getUserID(ctx context.Context) string { if userID, ok := ctx.Value("user_id").(string); ok { return userID } return "" } func simulateError() error { // 模拟一个错误 return &customError{message: "Something went wrong"} } type customError struct { message string } func (e *customError) Error() string { return e.message }