Skip to content

12 KisFlow Logger

刘丹冰 edited this page Apr 17, 2024 · 1 revision

Case Source Code https://github.com/aceld/kis-flow-usage/tree/main/11-logger

12.1 Custom Log Output

12.1.1 KisLogger interface

type KisLogger interface {
	// InfoFX is the Info level logging interface with context, using string format
	InfoFX(ctx context.Context, str string, v ...interface{})
	// ErrorFX is the Error level logging interface with context, using string format
	ErrorFX(ctx context.Context, str string, v ...interface{})
	// DebugFX is the Debug level logging interface with context, using string format
	DebugFX(ctx context.Context, str string, v ...interface{})

	// InfoF is the Info level logging interface without context, using string format
	InfoF(str string, v ...interface{})
	// ErrorF is the Error level logging interface without context, using string format
	ErrorF(str string, v ...interface{})
	// DebugF is the Debug level logging interface without context, using string format
	DebugF(str string, v ...interface{})

	// SetDebugMode sets the Debug mode
	SetDebugMode(enable bool)
}

12.1.2 Implementing Custom Log

// MyLogger Custom Logger
type MyLogger struct {
	debugMode bool
	mu        sync.Mutex
}

func (log *MyLogger) SetDebugMode(enable bool) {
	log.mu.Lock()
	defer log.mu.Unlock()
	log.debugMode = enable
}

func (log *MyLogger) InfoF(str string, v ...interface{}) {
	fmt.Printf(str, v...)
	fmt.Printf("\n")
}

func (log *MyLogger) ErrorF(str string, v ...interface{}) {
	fmt.Printf(str, v...)
	fmt.Printf("\n")
}

func (log *MyLogger) DebugF(str string, v ...interface{}) {
	log.mu.Lock()
	defer log.mu.Unlock()
	if log.debugMode {
		fmt.Printf(str, v...)
		fmt.Printf("\n")
	}
}

func (log *MyLogger) InfoFX(ctx context.Context, str string, v ...interface{}) {
	fmt.Println(ctx)
	fmt.Printf(str, v...)
	fmt.Printf("\n")
}

func (log *MyLogger) ErrorFX(ctx context.Context, str string, v ...interface{}) {
	fmt.Println(ctx)
	fmt.Printf(str, v...)
	fmt.Printf("\n")
}

func (log *MyLogger) DebugFX(ctx context.Context, str string, v ...interface{}) {
	log.mu.Lock()
	defer log.mu.Unlock()
	if log.debugMode {
		fmt.Println(ctx)
		fmt.Printf(str, v...)
		fmt.Printf("\n")
	}
}

12.1.3 Setting Custom Log

	// Set Custom Logger
	log.SetLogger(&MyLogger{})

12.2 Enable/Disable KisFlow Debug

// Set Debug Mode
log.Logger().SetDebugMode(true)