心有法竹
我最终得到了以下解决方案:func DB() *pgxpool.Pool { config, err := pgxpool.ParseConfig(connStr) if err != nil { fmt.Fprintf(os.Stderr, "Unable to parse config: %v\n", err) os.Exit(1) } looger := &log.Logger{ Out: os.Stderr, Formatter: new(log.JSONFormatter), Hooks: make(log.LevelHooks), Level: log.InfoLevel, ExitFunc: os.Exit, ReportCaller: false, } config.ConnConfig.Logger = logrusadapter.NewLogger(looger) conn, err := pgxpool.ConnectConfig(context.Background(), config) if err != nil { fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) os.Exit(1) } return conn}
幕布斯7119047
完全归功于@mystdeim,他在上面回答了。抄袭原因:进口说明清楚为什么不只是评论?:我没有 50 个代表让我们开始原答案:func DB() *pgxpool.Pool {config, err := pgxpool.ParseConfig(connStr)if err != nil { fmt.Fprintf(os.Stderr, "Unable to parse config: %v\n", err) os.Exit(1)}looger := &log.Logger{ Out: os.Stderr, Formatter: new(log.JSONFormatter), Hooks: make(log.LevelHooks), Level: log.InfoLevel, ExitFunc: os.Exit, ReportCaller: false,}config.ConnConfig.Logger = logrusadapter.NewLogger(looger)conn, err := pgxpool.ConnectConfig(context.Background(), config)if err != nil { fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) os.Exit(1)}return conn}上面的代码是可以的,但是我这里讲两点进口:log有一个令人困惑的导入log让我们仔细看看 looger := &log.Logger{ Out: os.Stderr, Formatter: new(log.JSONFormatter), Hooks: make(log.LevelHooks), Level: log.InfoLevel, ExitFunc: os.Exit, ReportCaller: false,}config.ConnConfig.Logger = logrusadapter.NewLogger(looger)首先,我们来谈谈log包导入。假设从最后一行开始,他正在使用logrus所以import ("log")是不可能的,因为你会失去logrus那时的力量。现在,如果您使用重命名logrus为logimport (log "github.com/sirupsen/logrus")它会产生另一个错误:LstdFlags not declared by package logrus (UndeclaredImportedName)进口logrusadapter不再工作: import ("github.com/jackc/pgx/log/logrusadapter")正在工作: import ("github.com/jackc/pgx/v4/log/logrusadapter")[嗯,好像是2021年的v4,以后导入前一定要检查你的版本]我修改后的解决方案你不需要remame logrus,保持原样。 import ( "github.com/sirupsen/logrus" "github.com/jackc/pgx/v4/pgxpool""github.com/jackc/pgx/v4/log/logrusadapter")最后func DB() *pgxpool.Pool { config, err := pgxpool.ParseConfig(connStr) if err != nil { fmt.Fprintf(os.Stderr, "Unable to parse config: %v\n", err) os.Exit(1) } logrusLogger := &logrus.Logger{ Out: os.Stderr, Formatter: new(logrus.JSONFormatter), Hooks: make(logrus.LevelHooks), Level: logrus.InfoLevel, ExitFunc: os.Exit, ReportCaller: false, } config.ConnConfig.Logger = logrusadapter.NewLogger(logrusLogger) conn, err := pgxpool.ConnectConfig(context.Background(), config) if err != nil { fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) os.Exit(1) } return conn}