123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package ctrl_v1
- import (
- "context"
- "gd_management_gateway/common.in/jsonrpc2"
- "gd_management_gateway/errors"
- "gd_management_gateway/params/param_base"
- "gd_management_gateway/params/param_v1_0"
- "gd_management_gateway/rpc_apis"
- "gd_management_gateway/rpc_apis/gd_statistics"
- "gd_management_gateway/rpc_apis/gd_management"
- "fmt"
- "strconv"
- "strings"
- "sync"
- "time"
- "gd_management_gateway/common.in/cache"
- "gd_management_gateway/common.in/httper"
- "gd_management_gateway/common.in/task"
- "gd_management_gateway/common.in/utils"
- "github.com/astaxie/beego"
- "github.com/tealeg/xlsx"
- "go.uber.org/zap"
- )
- const exportPath = "/export/"
- var ServerPort = "61002"
- var ServerIp = ""
- // Operations about access log api
- type BaseAccessLogController struct {
- metadata interface{} // 中继元数据
- beego.Controller
- LogID string
- }
- // SetPercentForXlsx 单元格设置百分率
- func SetPercentForXlsx(percent string, cell *xlsx.Cell) {
- s := strings.TrimRight(percent, "%")
- // 对零单独处理
- f, _ := strconv.ParseFloat(s, 64)
- if f == 0 {
- cell.SetFloatWithFormat(0.0000, "0.00%")
- return
- }
- // 将百分比转为小数形式
- f = f / 100.0000
- fstring := strconv.FormatFloat(f, 'f', 4, 64)
- ffloat, _ := strconv.ParseFloat(fstring, 64)
- // 设置单元格
- cell.SetFloatWithFormat(ffloat, "0.00%")
- }
- // @Title 访问日志
- // @Description 访问日志
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param state query int false "接口调用返回状态"
- // @Param code query string false "接口调用返回状态"
- // @Param request_param query string false "请求参数"
- // @Param search query string false "关键字"
- // @Param merchant_id query int64 false "商户id"
- // @Param api_id query int64 false "基础api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Param page_size query int64 false "页大小"
- // @Param page_number query int64 false "页号"
- // @Param min query float64 false "最小耗时"
- // @Param max query float64 false "最大耗时"
- // @Success 200 {object} params.param_v1_0.LogQueryAccessLogResp "响应信息"
- // @Failure 500 服务器错误
- // @router /access_log [get]
- func (u *BaseAccessLogController) LogQueryAccessLog() {
- u.LogID = fmt.Sprintf("LogQueryAccessLog[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryAccessLogReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryAccessLogReq{}
- mreq.PageNumber = req.PageNumber
- mreq.PageSize = req.PageSize
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ApiId = req.ApiId
- mreq.MerchantId = req.MerchantId
- mreq.State = req.State
- mreq.Code = req.Code
- mreq.RequestParam = req.RequestParam
- mreq.Search = req.Search
- mreq.Max = req.Max
- mreq.Min = req.Min
- reply, err := rpc_apis.Statistics.LogQueryAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryAccessLog"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryAccessLogResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 数据源日志
- // @Description 数据源日志
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param state query int false "接口调用返回状态"
- // @Param search query string false "关键字"
- // @Param request_param query string false "请求参数"
- // @Param provider_id query int64 false "三方平台id"
- // @Param provider_api_id query int64 false "三方api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Param page_size query int64 false "页大小"
- // @Param page_number query int64 false "页号"
- // @Param min query float64 false "最小耗时"
- // @Param max query float64 false "最大耗时"
- // @Param raw_code query string false "原始错误码"
- // @Success 200 {object} params.param_v1_0.LogQueryThirdpartAccessLogResp "响应信息"
- // @Failure 500 服务器错误
- // @router /thirdpart_access_log [get]
- func (u *BaseAccessLogController) LogQueryThirdpartAccessLog() {
- u.LogID = fmt.Sprintf("LogQueryThirdpartAccessLog[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryThirdpartAccessLogReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryThirdpartAccessLogReq{}
- mreq.EndTimestamp = req.EndTimestamp
- mreq.StartTimestamp = req.StartTimestamp
- mreq.PageSize = req.PageSize
- mreq.PageNumber = req.PageNumber
- mreq.ProviderApiId = req.ProviderApiId
- mreq.ProviderId = req.ProviderId
- mreq.State = req.State
- mreq.RequestParam = req.RequestParam
- mreq.Search = req.Search
- mreq.Max = req.Max
- mreq.Min = req.Min
- mreq.RawCode = req.RawCode
- fmt.Println("raw code:",mreq.RawCode,req.RawCode)
- reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryThirdpartAccessLog"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryThirdpartAccessLogResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 访问日志统计
- // @Description 访问日志统计
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param merchant_id query int64 false "商户id"
- // @Param api_id query int64 false "基础api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Param page_size query int64 false "页大小"
- // @Param page_number query int64 false "页号"
- // @Success 200 {object} params.param_v1_0.LogQueryAccessLogCountResp "响应信息"
- // @Failure 500 服务器错误
- // @router /access_log_count [get]
- func (u *BaseAccessLogController) LogQueryAccessLogCount() {
- u.LogID = fmt.Sprintf("LogQueryAccessLogCount[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryAccessLogCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryAccessLogCountReq{}
- mreq.PageNumber = req.PageNumber
- mreq.PageSize = req.PageSize
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ApiId = req.ApiId
- mreq.MerchantId = req.MerchantId
- reply, err := rpc_apis.Statistics.LogQueryAccessLogCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryAccessLogCount"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryAccessLogCountResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 数据源查询统计
- // @Description 数据源查询统
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param provider_id query int64 false "三方平台id"
- // @Param provider_api_id query int64 false "三方api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Param page_size query int64 false "页大小"
- // @Param page_number query int64 false "页号"
- // @Success 200 {object} params.param_v1_0.LogQueryThirdpartAccessLogCountResp "响应信息"
- // @Failure 500 服务器错误
- // @router /thirdpart_accesslog_count [get]
- func (u *BaseAccessLogController) LogQueryThirdpartAccessLogCount() {
- u.LogID = fmt.Sprintf("LogQueryThirdpartAccessLogCount[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryThirdpartAccessLogCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryThirdpartAccessLogCountReq{}
- mreq.EndTimestamp = req.EndTimestamp
- mreq.StartTimestamp = req.StartTimestamp
- mreq.PageSize = req.PageSize
- mreq.PageNumber = req.PageNumber
- mreq.ProviderApiId = req.ProviderApiId
- mreq.ProviderId = req.ProviderId
- reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessLogCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryThirdpartAccessLogCount"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryThirdpartAccessLogCountResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 访问日志关联数据源日志
- // @Description 访问日志关联数据源日志
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param access_id query int true "访问日志id"
- // @Param create_time query string true "时间"
- // @Success 200 {object} params.param_v1_0.LogQueryAccessLogThirdpartLogResp "响应信息"
- // @Failure 500 服务器错误
- // @router /access_log_get_thirdpart_log [get]
- func (u *BaseAccessLogController) LogQueryAccessLogThirdpartLog() {
- u.LogID = fmt.Sprintf("LogQueryAccessLogThirdpartLog[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryAccessLogThirdpartLogReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryAccessLogThirdpartLogReq{}
- mreq.AccessId = req.AccessId
- if req.CreateTime != "" {
- timeLayout := "2006-01-02"
- loc, _ := time.LoadLocation("Local")
- array := strings.Split(req.CreateTime, " ")
- t, _ := time.ParseInLocation(timeLayout, array[0], loc)
- mreq.Timestamp = t.Unix()
- }
- reply, err := rpc_apis.Statistics.LogQueryAccessLogThirdpartLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryAccessLogThirdpartLog"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryAccessLogThirdpartLogResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 访问日志用户统计报表
- // @Description 访问日志用户统计报表
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param merchant_id query int64 false "商户id"
- // @Param api_id query int64 false "基础api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Param page_size query int64 false "页大小"
- // @Param page_number query int64 false "页号"
- // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountResp "响应信息"
- // @Failure 500 服务器错误
- // @router /user_access_count [get]
- func (u *BaseAccessLogController) LogQueryUserAccessCount() {
- u.LogID = fmt.Sprintf("LogQueryUserAccessCount[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryUserAccessCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryUserAccessCountReq{}
- mreq.PageNumber = req.PageNumber
- mreq.PageSize = req.PageSize
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ApiId = req.ApiId
- mreq.MerchantId = req.MerchantId
- reply, err := rpc_apis.Statistics.LogQueryUserAccessCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryUserAccessCount"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryUserAccessCountResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 访问日志接口统计详情
- // @Description 访问日志接口统计详情
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param merchant_id query int64 false "商户id"
- // @Param api_id query int64 false "基础api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Success 200 {object} params.param_v1_0.LogQueryInterfaceCountResp "响应信息"
- // @Failure 500 服务器错误
- // @router /access_log_interface_count [get]
- func (u *BaseAccessLogController) LogQueryInterfaceCount() {
- u.LogID = fmt.Sprintf("LogQueryInterfaceCount[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryInterfaceCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryInterfaceCountReq{}
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ApiId = req.ApiId
- mreq.MerchantId = req.MerchantId
- reply, err := rpc_apis.Statistics.LogQueryInterfaceCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryInterfaceCount"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryInterfaceCountResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 数据源接口用量统计
- // @Description 数据源接口用量统计
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param provider_api_id query int64 false "数据源api id"
- // @Param time query int64 false "时间"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Success 200 {object} params.param_v1_0.LogQueryThirdpartAccessCountResp "响应信息"
- // @Failure 500 服务器错误
- // @router /thirdpart_access_count [get]
- func (u *BaseAccessLogController) LogQueryThirdpartAccessCount() {
- u.LogID = fmt.Sprintf("LogQueryInterfaceCount[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryThirdpartAccessCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryThirdpartAccessCountReq{}
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ProviderApiId = req.ProviderApiId
- if req.Time > 0 {
- mreq.Time = time.Unix(req.Time, 0).Format("2006-01-02")
- }
- reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryThirdpartAccessCount"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryThirdpartAccessCountResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 数据源接口统计报表
- // @Description 数据源接口统计报表
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param provider_api_id query int64 false "数据源api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Param page_size query int64 false "页大小"
- // @Param page_number query int64 false "页号"
- // @Success 200 {object} params.param_v1_0.LogQueryThirdpartInterfaceCountResp "响应信息"
- // @Failure 500 服务器错误
- // @router /thirdpart_access_interface_count [get]
- func (u *BaseAccessLogController) LogQueryThirdpartInterfaceCount() {
- u.LogID = fmt.Sprintf("LogQueryThirdpartInterfaceCount[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryThirdpartInterfaceCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryThirdpartInterfaceCountReq{}
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ProviderApiId = req.ProviderApiId
- mreq.PageNumber = req.PageNumber
- mreq.PageSize = req.PageSize
- reply, err := rpc_apis.Statistics.LogQueryThirdpartInterfaceCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryThirdpartInterfaceCount"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryThirdpartInterfaceCountResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- func ExportUpdate(u *BaseAccessLogController, exportReq *gd_statistics.LogExportCreateReq) {
- _, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), exportReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportCreate"),
- zap.String("args", utils.MarshalJsonString(exportReq)),
- zap.String("error", err.Error()))
- }
- }
- var ErrCodeMutex sync.Mutex
- var ErrorCodeMap = map[string]string{}
- func IsErrorCodeMapExist() bool {
- ErrCodeMutex.Lock()
- defer ErrCodeMutex.Unlock()
- if len(ErrorCodeMap) > 0 {
- return true
- }
- return false
- }
- func SetErrorCodeMap() {
- ErrCodeMutex.Lock()
- defer ErrCodeMutex.Unlock()
- mreq := gd_management.ManagementGetErrorListReq{}
- mreq.PageNumber = 1
- mreq.IsAll = true
- reply, err := rpc_apis.Management.ManagementGetErrorList(context.Background(), &mreq)
- if err != nil {
- return
- }
- ErrorCodeMap = map[string]string{}
- for _, v := range reply.ErrorCodeList {
- ErrorCodeMap[v.Code] = v.Msg
- }
- }
- func makeXlsxErrorHeader(sheet *xlsx.Sheet, codes []gd_statistics.ErrorCodeCount) {
- if IsErrorCodeMapExist() == false {
- SetErrorCodeMap()
- }
- row := sheet.AddRow()
- cell := row.AddCell()
- cell.Value = "日期"
- cell = row.AddCell()
- cell.Value = "错误总量"
- for _, v := range codes {
- cell := row.AddCell()
- if msg, ok := ErrorCodeMap[v.Code]; ok {
- cell.Value = fmt.Sprintf("%s(%s)", v.Code, msg)
- } else {
- cell.Value = v.Code
- }
- cell = row.AddCell()
- cell.Value = v.Code + "占比"
- }
- }
- func makeXlsxSourceHeader(sheet *xlsx.Sheet, names []gd_statistics.SourceNameCount) {
- row := sheet.AddRow()
- cell := row.AddCell()
- cell.Value = "日期"
- cell = row.AddCell()
- cell.Value = "来源总量"
- for _, v := range names {
- cell := row.AddCell()
- cell.Value = v.Name
- cell = row.AddCell()
- cell.Value = v.Name + "占比"
- }
- }
- func makeXlsxHeader(sheet *xlsx.Sheet, timeList string) {
- tArray := strings.Split(timeList, ",")
- row := sheet.AddRow()
- dateCell := row.AddCell()
- dateCell.Value = "时间"
- //dateCell.HMerge
- dateCell.VMerge = 1
- cell := row.AddCell()
- cell.Value = "总调用量情况"
- cell.HMerge = 4
- row.AddCell()
- row.AddCell()
- row.AddCell()
- row.AddCell()
- cell = row.AddCell()
- cell.Value = "有效调用量情况"
- cell.HMerge = 10
- if len(tArray) > 0 && tArray[0] != "" {
- cell.HMerge += len(tArray)
- }
- row = sheet.AddRow()
- row.AddCell()
- totalCell := row.AddCell()
- totalCell.Value = "调用总量"
- validCell := row.AddCell()
- validCell.Value = "有效量"
- validRateCell := row.AddCell()
- validRateCell.Value = "有效率"
- chargeCell := row.AddCell()
- chargeCell.Value = "计费量"
- chargeRateCell := row.AddCell()
- chargeRateCell.Value = "计费率"
- successCell := row.AddCell()
- successCell.Value = "成功量"
- successRateCell := row.AddCell()
- successRateCell.Value = "成功率"
- queryCell := row.AddCell()
- queryCell.Value = "查得量"
- queryRateCell := row.AddCell()
- queryRateCell.Value = "查得率"
- reuseCell := row.AddCell()
- reuseCell.Value = "复用量"
- reuseRateCell := row.AddCell()
- reuseRateCell.Value = "复用率"
- platformErrorCell := row.AddCell()
- platformErrorCell.Value = "平台异常量"
- platformErrorRateCell := row.AddCell()
- platformErrorRateCell.Value = "平台异常率"
- providerErrorCell := row.AddCell()
- providerErrorCell.Value = "数据源异常量"
- providerErrorRateCell := row.AddCell()
- providerErrorRateCell.Value = "数据源异常率"
- avgElapsedCell := row.AddCell()
- avgElapsedCell.Value = "平均时长"
- offset := 17
- for i, v := range tArray {
- if v == "" {
- return
- }
- cell := row.AddCell()
- cell.Value = fmt.Sprintf("时长大于%s秒", v)
- sheet.SetColWidth(17+i, 17+i, 20)
- offset++
- }
- for i, v := range tArray {
- if v == "" {
- return
- }
- cell := row.AddCell()
- cell.Value = fmt.Sprintf("计费调用中时长大于%s秒", v)
- sheet.SetColWidth(offset+i, offset+i, 30)
- }
- }
- func makeProviderXlsxHeader(sheet *xlsx.Sheet, timeList string) {
- row := sheet.AddRow()
- dateCell := row.AddCell()
- dateCell.Value = "时间"
- nameCell := row.AddCell()
- nameCell.Value = "供应商"
- totalCell := row.AddCell()
- totalCell.Value = "总量"
- successCell := row.AddCell()
- successCell.Value = "成功"
- failCell := row.AddCell()
- failCell.Value = "失败"
- failRateCell := row.AddCell()
- failRateCell.Value = "失败率"
- queryCell := row.AddCell()
- queryCell.Value = "查得"
- queryNoRecordCell := row.AddCell()
- queryNoRecordCell.Value = "查无"
- queryNoRecordRateCell := row.AddCell()
- queryNoRecordRateCell.Value = "查无率"
- avgElapsedCell := row.AddCell()
- avgElapsedCell.Value = "平均时长"
- tArray := strings.Split(timeList, ",")
- for _, v := range tArray {
- if v == "" {
- break
- }
- cell := row.AddCell()
- cell.Value = fmt.Sprintf("时长大于%s秒", v)
- }
- for _, v := range tArray {
- if v == "" {
- break
- }
- cell := row.AddCell()
- cell.Value = fmt.Sprintf("计费调用中时长大于%s秒", v)
- }
- }
- func parseSumRate(rate string) string {
- array := strings.Split(rate, "-")
- total := float64(0)
- for _, v := range array {
- valuestring := strings.TrimRight(v, "%")
- value, _ := strconv.ParseFloat(valuestring, 64)
- total += value
- }
- ret := strconv.FormatFloat(float64(total)/float64(len(array)), 'f', 3, 64) + "%"
- return ret
- }
- func parseSum(sum *gd_statistics.LogQueryUserAcessCountExport, sheet *xlsx.Sheet) {
- row := sheet.AddRow()
- if sum.Total == 0 {
- sum.ValidRate = "0%"
- sum.ChargeRate = "0%"
- } else {
- sum.ValidRate = strconv.FormatFloat(float64(100*sum.Valid)/float64(sum.Total), 'f', 2, 64) + "%"
- sum.ChargeRate = strconv.FormatFloat(float64(100*sum.Charge)/float64(sum.Total), 'f', 2, 64) + "%"
- }
- if sum.Valid == 0 {
- sum.QueryRate = "0%"
- sum.SuccessRate = "0%"
- sum.ReuseRate = "0%"
- } else {
- sum.QueryRate = strconv.FormatFloat(float64(100*sum.Query)/float64(sum.Valid), 'f', 2, 64) + "%"
- sum.SuccessRate = strconv.FormatFloat(float64(100*sum.Success)/float64(sum.Valid), 'f', 2, 64) + "%"
- sum.ReuseRate = strconv.FormatFloat(float64(100*sum.Reuse)/float64(sum.Valid), 'f', 2, 64) + "%"
- sum.PlatformErrorRate = strconv.FormatFloat(float64(100*sum.PlatformError)/float64(sum.Valid), 'f', 2, 64) + "%"
- sum.ProviderErrorRate = strconv.FormatFloat(float64(100*sum.ProviderError)/float64(sum.Valid), 'f', 2, 64) + "%"
- }
- dateCell := row.AddCell()
- dateCell.Value = sum.Date
- totalCell := row.AddCell()
- totalCell.SetInt(int(sum.Total))
- validCell := row.AddCell()
- validCell.SetInt(int(sum.Valid))
- validRateCell := row.AddCell()
- validRateCell.Value = sum.ValidRate
- SetPercentForXlsx(sum.ValidRate, validRateCell)
- chargeCell := row.AddCell()
- chargeCell.SetInt(sum.Charge)
- chargeRateCell := row.AddCell()
- SetPercentForXlsx(sum.ChargeRate, chargeRateCell)
- successCell := row.AddCell()
- successCell.SetInt(sum.Success)
- successRateCell := row.AddCell()
- SetPercentForXlsx(sum.SuccessRate, successRateCell)
- queryCell := row.AddCell()
- queryCell.SetInt(sum.Query)
- queryRateCell := row.AddCell()
- SetPercentForXlsx(sum.QueryRate, queryRateCell)
- reuseCell := row.AddCell()
- reuseCell.SetInt(sum.Reuse)
- reuseRateCell := row.AddCell()
- SetPercentForXlsx(sum.ReuseRate, reuseRateCell)
- platformErrorCell := row.AddCell()
- platformErrorCell.SetInt(sum.PlatformError)
- platformErrorRateCell := row.AddCell()
- SetPercentForXlsx(sum.PlatformErrorRate, platformErrorRateCell)
- providerErrorCell := row.AddCell()
- providerErrorCell.SetInt(sum.ProviderError)
- providerErrorRateCell := row.AddCell()
- SetPercentForXlsx(sum.ProviderErrorRate, providerErrorRateCell)
- avgElapsedCell := row.AddCell()
- sum.AvgElapsed = sum.SumElapsed / float64(sum.Total)
- elStr := strconv.FormatFloat(sum.AvgElapsed, 'f', 2, 64)
- el, _ := strconv.ParseFloat(elStr, 64)
- avgElapsedCell.SetFloatWithFormat(el, "0.00")
- for _, v := range sum.BigElapsedList {
- cell := row.AddCell()
- cell.SetInt(v)
- }
- for _, v := range sum.ChargeBigElapsedList {
- cell := row.AddCell()
- cell.SetInt(v)
- }
- }
- func parseProviderSum(sum *gd_statistics.LogQueryProviderCountExport, sheet *xlsx.Sheet) {
- row := sheet.AddRow()
- if sum.Total == 0 {
- sum.FailedRate = "0%"
- sum.QueryNoRecordRate = "0%"
- } else {
- sum.FailedRate = strconv.FormatFloat(float64(100*sum.Failed)/float64(sum.Total), 'f', 2, 64) + "%"
- sum.QueryNoRecordRate = strconv.FormatFloat(float64(100*sum.QueryNoRecord)/float64(sum.Total), 'f', 2, 64) + "%"
- }
- dateCell := row.AddCell()
- dateCell.Value = sum.Date
- nameCell := row.AddCell()
- nameCell.Value = " "
- totalCell := row.AddCell()
- totalCell.SetInt(int(sum.Total))
- successCell := row.AddCell()
- successCell.SetInt(int(sum.Success))
- failedCell := row.AddCell()
- failedCell.SetInt(int(sum.Failed))
- failedRateCell := row.AddCell()
- SetPercentForXlsx(sum.FailedRate, failedRateCell)
- queryCell := row.AddCell()
- queryCell.SetInt(int(sum.Query))
- queryNoRecordCell := row.AddCell()
- queryNoRecordCell.SetInt(int(sum.QueryNoRecord))
- queryNoRecordRateCell := row.AddCell()
- SetPercentForXlsx(sum.QueryNoRecordRate, queryNoRecordRateCell)
- avgElapsedCell := row.AddCell()
- elStr := strconv.FormatFloat(sum.SumElapsed/float64(sum.Total), 'f', 2, 64)
- el, _ := strconv.ParseFloat(elStr, 64)
- avgElapsedCell.SetFloatWithFormat(el, "0.00")
- for _, v := range sum.BigElapsedList {
- cell := row.AddCell()
- cell.SetInt(v)
- }
- for _, v := range sum.ChargeBigElapsedList {
- cell := row.AddCell()
- cell.SetInt(v)
- }
- }
- func parseErrorsCount(reply *gd_statistics.LogQueryUserAccessCountExportReply, file *xlsx.File) error {
- table := make(map[string][]gd_statistics.ErrorExport, 0)
- for index, _ := range reply.ErrorCount {
- table[reply.ErrorCount[index].ApiName] = append(table[reply.ErrorCount[index].ApiName], reply.ErrorCount[index])
- }
- if len(table) == 0 {
- file.AddSheet("空")
- }
- for k, v := range table {
- sheet, err := file.AddSheet(k + "失败分布")
- if err != nil {
- return err
- }
- makeXlsxErrorHeader(sheet, v[0].Errors)
- sumTotal := 0
- sumRate := make([]gd_statistics.ErrorCodeCount, len(v[0].Errors))
- for index, _ := range v {
- row := sheet.AddRow()
- cell := row.AddCell()
- cell.Value = v[index].Date
- cell = row.AddCell()
- cell.Value = fmt.Sprintf("%d", v[index].Total)
- sumTotal += v[index].Total
- for i := 0; i < len(v[index].Errors); i++ {
- cell := row.AddCell()
- cell.Value = fmt.Sprintf("%d", v[index].Errors[i].Count)
- cell = row.AddCell()
- cell.Value = v[index].Errors[i].Rate
- sumRate[i].Count += v[index].Errors[i].Count
- }
- }
- row := sheet.AddRow()
- cell := row.AddCell()
- cell.Value = "总"
- cell = row.AddCell()
- cell.Value = fmt.Sprintf("%d", sumTotal)
- for i := 0; i < len(sumRate); i++ {
- cell = row.AddCell()
- cell.Value = fmt.Sprintf("%d", sumRate[i].Count)
- cell = row.AddCell()
- cell.Value = strconv.FormatFloat(float64(100*sumRate[i].Count)/float64(sumTotal), 'f', 2, 64) + "%"
- }
- }
- return nil
- }
- func parseSourceCount(reply *gd_statistics.LogQueryUserAccessCountExportReply, file *xlsx.File) error {
- table := make(map[string][]gd_statistics.SourceExport, 0)
- for index, _ := range reply.SourceCount {
- table[reply.SourceCount[index].ApiName] = append(table[reply.SourceCount[index].ApiName], reply.SourceCount[index])
- }
- if len(table) == 0 {
- file.AddSheet("空")
- }
- for k, v := range table {
- sheet, err := file.AddSheet(k + "来源分布")
- if err != nil {
- return err
- }
- makeXlsxSourceHeader(sheet, v[0].Sources)
- sumTotal := 0
- sumRate := make([]gd_statistics.SourceNameCount, len(v[0].Sources))
- for index, _ := range v {
- row := sheet.AddRow()
- cell := row.AddCell()
- cell.Value = v[index].Date
- cell = row.AddCell()
- cell.Value = fmt.Sprintf("%d", v[index].Total)
- sumTotal += v[index].Total
- for i := 0; i < len(v[index].Sources); i++ {
- cell := row.AddCell()
- cell.Value = fmt.Sprintf("%d", v[index].Sources[i].Count)
- cell = row.AddCell()
- cell.Value = v[index].Sources[i].Rate
- sumRate[i].Count += v[index].Sources[i].Count
- }
- }
- row := sheet.AddRow()
- cell := row.AddCell()
- cell.Value = "总"
- cell = row.AddCell()
- cell.Value = fmt.Sprintf("%d", sumTotal)
- for i := 0; i < len(sumRate); i++ {
- cell = row.AddCell()
- cell.Value = fmt.Sprintf("%d", sumRate[i].Count)
- cell = row.AddCell()
- cell.Value = strconv.FormatFloat(float64(100*sumRate[i].Count)/float64(sumTotal), 'f', 2, 64) + "%"
- }
- }
- return nil
- }
- func sumBigElapseds(oldList []int, newList []int) []int {
- if len(oldList) == 0 {
- return newList
- }
- if len(oldList) != len(newList) {
- return oldList
- }
- for i, _ := range oldList {
- oldList[i] = oldList[i] + newList[i]
- }
- return oldList
- }
- func setAllCells(file *xlsx.File) {
- style := xlsx.NewStyle()
- font := xlsx.NewFont(10, "Microsoft YaHei")
- style.Font = *font
- style.Border = *xlsx.NewBorder("thin", "none", "thin", "thin")
- headerStyle := xlsx.NewStyle()
- fill := xlsx.NewFill("solid", "00B0C4DE", "00000000")
- headerStyle.Font = *font
- headerStyle.Fill = *fill
- headerStyle.Border = *xlsx.NewBorder("thin", "none", "thin", "thin")
- sheets := file.Sheets
- for i := 0; i < len(sheets); i++ {
- rows := sheets[i].Rows
- for j := 0; j < len(rows); j++ {
- cells := rows[j].Cells
- for k := 0; k < len(cells); k++ {
- if j < 2 {
- cells[k].SetStyle(headerStyle)
- } else {
- cells[k].SetStyle(style)
- }
- }
- }
- }
- }
- func parseAccessCount(reply *gd_statistics.LogQueryUserAccessCountExportReply, file *xlsx.File, timeList string) error {
- table := make(map[string][]gd_statistics.LogQueryUserAcessCountExport, 0)
- for index, _ := range reply.LogQueryUserAcessCount {
- table[reply.LogQueryUserAcessCount[index].ApiName] = append(table[reply.LogQueryUserAcessCount[index].ApiName], reply.LogQueryUserAcessCount[index])
- }
- if len(table) == 0 {
- file.AddSheet("空")
- }
- for k, v := range table {
- sheet, err := file.AddSheet(k + "指标")
- if err != nil {
- return err
- }
- makeXlsxHeader(sheet, timeList)
- sum := gd_statistics.LogQueryUserAcessCountExport{}
- sum.Date = "总"
- for index, _ := range v {
- row := sheet.AddRow()
- dateCell := row.AddCell()
- dateCell.Value = v[index].Date
- totalCell := row.AddCell()
- sum.Total += int(v[index].Total)
- totalCell.SetInt(int(v[index].Total))
- validCell := row.AddCell()
- sum.Valid += int(v[index].Valid)
- validCell.SetInt(int(v[index].Valid))
- validRateCell := row.AddCell()
- SetPercentForXlsx(v[index].ValidRate, validRateCell)
- chargeCell := row.AddCell()
- sum.Charge += int(v[index].Charge)
- chargeCell.SetInt(int(v[index].Charge))
- chargeRateCell := row.AddCell()
- SetPercentForXlsx(v[index].ChargeRate, chargeRateCell)
- successCell := row.AddCell()
- successCell.SetInt(v[index].Success)
- sum.Success += v[index].Success
- successRateCell := row.AddCell()
- SetPercentForXlsx(v[index].SuccessRate, successRateCell)
- queryCell := row.AddCell()
- queryCell.SetInt(v[index].Query)
- sum.Query += v[index].Query
- queryRateCell := row.AddCell()
- SetPercentForXlsx(v[index].QueryRate, queryRateCell)
- reuseCell := row.AddCell()
- reuseCell.SetInt(v[index].Reuse)
- sum.Reuse += v[index].Reuse
- reuseRateCell := row.AddCell()
- SetPercentForXlsx(v[index].ReuseRate, reuseRateCell)
- platformErrorCell := row.AddCell()
- platformErrorCell.SetInt(v[index].PlatformError)
- sum.PlatformError += v[index].PlatformError
- platformErrorRateCell := row.AddCell()
- SetPercentForXlsx(v[index].PlatformErrorRate, platformErrorRateCell)
- providerErrorCell := row.AddCell()
- providerErrorCell.SetInt(v[index].ProviderError)
- sum.ProviderError += v[index].ProviderError
- providerErrorRateCell := row.AddCell()
- SetPercentForXlsx(v[index].ProviderErrorRate, providerErrorRateCell)
- avgElapsedCell := row.AddCell()
- elStr := strconv.FormatFloat(v[index].AvgElapsed, 'f', 2, 64)
- el, _ := strconv.ParseFloat(elStr, 64)
- avgElapsedCell.SetFloatWithFormat(el, "0.00")
- sum.SumElapsed += v[index].SumElapsed
- for _, big := range v[index].BigElapsedList {
- cell := row.AddCell()
- cell.SetInt(big)
- }
- sum.BigElapsedList = sumBigElapseds(sum.BigElapsedList, v[index].BigElapsedList)
- for _, big := range v[index].ChargeBigElapsedList {
- cell := row.AddCell()
- cell.SetInt(big)
- }
- sum.ChargeBigElapsedList = sumBigElapseds(sum.ChargeBigElapsedList, v[index].ChargeBigElapsedList)
- }
- parseSum(&sum, sheet)
- }
- return nil
- }
- // @Title 访问日志用户统计报表导出
- // @Description 访问日志用户统计报表导出
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param export body rpc_apis.gd_statistics.LogQueryUserAccessCountExportReq true "数据源"
- // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountResp "响应信息"
- // @Failure 500 服务器错误
- // @router /user_access_count_export [post]
- func (u *BaseAccessLogController) LogQueryUserAccessCountExport() {
- u.LogID = fmt.Sprintf("LogQueryUserAccessCountExport[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryUserAccessCountExportReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- exportReq := gd_statistics.LogExportCreateReq{}
- exportReq.Status = "开始"
- exportReq.FileName = req.Export.ExportName
- if exportReq.FileName == "" {
- return errors.ArgsError
- }
- host := u.Ctx.Request.Host
- if strings.Contains(ServerIp, "0.0.0.0") == false {
- host = ServerIp + ":" + ServerPort
- } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
- host = u.Ctx.Request.Host + ":" + ServerPort
- }
- exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
- if true {
- exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
- }
- exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportCreate"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- exportReq.Id = exportReply.Id
- defer ExportUpdate(u, &exportReq)
- mreq := gd_statistics.LogQueryUserAccessCountExportReq{}
- mreq.StartTimestamp = req.Export.StartTimestamp
- mreq.EndTimestamp = req.Export.EndTimestamp
- mreq.ApiIdList = req.Export.ApiIdList
- mreq.MerchantId = req.Export.MerchantId
- mreq.TimeList = req.Export.TimeList
- reply, err := rpc_apis.Statistics.LogQueryUserAccessCountExport(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryUserAccessCountExport"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- exportReq.Status = "失败"
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryUserAccessCountExportResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- file := xlsx.NewFile()
- if err := parseAccessCount(&reply, file, mreq.TimeList); err != nil {
- exportReq.Status = "失败"
- return err
- }
- if err := parseErrorsCount(&reply, file); err != nil {
- exportReq.Status = "失败"
- return err
- }
- if err := parseSourceCount(&reply, file); err != nil {
- exportReq.Status = "失败"
- return err
- }
- setAllCells(file)
- err = file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
- if true {
- utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
- }
- //resp.Data = reply
- if err != nil {
- exportReq.Status = "失败"
- } else {
- exportReq.Status = "完成"
- }
- httper.JSON(u.Ctx, resp, u.LogID)
- return err
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 数据源日志用户统计报表导出
- // @Description 数据源日志用户统计报表导出
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param export body rpc_apis.gd_statistics.LogQueryProviderCountExportReq true ""
- // @Success 200 {object} params.param_v1_0.LogQueryProviderCountExportResp "响应信息"
- // @Failure 500 服务器错误
- // @router /provider_count_export [post]
- func (u *BaseAccessLogController) LogQueryProviderCountExport() {
- u.LogID = fmt.Sprintf("LogQueryProviderCountExport[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryProviderCountExportReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- exportReq := gd_statistics.LogExportCreateReq{}
- exportReq.ExportType = 1
- exportReq.Status = "开始"
- exportReq.FileName = req.Export.ExportName
- if exportReq.FileName == "" {
- return errors.ArgsError
- }
- host := u.Ctx.Request.Host
- if strings.Contains(ServerIp, "0.0.0.0") == false {
- host = ServerIp + ":" + ServerPort
- } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
- host = u.Ctx.Request.Host + ":" + ServerPort
- }
- exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
- if true {
- exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
- }
- exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportCreate"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- exportReq.Id = exportReply.Id
- defer ExportUpdate(u, &exportReq)
- mreq := gd_statistics.LogQueryProviderCountExportReq{}
- mreq.StartTimestamp = req.Export.StartTimestamp
- mreq.EndTimestamp = req.Export.EndTimestamp
- mreq.ProviderApiIdList = req.Export.ProviderApiIdList
- mreq.ProviderId = req.Export.ProviderId
- mreq.TimeList = req.Export.TimeList
- reply, err := rpc_apis.Statistics.LogQueryProviderCountExport(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryProviderCountExport"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- exportReq.Status = "失败"
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryProviderCountExportResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- table := make(map[string][]gd_statistics.LogQueryProviderCountExport, 0)
- for index, _ := range reply.LogQueryProviderCount {
- table[reply.LogQueryProviderCount[index].ProviderApiName] = append(table[reply.LogQueryProviderCount[index].ProviderApiName], reply.LogQueryProviderCount[index])
- }
- file := xlsx.NewFile()
- if len(table) == 0 {
- file.AddSheet("空")
- }
- for k, v := range table {
- sheet, err := file.AddSheet(k)
- if err != nil {
- exportReq.Status = "失败"
- return err
- }
- makeProviderXlsxHeader(sheet, mreq.TimeList)
- sum := gd_statistics.LogQueryProviderCountExport{}
- sum.Date = "总"
- for index, _ := range v {
- row := sheet.AddRow()
- dateCell := row.AddCell()
- dateCell.Value = v[index].Date
- nameCell := row.AddCell()
- nameCell.Value = v[index].ProviderName
- totalCell := row.AddCell()
- sum.Total += v[index].Total
- totalCell.SetInt(int(v[index].Total))
- successCell := row.AddCell()
- sum.Success += v[index].Success
- successCell.SetInt(int(v[index].Success))
- failedCell := row.AddCell()
- sum.Failed += v[index].Failed
- failedCell.SetInt(int(v[index].Failed))
- failedRateCell := row.AddCell()
- SetPercentForXlsx(v[index].FailedRate, failedRateCell)
- queryCell := row.AddCell()
- queryCell.SetInt(int(v[index].Query))
- sum.Query += v[index].Query
- queryNoRecordCell := row.AddCell()
- queryNoRecordCell.SetInt(int(v[index].QueryNoRecord))
- sum.QueryNoRecord += v[index].QueryNoRecord
- queryNoRecordRateCell := row.AddCell()
- SetPercentForXlsx(v[index].QueryNoRecordRate, queryNoRecordRateCell)
- avgElapsedCell := row.AddCell()
- elStr := strconv.FormatFloat(v[index].AvgElapsed, 'f', 2, 64)
- el, _ := strconv.ParseFloat(elStr, 64)
- avgElapsedCell.SetFloatWithFormat(el, "0.00")
- sum.AvgElapsed += v[index].AvgElapsed
- sum.SumElapsed += v[index].SumElapsed
- for _, big := range v[index].BigElapsedList {
- cell := row.AddCell()
- cell.SetInt(big)
- }
- sum.BigElapsedList = sumBigElapseds(sum.BigElapsedList, v[index].BigElapsedList)
- for _, big := range v[index].ChargeBigElapsedList {
- cell := row.AddCell()
- cell.SetInt(big)
- }
- sum.ChargeBigElapsedList = sumBigElapseds(sum.ChargeBigElapsedList, v[index].ChargeBigElapsedList)
- }
- parseProviderSum(&sum, sheet)
- }
- err = file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
- if true {
- utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
- }
- //resp.Data = reply
- if err != nil {
- exportReq.Status = "失败"
- } else {
- exportReq.Status = "完成"
- }
- httper.JSON(u.Ctx, resp, u.LogID)
- return err
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- var exportStatusMap = map[string]int{
- "开始": 1,
- "完成": 2,
- "失败": 3,
- }
- // 导出文件时去掉文件后的时间戳后缀
- func convertExportFileName(src string) string {
- array := strings.Split(src, "_")
- length := len(array)
- if length < 2 {
- return src
- }
- timestampString := array[length-1]
- if len([]byte(timestampString)) < 19 {
- return src
- }
- _, err := strconv.ParseInt(timestampString, 10, 64)
- if err != nil {
- return src
- }
- return strings.TrimRight(src, "_"+timestampString)
- }
- // @Title 获取导出列表
- // @Description 获取导出列表
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param page_number query int64 false "当前页"
- // @Param is_all query bool false "是否返回所有"
- // @Param export_type query int false "api报表或数据源列表"
- // @Success 200 {object} params.param_v1_0.LogExportListResp "响应信息"
- // @Failure 500 服务器错误
- // @router /exports [get]
- func (u *BaseAccessLogController) LogExportList() {
- u.LogID = fmt.Sprintf("LogExportList[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogExportListReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogExportListReq{}
- mreq.PageNumber = req.PageNumber
- mreq.IsAll = req.IsAll
- mreq.ExportType = req.ExportType
- reply, err := rpc_apis.Statistics.LogExportList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportList"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogExportListResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- for i, v := range reply.ExportList {
- reply.ExportList[i].StatusCode, _ = exportStatusMap[v.Status]
- reply.ExportList[i].FileName = convertExportFileName(v.FileName)
- }
- resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 删除导出报表
- // @Description 删除导出报表
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param id query int64 false "导出报告id"
- // @Success 200 {object} params.param_v1_0.LogExportDeleteResp "响应信息"
- // @Failure 500 服务器错误
- // @router /export [delete]
- func (u *BaseAccessLogController) LogExportDelete() {
- u.LogID = fmt.Sprintf("LogExportDelete[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogExportDeleteReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogExportDeleteReq{}
- mreq.Id = req.Id
- mreq.ExportDir = beego.BConfig.WebConfig.StaticDir["/export"]
- reply, err := rpc_apis.Statistics.LogExportDelete(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportDelete"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- if reply.RealPath != "" {
- cache.Redis.Publish(BatchRemoveFileNotifyChannel, reply.RealPath)
- }
- resp := param_v1_0.LogExportDeleteResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- //resp.Data = reply
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 访问日志接口异常分析
- // @Description 访问日志接口异常分析
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param merchant_id query int64 false "商户id"
- // @Param api_id query int64 false "基础api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param status query int false "0 全部 1 成功 2 失败"
- // @Param end_timestamp query int64 false "结束时间"
- // @Success 200 {object} params.param_v1_0.LogQueryInterfaceAnalyzeResp "响应信息"
- // @Failure 500 服务器错误
- // @router /access_log_interface_analyze [get]
- func (u *BaseAccessLogController) LogQueryInterfaceAnalyze() {
- u.LogID = fmt.Sprintf("LogQueryInterfaceAnalyze[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryInterfaceCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryInterfaceCountReq{}
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ApiId = req.ApiId
- mreq.MerchantId = req.MerchantId
- mreq.Option = req.Status
- reply, err := rpc_apis.Statistics.LogQueryInterfaceAnalyzeError(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryInterfaceAnalyzeError"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.LogQueryInterfaceAnalyzeResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- Data: make([]gd_statistics.LogQueryInterfaceAnalyzeError, 0),
- }
- resp.Data = reply.List
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 访问日志接口数据源分析
- // @Description 访问日志接口数据源分析
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param merchant_id query int64 false "商户id"
- // @Param api_id query int64 false "基础api id"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Success 200 {object} params.param_v1_0.LogQueryInterfaceAnalyzeResp "响应信息"
- // @Failure 500 服务器错误
- // @router /third_party_analyze [get]
- func (u *BaseAccessLogController) LogQueryThirdPartyAnalyze() {
- u.LogID = fmt.Sprintf("LogQueryThirdPartyAnalyze[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryInterfaceCountReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.LogQueryInterfaceCountReq{}
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ApiId = req.ApiId
- mreq.MerchantId = req.MerchantId
- reply, err := rpc_apis.Statistics.LogQueryInterfaceThirdPartyCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryInterfaceThirdPartyCount"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.ThirdPartyAnalyzeResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- Data: make([]gd_statistics.LogQueryInterfaceThirdPartyCount, 0),
- }
- resp.Data = reply.List
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- // @Title 数据源异常分析
- // @Description 数据源异常分析
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param provider_api_id query int64 false "基础api id"
- // @Param status query int false "0 全部 1 成功 2 异常"
- // @Param start_timestamp query int64 false "开始时间"
- // @Param end_timestamp query int64 false "结束时间"
- // @Success 200 {object} params.param_v1_0.ThirdPartyInterfaceErrorAnalyzeResp "响应信息"
- // @Failure 500 服务器错误
- // @router /third_party_err_analyze [get]
- func (u *BaseAccessLogController) ThirdPartyInterfaceErrorAnalyze() {
- u.LogID = fmt.Sprintf("LogQueryThirdPartyAnalyze[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.ThirdPartyInterfaceErrorAnalyzeReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleTokenCheck := func() error {
- uid, _, err := utils.ParseToken(req.Token)
- if err != nil {
- return err
- }
- if uid != req.Uid {
- return errors.UserTokenillegality
- }
- /*if level == 0 {
- return errors.AuthNotAllow
- }*/
- return nil
- }
- handleDataTask := func() error {
- mreq := gd_statistics.ThirdPartyInterfaceErrorAnalyzeReq{}
- mreq.StartTimestamp = req.StartTimestamp
- mreq.EndTimestamp = req.EndTimestamp
- mreq.ProviderApiId = req.ProviderApiId
- mreq.Status = req.Status
- reply, err := rpc_apis.Statistics.ThirdPartyInterfaceErrorAnalyze(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "ThirdPartyInterfaceErrorAnalyze"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- resp := param_v1_0.ThirdPartyInterfaceErrorAnalyzeResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- Data: make([]gd_statistics.ThirdPartyInterfaceErrorAnalyze, 0),
- }
- resp.Data = reply.List
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleTokenCheck, handleDataTask,
- )
- }
- func ExportImpl(req *param_v1_0.LogQueryUserAccessLogExportReq,u *BaseAccessLogController) error {
- defer func() {
- if r := recover(); r != nil {
- err := fmt.Errorf("%+v", r)
- fmt.Println("export err:",err)
- }
- }()
- var headMap map[string]string
- if !req.Export.EnglishHeader {
- hReq := gd_management.ManagementGetBaseApiByRouterReq{}
- hReq.MerchantId = int(req.Export.MerchantId)
- hReq.ApiId = int(req.Export.ApiId)
- hReply, err := rpc_apis.Management.ManagementGetBaseApiByRouter(utils.NewContextFromBeegoCtx(u.Ctx), &hReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "ManagementGetBaseApiByRouter"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- //return errors.ErrorTransform(err)
- } else {
- headMap = hReply.Data
- }
- fmt.Println("ManagementGetBaseApiByRouter:", hReply, err)
- }
- // 创建导出任务
- req.Export.ExportName = fmt.Sprintf("%s_%d", req.Export.ExportName, time.Now().UnixNano())
- exportReq := gd_statistics.LogExportCreateReq{}
- exportReq.Status = "开始"
- exportReq.ExportType = 2
- exportReq.FileName = req.Export.ExportName
- if exportReq.FileName == "" {
- return errors.ArgsError
- }
- host := u.Ctx.Request.Host
- if strings.Contains(ServerIp, "0.0.0.0") == false {
- host = ServerIp + ":" + ServerPort
- } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
- host = u.Ctx.Request.Host + ":" + ServerPort
- }
- exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
- if true {
- exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
- }
- exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportCreate"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- exportReq.Id = exportReply.Id
- // 任务执行完成后更新任务
- defer ExportUpdate(u, &exportReq)
- // 调微服务获取日志数据
- mreq := gd_statistics.LogQueryAccessLogReq{}
- mreq.StartTimestamp = req.Export.StartTimestamp
- mreq.EndTimestamp = req.Export.EndTimestamp
- mreq.ApiId = req.Export.ApiId
- mreq.MerchantId = req.Export.MerchantId
- mreq.PageNumber = 0
- mreq.PageSize = 10000
- mreq.UseId = true
- // 初始化excel manager
- mg := initLogExcelManagerNew(req.Export.IsParseParam)
- exportReq.Status = "进行中"
- ExportUpdate(u, &exportReq)
- // 考虑到数据量问题分批获取数据
- for {
- fmt.Println("111111111111111111111111111111111111111111111111111111",mreq.PageNumber)
- mreq.PageNumber += 1
- reply, err := rpc_apis.Statistics.LogExport(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExport"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- exportReq.Status = "失败"
- return errors.ErrorTransform(err)
- }
- logLen := int64(len(reply.AccessLogs))
- if len(reply.AccessLogs) == 0 {
- break
- }
- // 写入execel
- accessLogWriteToExcelNew(mg, reply.AccessLogs, headMap)
- if logLen < mreq.PageSize{
- break
- }
- mreq.LastId = reply.AccessLogs[logLen-1].Id
- }
- exportReq.Status = "完成"
- // 保存execel
- mg.baseSheet.Flush()
- if req.Export.IsParseParam{
- if mg.reqSheet != nil{
- mg.reqSheet.Flush()
- }
- if mg.resSheet != nil{
- mg.resSheet.Flush()
- }
- }
- mg.file.SaveAs(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
- //mg.file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
- if true {
- utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
- }
- return nil
- }
- // @Title 平台日志导出
- // @Description 平台日志导出
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param export body params.param_v1_0.LogExportInfo true "导出任务信息"
- // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountExportResp "响应信息"
- // @Failure 500 服务器错误
- // @router /access_log_export [post]
- func (u *BaseAccessLogController) LogQueryUserAccessLogExport() {
- u.LogID = fmt.Sprintf("LogQueryUserAccessLogExport[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryUserAccessLogExportReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleDataTask := func() error {
- /*var headMap map[string]string
- if !req.Export.EnglishHeader {
- hReq := gd_management.ManagementGetBaseApiByRouterReq{}
- hReq.MerchantId = int(req.Export.MerchantId)
- hReq.ApiId = int(req.Export.ApiId)
- hReply, err := rpc_apis.Management.ManagementGetBaseApiByRouter(utils.NewContextFromBeegoCtx(u.Ctx), &hReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "ManagementGetBaseApiByRouter"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- } else {
- headMap = hReply.Data
- }
- fmt.Println("ManagementGetBaseApiByRouter:", hReply, err)
- }
- // 创建导出任务
- req.Export.ExportName = fmt.Sprintf("%s_%d", req.Export.ExportName, time.Now().UnixNano())
- exportReq := gd_statistics.LogExportCreateReq{}
- exportReq.Status = "开始"
- exportReq.ExportType = 2
- exportReq.FileName = req.Export.ExportName
- if exportReq.FileName == "" {
- return errors.ArgsError
- }
- host := u.Ctx.Request.Host
- if strings.Contains(ServerIp, "0.0.0.0") == false {
- host = ServerIp + ":" + ServerPort
- } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
- host = u.Ctx.Request.Host + ":" + ServerPort
- }
- exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
- if true {
- exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
- }
- exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportCreate"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- exportReq.Id = exportReply.Id
- defer ExportUpdate(u, &exportReq)
- mreq := gd_statistics.LogQueryAccessLogReq{}
- mreq.StartTimestamp = req.Export.StartTimestamp
- mreq.EndTimestamp = req.Export.EndTimestamp
- mreq.ApiId = req.Export.ApiId
- mreq.MerchantId = req.Export.MerchantId
- mreq.PageNumber = 0
- mreq.PageSize = 1000
- // 初始化excel manager
- mg := initLogExcelManagerNew(req.Export.IsParseParam)
- total := int64(0)
- handled := int64(0)
- // 考虑到数据量问题分批获取数据
- for {
- mreq.PageNumber += 1
- reply, err := rpc_apis.Statistics.LogQueryAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryAccessLog"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- exportReq.Status = "失败"
- return errors.ErrorTransform(err)
- }
- // 设置总数
- if total == 0 {
- total = reply.Total
- }
- // 写入execel
- accessLogWriteToExcelNew(mg, reply.AccessLogs, headMap)
- handled += int64(len(reply.AccessLogs))
- // 处理完毕
- if handled >= total {
- break
- }
- }
- exportReq.Status = "完成"
- // 保存execel
- mg.baseSheet.Flush()
- if req.Export.IsParseParam{
- if mg.reqSheet != nil{
- mg.reqSheet.Flush()
- }
- if mg.resSheet != nil{
- mg.resSheet.Flush()
- }
- }
- mg.file.SaveAs(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
- if true {
- utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
- }*/
- if req.Export.ExportName == "" {
- return errors.ArgsError
- }
- if req.Export.StartTimestamp == 0 || req.Export.EndTimestamp == 0 {
- return errors.ArgsError
- }
- // TODO 判断是否在一个月内
- monthstar := time.Unix(req.Export.StartTimestamp,0).Month()
- monthEnd := time.Unix(req.Export.EndTimestamp,0).Month()
- if monthstar != monthEnd{
- return jsonrpc2.NewJsonError(20001, "参数错误,不能跨月导出")
- }
- go ExportImpl(req,u)
- resp := param_v1_0.LogQueryUserAccessCountExportResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- httper.JSON(u.Ctx, resp, u.LogID)
- return nil
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleDataTask,
- )
- }
- // @Title 数据源日志导出
- // @Description 数据源日志导出
- // @Param token header string true "token"
- // @Param uid header int64 true "admin id"
- // @Param export body params.param_v1_0.ThirdpartLogExportInfo true "导出任务信息"
- // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountExportResp "响应信息"
- // @Failure 500 服务器错误
- // @router /thirdpart_log_export [post]
- func (u *BaseAccessLogController) LogQueryUserThirdpartLogExport() {
- u.LogID = fmt.Sprintf("LogQueryUserThirdpartLogExport[%d]", time.Now().UnixNano())
- req := ¶m_v1_0.LogQueryUserThirdpartLogExportReq{}
- getParamsTask := func() error {
- httper.FillRequireParams(u.Ctx, req, u.LogID)
- return nil
- }
- handleDataTask := func() error {
- // 创建导出任务
- req.Export.ExportName = fmt.Sprintf("%s_%d", req.Export.ExportName, time.Now().UnixNano())
- exportReq := gd_statistics.LogExportCreateReq{}
- exportReq.Status = "开始"
- exportReq.ExportType = 3
- exportReq.FileName = req.Export.ExportName
- if exportReq.FileName == "" {
- return errors.ArgsError
- }
- host := ServerIp + ":" + ServerPort
- exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
- if true {
- exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
- }
- exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogExportCreate"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- return errors.ErrorTransform(err)
- }
- exportReq.Id = exportReply.Id
- // 任务执行完成后更新任务
- defer ExportUpdate(u, &exportReq)
- // 调微服务获取日志数据
- mreq := gd_statistics.LogQueryThirdpartAccessLogReq{}
- mreq.StartTimestamp = req.Export.StartTimestamp
- mreq.EndTimestamp = req.Export.EndTimestamp
- mreq.ProviderApiId = req.Export.ProviderApiId
- mreq.ProviderId = req.Export.ProviderId
- mreq.PageNumber = 0
- mreq.PageSize = 1000
- // 初始化excel manager
- mg := initLogExcelManager(req.Export.IsParseParam)
- total := int64(0)
- handled := int64(0)
- // 考虑到数据量问题分批获取数据
- for {
- mreq.PageNumber += 1
- reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
- if err != nil {
- l.Error("rpc",
- zap.String("call", "LogQueryThirdpartAccessLog"),
- zap.String("args", utils.MarshalJsonString(req)),
- zap.String("error", err.Error()))
- exportReq.Status = "失败"
- return errors.ErrorTransform(err)
- }
- // 设置总数
- if total == 0 {
- total = reply.Total
- }
- // 数据写入execel
- thirdLogWriteToExcel(mg, reply.ThirdpartLogs)
- handled += int64(len(reply.ThirdpartLogs))
- // 处理完毕
- if handled >= total {
- break
- }
- }
- exportReq.Status = "完成"
- // 保存execel
- mg.file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
- if true {
- utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
- }
- resp := param_v1_0.LogQueryUserAccessCountExportResp{
- SimpleResp: param_base.SimpleResp{
- Code: 0,
- Msg: "SUCCESS",
- },
- }
- httper.JSON(u.Ctx, resp, u.LogID)
- return err
- }
- // 执行以上定义的任务
- task.Do(&task.PanicRecover{
- Ctx: u.Ctx,
- LogID: u.LogID}, u.Ctx,
- getParamsTask, handleDataTask,
- )
- }
|