12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package networkdiagnostic
- import (
- networkDiagnostic "cfTest/networkdiagnostic/pb"
- "context"
- "github.com/go-ping/ping"
- "github.com/sirupsen/logrus"
- "gopkg.in/natefinch/lumberjack.v2"
- "runtime"
- "time"
- )
- var logger *logrus.Logger
- type NetworkDiagnosticServer struct {
- networkDiagnostic.UnimplementedNetworkDiagnosticServiceServer
- }
- func (s *NetworkDiagnosticServer) NetworkLatencyProbe(ctx context.Context, probeRequest *networkDiagnostic.NetworkLatencyProbeRequest) (*networkDiagnostic.NetworkLatencyProbeReply, error) {
- logger.Println("domainName Received: ", probeRequest.GetDomainName())
- logger.Println("execCount Received: ", probeRequest.GetExecCount())
- logger.Println("interval Received: ", probeRequest.GetInterval())
- // 业务请求 -> ping
- pinger, err := ping.NewPinger(probeRequest.GetDomainName())
- if err != nil {
- return &networkDiagnostic.NetworkLatencyProbeReply{
- Error: err.Error(),
- }, nil
- }
- pinger.Count = int(probeRequest.GetExecCount())
- pinger.Timeout = 5 * time.Second
- pinger.Interval = time.Duration(probeRequest.GetInterval()) * time.Second
- if runtime.GOOS == "windows" {
- pinger.SetPrivileged(true)
- }
- err = pinger.Run()
- if err != nil {
- return &networkDiagnostic.NetworkLatencyProbeReply{
- Error: err.Error(),
- }, nil
- }
- status := pinger.Statistics()
- // response
- return &networkDiagnostic.NetworkLatencyProbeReply{
- Latency: float64(status.AvgRtt.Milliseconds()),
- PacketsReceive: int32(status.PacketsRecv),
- PacketsSend: int32(status.PacketsSent),
- IpAddr: status.IPAddr.IP.String(),
- }, nil
- }
- // logger
- func Init() {
- initLogger()
- }
- func initLogger() {
- setupLogger()
- // 在初始化函数中对包级别的变量进行初始化
- logger = logrus.StandardLogger()
- logger.Println("启动NetworkDiagnosticServer, 初始化日志框架...")
- }
- func setupLogger() {
- // 创建一个新的logrus实例
- log := logrus.New()
- // 设置日志输出为文件,并使用lumberjack库来实现每天生成一个新的日志文件,并保存旧日志文件
- log.SetOutput(&lumberjack.Logger{
- Filename: "../../logs/networkDiagnosticServer/" + generateLogFileName(), // 日志文件路径,使用日期占位符%Y-%m-%d
- MaxSize: 20, // 每个日志文件的最大尺寸,单位:MB
- MaxBackups: 3, // 最多保留的旧日志文件数
- MaxAge: 30, // 最多保留的旧日志文件天数(这里设置为30天)
- LocalTime: true, // 使用本地时间(默认为UTC时间)
- Compress: true, // 是否压缩旧日志文件
- })
- // 设置日志格式为JSON格式
- log.SetFormatter(&logrus.JSONFormatter{})
- // 设置日志级别为Debug
- log.SetLevel(logrus.DebugLevel)
- // 将logrus实例设置为全局的默认日志记录器
- logrus.StandardLogger().SetOutput(log.Out)
- }
- func generateLogFileName() string {
- currentDate := time.Now().Format("01-02-2006")
- return "networkDiagnostic_" + currentDate + ".log"
- }
- func GetLogger() *logrus.Logger {
- return logger
- }
|