GoLog

package module
v1.0.5-0...-20c45f9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2022 License: GPL-3.0 Imports: 17 Imported by: 0

README

gotaskv1

go定时任务工具库

Api
// 创建一个定时任务对象
// @params: routineCount    执行任务的线程池大小
// @retuen: *TimedTask      创建的定时任务对象
func NewTimedTask(routineCount int) (*TimedTask)


// 添加定时任务
func (tt *TimedTask) Add(key string, task TaskObj, spec int)
// @params: key              任务键
// @params: task             任务方法
// @params: spec             任务定时时长


// 取消定时任务
func (tt *TimedTask) Cancel(key string)
// @params: key              任务键


// 获取定时任务列表信息
func (tt *TimedTask)GetTimedTaskInfo()map[string]*TaskInfo
// @retuen: map[string]*TaskInfo      定时任务列表

Struct
// 执行任务回调函数参数结构体
type ExecuteCbArgs struct {
	Key      string                         任务键key
	Task     TaskObj                        任务方法
	LastTime time.Time                      最后一次执行任务的时间(未执行过时为time.Time{})
	AddTime  time.Time                      任务添加的时间
	Count    int                            任务执行次数
	Spec     int                            任务执行时间间隔
	Res     map[string]interface{}          任务执行结果
	Error   error                           任务执行错误信息
}


// 添加任务回调函数参数结构体
type AddCbArgs struct {
	Key      string                         任务键key
	Task     TaskObj                        任务方法
	LastTime time.Time                      最后一次执行任务的时间(未执行过时为time.Time{})
	AddTime  time.Time                      任务添加的时间
	Count    int                            任务执行次数
	Spec     int                            任务执行时间间隔
	Error error                             添加任务操作错误(如果任务键已经存在时会出错)
}


// 取消任务回调函数参数结构体
type CancelCbArgs struct {
	key   string                            任务键key
	Error error                             取消任务操作错误(如果任务键本身不存在时会出错)
}


// 定时任务信息
type TaskInfo struct {
	Key      string                         任务键key
	Task     TaskObj                        任务方法
	LastTime time.Time                      最后一次执行任务的时间(未执行过时为time.Time{})
	AddTime  time.Time                      任务添加的时间
	Count    int                            任务执行次数
	Spec     int                            任务执行时间间隔
}


// 定时任务方法
type TaskObj func() (map[string]interface{}, error)


// 添加任务回调函数
type addCallback func(*AddCbArgs)


// 取消任务回调函数
type cancelCallback func(*CancelCbArgs)


// 执行任务回调函数
type executeCallback func(*ExecuteCbArgs)
Demo
	tt := NewTimedTask(10)

	// 添加添加任务回调
	tt.AddAddCallback(func(args *AddCbArgs) {
		if args.Error != nil {
			fmt.Println(fmt.Sprintf("add task: %s ,error msg: %s", args.Key, args.Error))
		} else {
			fmt.Println(fmt.Sprintf("add task: %s", args.Key))
		}
	})

	// 让C任务执行10次后取消
	tt.AddExecuteCallback(func(args *ExecuteCbArgs) {
		if args.Key == "C" && args.Count == 10 {
			tt.Cancel("C")
		}
	})

	// 添加取消任务回调
	tt.AddCancelCallback(func(args *CancelCbArgs) {
		if args.Error == nil {
			fmt.Println("cancel timed task: ", args.Key)
		} else {
			fmt.Println(fmt.Sprintf("cancel timed task:%s ,error msg: %s", args.Key, args.Error))
		}
	})

	// 添加任务A
	tt.Add("A", func() (map[string]interface{}, error) {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "Execute Task `A`")
		return nil, nil
	}, 2)

	// 重复添加任务A
	tt.Add("A", func() (map[string]interface{}, error) {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "Execute Task `A`")
		return nil, nil
	}, 2)

	// 添加任务B
	tt.Add("B", func() (map[string]interface{}, error) {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "Execute Task `B`")
		return nil, nil
	}, 1)

	// 添加任务C
	tt.Add("C", func() (map[string]interface{}, error) {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "Execute Task `C`")
		return nil, nil
	}, 3)

	// 打印时间
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "[Init]")

	// 6秒后取消A
	time.Sleep(time.Second * 6)
	tt.Cancel("A")

	// 6秒后取消B
	time.Sleep(time.Second * 10)
	tt.Cancel("B")

	time.Sleep(time.Hour)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateLocation

func CreateLocation(skip int) *location.Location

func CreateLocationChainReverse

func CreateLocationChainReverse(skip int) []*location.Location

func ErrorLog

func ErrorLog(err *errors.Error, params ...interface{}) error

func ErrorLogWithLocation

func ErrorLogWithLocation(err *errors.Error, invoker []*location.Location, params ...interface{}) error

func FatalLog

func FatalLog(err *errors.Error, params ...interface{}) error

func FatalLogWithLocation

