github.com/fzfile/BaiduPCS-Go@v0.0.0-20200606205115-4408961cf336/pcsverbose/pcsverbose.go (about)

     1  // Package pcsverbose 调试包
     2  package pcsverbose
     3  
     4  import (
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  )
     9  
    10  const (
    11  	// EnvVerbose 启用调试环境变量
    12  	EnvVerbose = "BAIDUPCS_GO_VERBOSE"
    13  )
    14  
    15  var (
    16  	// IsVerbose 是否调试
    17  	IsVerbose = os.Getenv(EnvVerbose) == "1"
    18  
    19  	// Outputs 输出
    20  	Outputs = []io.Writer{os.Stderr}
    21  )
    22  
    23  // PCSVerbose 调试
    24  type PCSVerbose struct {
    25  	Module string
    26  }
    27  
    28  // New 根据module, 初始化PCSVerbose
    29  func New(module string) *PCSVerbose {
    30  	return &PCSVerbose{
    31  		Module: module,
    32  	}
    33  }
    34  
    35  // Info 提示
    36  func (pv *PCSVerbose) Info(l string) {
    37  	Verbosef("DEBUG: %s INFO: %s\n", pv.Module, l)
    38  }
    39  
    40  // Infof 提示, 格式输出
    41  func (pv *PCSVerbose) Infof(format string, a ...interface{}) {
    42  	Verbosef("DEBUG: %s INFO: %s", pv.Module, fmt.Sprintf(format, a...))
    43  }
    44  
    45  // Warn 警告
    46  func (pv *PCSVerbose) Warn(l string) {
    47  	Verbosef("DEBUG: %s WARN: %s\n", pv.Module, l)
    48  }
    49  
    50  // Warnf 警告, 格式输出
    51  func (pv *PCSVerbose) Warnf(format string, a ...interface{}) {
    52  	Verbosef("DEBUG: %s WARN: %s", pv.Module, fmt.Sprintf(format, a...))
    53  }
    54  
    55  // Verbosef 调试格式输出
    56  func Verbosef(format string, a ...interface{}) (n int, err error) {
    57  	if IsVerbose {
    58  		for _, Output := range Outputs {
    59  			n1, err := fmt.Fprintf(Output, TimePrefix()+" "+format, a...)
    60  			n += n1
    61  			if err != nil {
    62  				return n, err
    63  			}
    64  		}
    65  	}
    66  	return
    67  }
    68  
    69  // Verboseln 调试输出一行
    70  func Verboseln(a ...interface{}) (n int, err error) {
    71  	if IsVerbose {
    72  		for _, Output := range Outputs {
    73  			n1, err := fmt.Fprint(Output, TimePrefix()+" ")
    74  			n += n1
    75  			if err != nil {
    76  				return n, err
    77  			}
    78  			n2, err := fmt.Fprintln(Output, a...)
    79  			n += n2
    80  			if err != nil {
    81  				return n, err
    82  			}
    83  		}
    84  	}
    85  	return
    86  }