github.com/imannamdari/v2ray-core/v5@v5.0.5/main/commands/all/api/log.go (about)

     1  package api
     2  
     3  import (
     4  	"io"
     5  	"log"
     6  	"os"
     7  
     8  	logService "github.com/imannamdari/v2ray-core/v5/app/log/command"
     9  	"github.com/imannamdari/v2ray-core/v5/main/commands/base"
    10  )
    11  
    12  var cmdLog = &base.Command{
    13  	CustomFlags: true,
    14  	UsageLine:   "{{.Exec}} api log [--server=127.0.0.1:8080]",
    15  	Short:       "log operations",
    16  	Long: `
    17  Follow and print logs from v2ray.
    18  
    19  > Make sure you have "LoggerService" set in "config.api.services" 
    20  of server config.
    21  
    22  > It ignores -timeout flag while following logs
    23  
    24  Arguments:
    25  
    26  	-restart 
    27  		Restart the logger
    28  
    29  	-s, -server <server:port>
    30  		The API server address. Default 127.0.0.1:8080
    31  
    32  	-t, -timeout <seconds>
    33  		Timeout seconds to call API. Default 3
    34  
    35  Example:
    36  
    37      {{.Exec}} {{.LongName}}
    38      {{.Exec}} {{.LongName}} --restart
    39  `,
    40  	Run: executeLog,
    41  }
    42  
    43  func executeLog(cmd *base.Command, args []string) {
    44  	var restart bool
    45  	cmd.Flag.BoolVar(&restart, "restart", false, "")
    46  	setSharedFlags(cmd)
    47  	cmd.Flag.Parse(args)
    48  
    49  	if restart {
    50  		restartLogger()
    51  		return
    52  	}
    53  	followLogger()
    54  }
    55  
    56  func restartLogger() {
    57  	conn, ctx, close := dialAPIServer()
    58  	defer close()
    59  	client := logService.NewLoggerServiceClient(conn)
    60  	r := &logService.RestartLoggerRequest{}
    61  	_, err := client.RestartLogger(ctx, r)
    62  	if err != nil {
    63  		base.Fatalf("failed to restart logger: %s", err)
    64  	}
    65  }
    66  
    67  func followLogger() {
    68  	conn, ctx, close := dialAPIServerWithoutTimeout()
    69  	defer close()
    70  	client := logService.NewLoggerServiceClient(conn)
    71  	r := &logService.FollowLogRequest{}
    72  	stream, err := client.FollowLog(ctx, r)
    73  	if err != nil {
    74  		base.Fatalf("failed to follow logger: %s", err)
    75  	}
    76  	// work with `v2ray api log | grep expr`
    77  	log.SetOutput(os.Stdout)
    78  	for {
    79  		resp, err := stream.Recv()
    80  		if err == io.EOF {
    81  			break
    82  		}
    83  		if err != nil {
    84  			base.Fatalf("failed to fetch log: %s", err)
    85  		}
    86  		log.Println(resp.Message)
    87  	}
    88  }