func FatalLogWithLocation(err *errors.Error, invoker []*location.Location, params ...interface{}) error

func GinLog

func GinLog() gin.HandlerFunc

example r.Use(log.GinLog(log, service)) 提供给gin的中间件

func GinLogger

func GinLogger() gin.HandlerFunc

func InfoLog

func InfoLog(info string, params ...interface{})

func InfoLogWithLocation

func InfoLogWithLocation(invoker *location.Location, info string, params ...interface{})

func Init

func Init(environment string, service string)

func InitDefault

func InitDefault()

func Stop

func Stop()

func Timer

func Timer() func() time.Duration

计时器

func WarnLog

func WarnLog(err *errors.Error, params ...interface{}) error

func WarnLogWithLocation

func WarnLogWithLocation(err *errors.Error, invoker []*location.Location, params ...interface{}) error

Types

type BufferLog

type BufferLog struct {
	// contains filtered or unexported fields
}

func NewBufferLog

func NewBufferLog(bufferSize int, writer func(msg IMsg)) *BufferLog

func (*BufferLog) Stop

func (c *BufferLog) Stop()

func (*BufferLog) Write

func (c *BufferLog) Write(msg IMsg)

type CbFuncMap

type CbFuncMap struct {
	// contains filtered or unexported fields
}

func NewCbFuncMap

func NewCbFuncMap() *CbFuncMap

func (*CbFuncMap) Add

func (fm *CbFuncMap) Add(i interface{})

func (*CbFuncMap) Del

func (fm *CbFuncMap) Del(i interface{})

func (*CbFuncMap) GetAll

func (fm *CbFuncMap) GetAll(out interface{}) int

type ConsoleLog

type ConsoleLog struct {
	// contains filtered or unexported fields
}

func NewConsoleLog

func NewConsoleLog() *ConsoleLog

func (*ConsoleLog) Stop

func (c *ConsoleLog) Stop()

func (*ConsoleLog) Write

func (c *ConsoleLog) Write(msg IMsg)

type EsLog

type EsLog struct {
	// contains filtered or unexported fields
}

func NewEsLog

func NewEsLog(url string, index string) (*EsLog, error)

func (*EsLog) Stop

func (c *EsLog) Stop()

func (*EsLog) Write

func (c *EsLog) Write(msg IMsg)

type FluentLog

type FluentLog struct {
	// contains filtered or unexported fields
}

func NewFluentLog

func NewFluentLog() *FluentLog

func (*FluentLog) Stop

func (c *FluentLog) Stop()

func (*FluentLog) Write

func (c *FluentLog) Write(msg IMsg)

type GinMsg

type GinMsg struct {
	Service      string        // 服务名
	LogType      Kind          // 日志类型
	ErrorMessage string        // 信息
	CreateTime   time.Time     // 创建时间
	Path         string        // 访问路径
	RawQuery     string        // 参数
	Body         string        // 主题
	Latency      time.Duration // 执行时长
	ClientIP     string        // 请求ip
	StatusCode   int           // HTTP状态码
	Method       string        // 方法名
}

func NewGinMsgByContext

func NewGinMsgByContext(c *gin.Context, service string) *GinMsg

func (*GinMsg) GetLevel

func (msg *GinMsg) GetLevel() Level

func (*GinMsg) GetType

func (msg *GinMsg) GetType() Kind

func (*GinMsg) ToAlarm

func (msg *GinMsg) ToAlarm(attach map[string]interface{}) string

func (*GinMsg) ToColorfulContent

func (msg *GinMsg) ToColorfulContent() string

func (*GinMsg) ToContent

func (msg *GinMsg) ToContent() string

func (*GinMsg) ToJson

func (msg *GinMsg) ToJson() string

func (*GinMsg) ToMap

func (msg *GinMsg) ToMap() map[string]interface{}

type ILog

type ILog interface {
	Write(le IMsg)
	Stop()
}

type IMsg

type IMsg interface {
	GetType() Kind
	GetLevel() Level
	ToContent() string
	ToColorfulContent() string
	ToMap() map[string]interface{}
	ToJson() string
	ToAlarm(attach map[string]interface{}) string
}

type ISchedule

type ISchedule interface {
	GetAddTime() time.Time                    // 获取添加时间
	AddExecuteCount()                         // 添加执行次数 任务执行完毕后调用
	GetExecuteCount() int                     // 获取执行次数
	Expression() (nt time.Time, isValid bool) // 表达式
	ToString() string
}

任务调度接口

type Kind

type Kind = string

type Level

type Level = string
var (
	LevelNone    Level = ""
	LevelInfo    Level = "Info"  // 绿
	LevelWarning Level = "Warn"  // 蓝
	LevelError   Level = "Error" // 黄
	LevelFatal   Level = "Fatal" // 红
)

type LogStashLog

type LogStashLog struct {
	// contains filtered or unexported fields
}
	+---------------------------------------------------------+
	+                                                         +
 +                        LogStashLog					  +
	+                                                         +
	+---------------------------------------------------------+

使用logstash

func NewLogStashLog

func NewLogStashLog(host string, port int, password string, dbname int, poolSize int, listKey string) (*LogStashLog, error)

func (*LogStashLog) Stop

func (c *LogStashLog) Stop()

func (*LogStashLog) Write

func (c *LogStashLog) Write(msg IMsg)

type Logger

type Logger struct {
	Writers []ILog
	Alarm   *alarm.Alarm
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(writers []ILog, _alarm *alarm.Alarm, filters []func(msg IMsg) bool, service string, attach map[string]interface{}) *Logger

func (*Logger) ErrorLog

func (l *Logger) ErrorLog(err *errors.Error, invoker []*location.Location, params ...interface{}) error

错误日志接口

func (*Logger) FatalLog

func (l *Logger) FatalLog(err *errors.Error, invoker []*location.Location, params ...interface{}) error

致命日志接口

func (*Logger) InfoLog

func (l *Logger) InfoLog(invoker []*location.Location, info string, params ...interface{})

日志日志接口

func (*Logger) Log

func (l *Logger) Log(msg IMsg)

通用日志输出接口

func (*Logger) Stop

func (l *Logger) Stop()

func (*Logger) WarnLog

func (l *Logger) WarnLog(err *errors.Error, invoker []*location.Location, params ...interface{}) error

警告日志接口

type MongoLog

type MongoLog struct {
	// contains filtered or unexported fields
}
	+---------------------------------------------------------+
	+                                                         +
 +                        MongoLog 					      +
	+                                                         +
	+---------------------------------------------------------+

使用mongo

func NewMongoLog

func NewMongoLog(
	host string,
	port int,
	dbname string,
	mongodbAuthDB string,
	mongodbUser string,
	mongodbPwd string,
	mongodbAuth bool,
	mongodbCollection string,
) (*MongoLog, error)

func (*MongoLog) Stop

func (c *MongoLog) Stop()

func (*MongoLog) Write

func (c *MongoLog) Write(msg IMsg)

type Msg

type Msg struct {
	Service    string
	LogType    Kind                 // 日志类型
	Locations  []*location.Location // 定位
	Level      Level                // 报错级别
	Error      *errors.Error        // 错误抽象
	LogDetail  string               // 详细信息
	Parameter  []interface{}        // 参数
	CreateTime time.Time            // 创建时间
}

日志信息

func NewErrorMsg

func NewErrorMsg(service string, level Level, err *errors.Error, locations []*location.Location, v ...interface{}) *Msg

创建一个错误日志记录

func NewInfoMsg

func NewInfoMsg(service string, locations []*location.Location, detail string, params ...interface{}) *Msg

创建一个日志记录

func (*Msg) GetLevel

func (msg *Msg) GetLevel() Level

func (*Msg) GetType

func (msg *Msg) GetType() Kind

func (*Msg) ToAlarm

func (msg *Msg) ToAlarm(attach map[string]interface{}) string

func (*Msg) ToColorfulContent

func (msg *Msg) ToColorfulContent() string

func (*Msg) ToContent

func (msg *Msg) ToContent() string

func (*Msg) ToJson

func (msg *Msg) ToJson() string

func (*Msg) ToMap

func (msg *Msg) ToMap() map[string]interface{}

type SpecSchedule

type SpecSchedule struct {
	// contains filtered or unexported fields
}

指定时长循环调度

func NewSpecSchedule

func NewSpecSchedule(addTime time.Time, count int, spec time.Duration) *SpecSchedule

func (*SpecSchedule) AddExecuteCount

func (p *SpecSchedule) AddExecuteCount()

func (*SpecSchedule) Expression

func (p *SpecSchedule) Expression() (nt time.Time, isValid bool)

func (*SpecSchedule) GetAddTime

func (p *SpecSchedule) GetAddTime() time.Time

func (*SpecSchedule) GetExecuteCount

func (p *SpecSchedule) GetExecuteCount() int

func (*SpecSchedule) ToString

func (p *SpecSchedule) ToString() string

type SpecTimeSchedule

type SpecTimeSchedule struct {
	// contains filtered or unexported fields
}

指定时长指定次数调度器

func NewSpecTimeSchedule

func NewSpecTimeSchedule(spec time.Duration, limit int) *SpecTimeSchedule

func (*SpecTimeSchedule) AddExecuteCount

func (p *SpecTimeSchedule) AddExecuteCount()

func (*SpecTimeSchedule) Expression

func (p *SpecTimeSchedule) Expression() (nt time.Time, isValid bool)

func (*SpecTimeSchedule) GetAddTime

func (p *SpecTimeSchedule) GetAddTime() time.Time

func (*SpecTimeSchedule) GetExecuteCount

func (p *SpecTimeSchedule) GetExecuteCount() int

func (*SpecTimeSchedule) ToString

func (p *SpecTimeSchedule) ToString() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL