package main import ( "cfTest/cloudflareApi/cache/purge" "cfTest/cloudflareApi/certificate" "cfTest/cloudflareApi/dns" "cfTest/cloudflareApi/logPush" "cfTest/cloudflareApi/zone" "cfTest/server" "context" "fmt" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery" "github.com/sirupsen/logrus" "google.golang.org/grpc" "io" "log" "net" "os" ) import "github.com/grpc-ecosystem/go-grpc-middleware" const ( port = ":50051" ) // InterceptorLogger adapts logrus logger to interceptor logger. // This code is simple enough to be copied and not imported. func InterceptorLogger(l logrus.FieldLogger) logging.Logger { return logging.LoggerFunc(func(_ context.Context, lvl logging.Level, msg string, fields ...any) { f := make(map[string]any, len(fields)/2) i := logging.Fields(fields).Iterator() for i.Next() { k, v := i.At() f[k] = v } l := l.WithFields(f) switch lvl { case logging.LevelDebug: l.Debug(msg) case logging.LevelInfo: l.Info(msg) case logging.LevelWarn: l.Warn(msg) case logging.LevelError: l.Error(msg) default: panic(fmt.Sprintf("unknown level %v", lvl)) } }) } func main() { //日志设置 logger := logrus.New() loggerOutputs := []io.Writer{os.Stdout} logFilePath := "CloudflareServer.log" if len(os.Args) > 1 { logFilePath = os.Args[1] } file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) if err != nil { logger.Error(err) } else { loggerOutputs = append(loggerOutputs, file) } logger.SetOutput(io.MultiWriter(loggerOutputs...)) opts := []logging.Option{ logging.WithLogOnEvents(logging.StartCall, logging.FinishCall, logging.PayloadReceived, logging.PayloadSent), } //监听端口 lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } //注册GRPC中间件 s := grpc.NewServer( grpc.ChainUnaryInterceptor(grpc_middleware.ChainUnaryServer( grpc_recovery.UnaryServerInterceptor(), logging.UnaryServerInterceptor(InterceptorLogger(logger), opts...), )), grpc.ChainStreamInterceptor(grpc_middleware.ChainStreamServer( grpc_recovery.StreamServerInterceptor(), logging.StreamServerInterceptor(InterceptorLogger(logger), opts...), )), ) //注册服务 purge.RegisterPurgeCloudflareServer(s, &server.PurgeServer{}) certificate.RegisterCertificateCloudflareServer(s, &server.CertificateServer{}) zone.RegisterZoneCloudflareServer(s, &server.ZoneServer{}) dns.RegisterDnsCloudflareServer(s, &server.DnsServer{}) logPush.RegisterLogPushCloudflareServer(s, &server.LogPushCloudflareServer{}) //启动服务 log.Printf("server listening at %v", lis.Addr()) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }