index.go 5.68 KB
package lxalilog

import (
	"fmt"
	"os"
	"os/signal"
	"runtime"
	"strings"
	"time"

	sls "github.com/aliyun/aliyun-log-go-sdk"

	"github.com/aliyun/aliyun-log-go-sdk/producer"
	"github.com/astaxie/beego/logs"
	lconv "github.com/lixu-any/go-tools/conv"
	ltime "github.com/lixu-any/go-tools/time"
)

var (
	LXAliProducer      *producer.Producer
	LXAliDefaultConfig MapAlilogConfig //默认配置
)

type MapAlilogConfig struct {
	Endpoint        string
	AccessKeyId     string
	AppNaame        string
	AccessKeySecret string
	Project         string
	On              string
	Debug           string

	TableError string
	TableDebug string
	Env        string
}

// 初始化阿里云日志
func InitAliLog(config MapAlilogConfig) {

	LXAliDefaultConfig = config

	if config.On != "1" {
		return
	}

	producerConfig := producer.GetDefaultProducerConfig()

	producerConfig.Endpoint = config.Endpoint
	producerConfig.AccessKeyID = config.AccessKeyId
	producerConfig.AccessKeySecret = config.AccessKeySecret

	LXAliProducer = producer.InitProducer(producerConfig)

	ch := make(chan os.Signal)

	signal.Notify(ch)

	LXAliProducer.Start()

	//LXAliProducer.SafeClose() // 安全关闭
}

func FormatLog(f interface{}, v ...interface{}) string {
	return formatLog(f, v)
}

func formatLog(f interface{}, v ...interface{}) string {
	var msg string
	switch f := f.(type) {
	case string:
		msg = f
		if len(v) == 0 {
			return msg
		}
		if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") {
			//format string
		} else {
			//do not contain format char
			msg += strings.Repeat(" %v", len(v))
		}
	default:
		msg = fmt.Sprint(f)
		if len(v) == 0 {
			return msg
		}
		msg += strings.Repeat(" %v", len(v))
	}
	return fmt.Sprintf(msg, v...)
}

// 写日志到阿里云
func Writelog(s string, topic string, ip string, config map[string]string) (err error) {

	if LXAliDefaultConfig.On != "1" {
		return
	}

	if LXAliDefaultConfig.Env != "" {
		config["env"] = LXAliDefaultConfig.Env
	}

	log := producer.GenerateLog(uint32(time.Now().Unix()), config)

	err = LXAliProducer.SendLog(LXAliDefaultConfig.Project, s, topic, ip, log)

	if err != nil {
		return
	}

	return

}

// 获取正在运行的函数名
func runFuncName(l int) (string, string, int) {

	pc, file, line, _ := runtime.Caller(l)

	name := runtime.FuncForPC(pc).Name()

	split := strings.Split(name, ".")

	funname := split[len(split)-1]

	return funname, file, line
}

// ErrorCode 错误日志
func ErrorCode(code interface{}, v ...interface{}) {

	funname, file, line := runFuncName(3)

	logd := make(map[string]string)

	logd["fun"] = funname

	logd["file"] = file

	logd["app"] = LXAliDefaultConfig.AppNaame

	logd["line"] = fmt.Sprintf("%d", line)

	logd["msg"] = formatLog(code, v)

	logd["time"] = lconv.Int64ToStr(ltime.UninxTime())

	logs.Error("file::", file, ",line::", line, ",fun::", funname, "[", logd["msg"], "],time::", logd["time"])

	if LXAliDefaultConfig.TableError != "" {
		go Writelog(LXAliDefaultConfig.TableError, funname, "127.0.0.1", logd)
	}

}

// 错误日志
func Errors(f interface{}, v ...interface{}) {

	funname, file, line := runFuncName(2)

	logd := make(map[string]string)

	logd["fun"] = funname

	logd["file"] = file

	logd["app"] = LXAliDefaultConfig.AppNaame

	logd["line"] = fmt.Sprintf("%d", line)

	logd["msg"] = formatLog(f, v)

	logd["time"] = lconv.Int64ToStr(ltime.UninxTime())

	logs.Error("file::", file, ",line::", line, ",fun::", funname, "[", logd["msg"], "],time::", logd["time"])

	if LXAliDefaultConfig.TableError != "" {
		go Writelog(LXAliDefaultConfig.TableError, funname, "127.0.0.1", logd)
	}

}

// 调试日志
func Debug(f interface{}, v ...interface{}) {

	funname, file, line := runFuncName(2)

	logd := make(map[string]string)

	logd["fun"] = funname

	logd["file"] = file

	logd["app"] = LXAliDefaultConfig.AppNaame

	logd["line"] = fmt.Sprintf("%d", line)

	logd["msg"] = formatLog(f, v)

	logd["time"] = lconv.Int64ToStr(ltime.UninxTime())

	logs.Debug("file::", file, ",line::", line, ",fun::", funname, "[", logd["msg"], "],time::", logd["time"])

	if LXAliDefaultConfig.Debug == "1" && LXAliDefaultConfig.TableDebug != "" {
		go Writelog(LXAliDefaultConfig.TableDebug, funname, "127.0.0.1", logd)
	}
}

type LogParams struct {
	Project  string
	PowerSql bool
}

// 查询日志
func GetLog(logname, sql string, starttime, endtime int64, nums int64, p ...LogParams) (lst []map[string]string, err error) {

	var dproject = LXAliDefaultConfig.Project

	if len(p) > 0 {
		if p[0].Project != "" {
			dproject = p[0].Project
		}
	}

	// 创建日志服务Client。
	client := sls.CreateNormalInterface(LXAliDefaultConfig.Endpoint, LXAliDefaultConfig.AccessKeyId, LXAliDefaultConfig.AccessKeySecret, "")

	resp, err := client.GetLogs(dproject, logname, "", starttime, endtime, sql, nums, 0, true)
	if err != nil {
		return
	}

	logs := resp.Logs
	for i := range logs {
		var item = make(map[string]string)
		for k, v := range logs[i] {
			item[k] = v
		}
		lst = append(lst, item)
	}

	return
}

func GetLog1(logname, sql string, starttime, endtime int64, nums int64, pas int64) (lst []map[string]string, err error) {

	// 创建日志服务Client。
	client := sls.CreateNormalInterface(LXAliDefaultConfig.Endpoint, LXAliDefaultConfig.AccessKeyId, LXAliDefaultConfig.AccessKeySecret, "")

	resp, err := client.GetLogs(LXAliDefaultConfig.Project, logname, "", starttime, endtime, sql, nums, pas*nums, true)
	if err != nil {
		return
	}

	logs := resp.Logs
	for i := range logs {
		var item = make(map[string]string)
		for k, v := range logs[i] {
			item[k] = v
		}
		lst = append(lst, item)
	}

	return
}

func GetLogV2(logname, sql string, starttime, endtime int64, nums int64, pas int64) (lst []map[string]string, err error) {
	return GetLog1(logname, sql, starttime, endtime, nums, pas)
}