access_log.go 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package ctrl_v1
  4. import (
  5. "context"
  6. "gd_management_gateway/common.in/jsonrpc2"
  7. "gd_management_gateway/errors"
  8. "gd_management_gateway/params/param_base"
  9. "gd_management_gateway/params/param_v1_0"
  10. "gd_management_gateway/rpc_apis"
  11. "gd_management_gateway/rpc_apis/gd_statistics"
  12. "gd_management_gateway/rpc_apis/gd_management"
  13. "fmt"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "gd_management_gateway/common.in/cache"
  19. "gd_management_gateway/common.in/httper"
  20. "gd_management_gateway/common.in/task"
  21. "gd_management_gateway/common.in/utils"
  22. "github.com/astaxie/beego"
  23. "github.com/tealeg/xlsx"
  24. "go.uber.org/zap"
  25. )
  26. const exportPath = "/export/"
  27. var ServerPort = "61002"
  28. var ServerIp = ""
  29. // Operations about access log api
  30. type BaseAccessLogController struct {
  31. metadata interface{} // 中继元数据
  32. beego.Controller
  33. LogID string
  34. }
  35. // SetPercentForXlsx 单元格设置百分率
  36. func SetPercentForXlsx(percent string, cell *xlsx.Cell) {
  37. s := strings.TrimRight(percent, "%")
  38. // 对零单独处理
  39. f, _ := strconv.ParseFloat(s, 64)
  40. if f == 0 {
  41. cell.SetFloatWithFormat(0.0000, "0.00%")
  42. return
  43. }
  44. // 将百分比转为小数形式
  45. f = f / 100.0000
  46. fstring := strconv.FormatFloat(f, 'f', 4, 64)
  47. ffloat, _ := strconv.ParseFloat(fstring, 64)
  48. // 设置单元格
  49. cell.SetFloatWithFormat(ffloat, "0.00%")
  50. }
  51. // @Title 访问日志
  52. // @Description 访问日志
  53. // @Param token header string true "token"
  54. // @Param uid header int64 true "admin id"
  55. // @Param state query int false "接口调用返回状态"
  56. // @Param code query string false "接口调用返回状态"
  57. // @Param request_param query string false "请求参数"
  58. // @Param search query string false "关键字"
  59. // @Param merchant_id query int64 false "商户id"
  60. // @Param api_id query int64 false "基础api id"
  61. // @Param start_timestamp query int64 false "开始时间"
  62. // @Param end_timestamp query int64 false "结束时间"
  63. // @Param page_size query int64 false "页大小"
  64. // @Param page_number query int64 false "页号"
  65. // @Param min query float64 false "最小耗时"
  66. // @Param max query float64 false "最大耗时"
  67. // @Success 200 {object} params.param_v1_0.LogQueryAccessLogResp "响应信息"
  68. // @Failure 500 服务器错误
  69. // @router /access_log [get]
  70. func (u *BaseAccessLogController) LogQueryAccessLog() {
  71. u.LogID = fmt.Sprintf("LogQueryAccessLog[%d]", time.Now().UnixNano())
  72. req := &param_v1_0.LogQueryAccessLogReq{}
  73. getParamsTask := func() error {
  74. httper.FillRequireParams(u.Ctx, req, u.LogID)
  75. return nil
  76. }
  77. handleTokenCheck := func() error {
  78. uid, _, err := utils.ParseToken(req.Token)
  79. if err != nil {
  80. return err
  81. }
  82. if uid != req.Uid {
  83. return errors.UserTokenillegality
  84. }
  85. /*if level == 0 {
  86. return errors.AuthNotAllow
  87. }*/
  88. return nil
  89. }
  90. handleDataTask := func() error {
  91. mreq := gd_statistics.LogQueryAccessLogReq{}
  92. mreq.PageNumber = req.PageNumber
  93. mreq.PageSize = req.PageSize
  94. mreq.StartTimestamp = req.StartTimestamp
  95. mreq.EndTimestamp = req.EndTimestamp
  96. mreq.ApiId = req.ApiId
  97. mreq.MerchantId = req.MerchantId
  98. mreq.State = req.State
  99. mreq.Code = req.Code
  100. mreq.RequestParam = req.RequestParam
  101. mreq.Search = req.Search
  102. mreq.Max = req.Max
  103. mreq.Min = req.Min
  104. reply, err := rpc_apis.Statistics.LogQueryAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  105. if err != nil {
  106. l.Error("rpc",
  107. zap.String("call", "LogQueryAccessLog"),
  108. zap.String("args", utils.MarshalJsonString(req)),
  109. zap.String("error", err.Error()))
  110. return errors.ErrorTransform(err)
  111. }
  112. resp := param_v1_0.LogQueryAccessLogResp{
  113. SimpleResp: param_base.SimpleResp{
  114. Code: 0,
  115. Msg: "SUCCESS",
  116. },
  117. }
  118. resp.Data = reply
  119. httper.JSON(u.Ctx, resp, u.LogID)
  120. return nil
  121. }
  122. // 执行以上定义的任务
  123. task.Do(&task.PanicRecover{
  124. Ctx: u.Ctx,
  125. LogID: u.LogID}, u.Ctx,
  126. getParamsTask, handleTokenCheck, handleDataTask,
  127. )
  128. }
  129. // @Title 数据源日志
  130. // @Description 数据源日志
  131. // @Param token header string true "token"
  132. // @Param uid header int64 true "admin id"
  133. // @Param state query int false "接口调用返回状态"
  134. // @Param search query string false "关键字"
  135. // @Param request_param query string false "请求参数"
  136. // @Param provider_id query int64 false "三方平台id"
  137. // @Param provider_api_id query int64 false "三方api id"
  138. // @Param start_timestamp query int64 false "开始时间"
  139. // @Param end_timestamp query int64 false "结束时间"
  140. // @Param page_size query int64 false "页大小"
  141. // @Param page_number query int64 false "页号"
  142. // @Param min query float64 false "最小耗时"
  143. // @Param max query float64 false "最大耗时"
  144. // @Param raw_code query string false "原始错误码"
  145. // @Success 200 {object} params.param_v1_0.LogQueryThirdpartAccessLogResp "响应信息"
  146. // @Failure 500 服务器错误
  147. // @router /thirdpart_access_log [get]
  148. func (u *BaseAccessLogController) LogQueryThirdpartAccessLog() {
  149. u.LogID = fmt.Sprintf("LogQueryThirdpartAccessLog[%d]", time.Now().UnixNano())
  150. req := &param_v1_0.LogQueryThirdpartAccessLogReq{}
  151. getParamsTask := func() error {
  152. httper.FillRequireParams(u.Ctx, req, u.LogID)
  153. return nil
  154. }
  155. handleTokenCheck := func() error {
  156. uid, _, err := utils.ParseToken(req.Token)
  157. if err != nil {
  158. return err
  159. }
  160. if uid != req.Uid {
  161. return errors.UserTokenillegality
  162. }
  163. /*if level == 0 {
  164. return errors.AuthNotAllow
  165. }*/
  166. return nil
  167. }
  168. handleDataTask := func() error {
  169. mreq := gd_statistics.LogQueryThirdpartAccessLogReq{}
  170. mreq.EndTimestamp = req.EndTimestamp
  171. mreq.StartTimestamp = req.StartTimestamp
  172. mreq.PageSize = req.PageSize
  173. mreq.PageNumber = req.PageNumber
  174. mreq.ProviderApiId = req.ProviderApiId
  175. mreq.ProviderId = req.ProviderId
  176. mreq.State = req.State
  177. mreq.RequestParam = req.RequestParam
  178. mreq.Search = req.Search
  179. mreq.Max = req.Max
  180. mreq.Min = req.Min
  181. mreq.RawCode = req.RawCode
  182. fmt.Println("raw code:",mreq.RawCode,req.RawCode)
  183. reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  184. if err != nil {
  185. l.Error("rpc",
  186. zap.String("call", "LogQueryThirdpartAccessLog"),
  187. zap.String("args", utils.MarshalJsonString(req)),
  188. zap.String("error", err.Error()))
  189. return errors.ErrorTransform(err)
  190. }
  191. resp := param_v1_0.LogQueryThirdpartAccessLogResp{
  192. SimpleResp: param_base.SimpleResp{
  193. Code: 0,
  194. Msg: "SUCCESS",
  195. },
  196. }
  197. resp.Data = reply
  198. httper.JSON(u.Ctx, resp, u.LogID)
  199. return nil
  200. }
  201. // 执行以上定义的任务
  202. task.Do(&task.PanicRecover{
  203. Ctx: u.Ctx,
  204. LogID: u.LogID}, u.Ctx,
  205. getParamsTask, handleTokenCheck, handleDataTask,
  206. )
  207. }
  208. // @Title 访问日志统计
  209. // @Description 访问日志统计
  210. // @Param token header string true "token"
  211. // @Param uid header int64 true "admin id"
  212. // @Param merchant_id query int64 false "商户id"
  213. // @Param api_id query int64 false "基础api id"
  214. // @Param start_timestamp query int64 false "开始时间"
  215. // @Param end_timestamp query int64 false "结束时间"
  216. // @Param page_size query int64 false "页大小"
  217. // @Param page_number query int64 false "页号"
  218. // @Success 200 {object} params.param_v1_0.LogQueryAccessLogCountResp "响应信息"
  219. // @Failure 500 服务器错误
  220. // @router /access_log_count [get]
  221. func (u *BaseAccessLogController) LogQueryAccessLogCount() {
  222. u.LogID = fmt.Sprintf("LogQueryAccessLogCount[%d]", time.Now().UnixNano())
  223. req := &param_v1_0.LogQueryAccessLogCountReq{}
  224. getParamsTask := func() error {
  225. httper.FillRequireParams(u.Ctx, req, u.LogID)
  226. return nil
  227. }
  228. handleTokenCheck := func() error {
  229. uid, _, err := utils.ParseToken(req.Token)
  230. if err != nil {
  231. return err
  232. }
  233. if uid != req.Uid {
  234. return errors.UserTokenillegality
  235. }
  236. /*if level == 0 {
  237. return errors.AuthNotAllow
  238. }*/
  239. return nil
  240. }
  241. handleDataTask := func() error {
  242. mreq := gd_statistics.LogQueryAccessLogCountReq{}
  243. mreq.PageNumber = req.PageNumber
  244. mreq.PageSize = req.PageSize
  245. mreq.StartTimestamp = req.StartTimestamp
  246. mreq.EndTimestamp = req.EndTimestamp
  247. mreq.ApiId = req.ApiId
  248. mreq.MerchantId = req.MerchantId
  249. reply, err := rpc_apis.Statistics.LogQueryAccessLogCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  250. if err != nil {
  251. l.Error("rpc",
  252. zap.String("call", "LogQueryAccessLogCount"),
  253. zap.String("args", utils.MarshalJsonString(req)),
  254. zap.String("error", err.Error()))
  255. return errors.ErrorTransform(err)
  256. }
  257. resp := param_v1_0.LogQueryAccessLogCountResp{
  258. SimpleResp: param_base.SimpleResp{
  259. Code: 0,
  260. Msg: "SUCCESS",
  261. },
  262. }
  263. resp.Data = reply
  264. httper.JSON(u.Ctx, resp, u.LogID)
  265. return nil
  266. }
  267. // 执行以上定义的任务
  268. task.Do(&task.PanicRecover{
  269. Ctx: u.Ctx,
  270. LogID: u.LogID}, u.Ctx,
  271. getParamsTask, handleTokenCheck, handleDataTask,
  272. )
  273. }
  274. // @Title 数据源查询统计
  275. // @Description 数据源查询统
  276. // @Param token header string true "token"
  277. // @Param uid header int64 true "admin id"
  278. // @Param provider_id query int64 false "三方平台id"
  279. // @Param provider_api_id query int64 false "三方api id"
  280. // @Param start_timestamp query int64 false "开始时间"
  281. // @Param end_timestamp query int64 false "结束时间"
  282. // @Param page_size query int64 false "页大小"
  283. // @Param page_number query int64 false "页号"
  284. // @Success 200 {object} params.param_v1_0.LogQueryThirdpartAccessLogCountResp "响应信息"
  285. // @Failure 500 服务器错误
  286. // @router /thirdpart_accesslog_count [get]
  287. func (u *BaseAccessLogController) LogQueryThirdpartAccessLogCount() {
  288. u.LogID = fmt.Sprintf("LogQueryThirdpartAccessLogCount[%d]", time.Now().UnixNano())
  289. req := &param_v1_0.LogQueryThirdpartAccessLogCountReq{}
  290. getParamsTask := func() error {
  291. httper.FillRequireParams(u.Ctx, req, u.LogID)
  292. return nil
  293. }
  294. handleTokenCheck := func() error {
  295. uid, _, err := utils.ParseToken(req.Token)
  296. if err != nil {
  297. return err
  298. }
  299. if uid != req.Uid {
  300. return errors.UserTokenillegality
  301. }
  302. /*if level == 0 {
  303. return errors.AuthNotAllow
  304. }*/
  305. return nil
  306. }
  307. handleDataTask := func() error {
  308. mreq := gd_statistics.LogQueryThirdpartAccessLogCountReq{}
  309. mreq.EndTimestamp = req.EndTimestamp
  310. mreq.StartTimestamp = req.StartTimestamp
  311. mreq.PageSize = req.PageSize
  312. mreq.PageNumber = req.PageNumber
  313. mreq.ProviderApiId = req.ProviderApiId
  314. mreq.ProviderId = req.ProviderId
  315. reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessLogCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  316. if err != nil {
  317. l.Error("rpc",
  318. zap.String("call", "LogQueryThirdpartAccessLogCount"),
  319. zap.String("args", utils.MarshalJsonString(req)),
  320. zap.String("error", err.Error()))
  321. return errors.ErrorTransform(err)
  322. }
  323. resp := param_v1_0.LogQueryThirdpartAccessLogCountResp{
  324. SimpleResp: param_base.SimpleResp{
  325. Code: 0,
  326. Msg: "SUCCESS",
  327. },
  328. }
  329. resp.Data = reply
  330. httper.JSON(u.Ctx, resp, u.LogID)
  331. return nil
  332. }
  333. // 执行以上定义的任务
  334. task.Do(&task.PanicRecover{
  335. Ctx: u.Ctx,
  336. LogID: u.LogID}, u.Ctx,
  337. getParamsTask, handleTokenCheck, handleDataTask,
  338. )
  339. }
  340. // @Title 访问日志关联数据源日志
  341. // @Description 访问日志关联数据源日志
  342. // @Param token header string true "token"
  343. // @Param uid header int64 true "admin id"
  344. // @Param access_id query int true "访问日志id"
  345. // @Param create_time query string true "时间"
  346. // @Success 200 {object} params.param_v1_0.LogQueryAccessLogThirdpartLogResp "响应信息"
  347. // @Failure 500 服务器错误
  348. // @router /access_log_get_thirdpart_log [get]
  349. func (u *BaseAccessLogController) LogQueryAccessLogThirdpartLog() {
  350. u.LogID = fmt.Sprintf("LogQueryAccessLogThirdpartLog[%d]", time.Now().UnixNano())
  351. req := &param_v1_0.LogQueryAccessLogThirdpartLogReq{}
  352. getParamsTask := func() error {
  353. httper.FillRequireParams(u.Ctx, req, u.LogID)
  354. return nil
  355. }
  356. handleTokenCheck := func() error {
  357. uid, _, err := utils.ParseToken(req.Token)
  358. if err != nil {
  359. return err
  360. }
  361. if uid != req.Uid {
  362. return errors.UserTokenillegality
  363. }
  364. /*if level == 0 {
  365. return errors.AuthNotAllow
  366. }*/
  367. return nil
  368. }
  369. handleDataTask := func() error {
  370. mreq := gd_statistics.LogQueryAccessLogThirdpartLogReq{}
  371. mreq.AccessId = req.AccessId
  372. if req.CreateTime != "" {
  373. timeLayout := "2006-01-02"
  374. loc, _ := time.LoadLocation("Local")
  375. array := strings.Split(req.CreateTime, " ")
  376. t, _ := time.ParseInLocation(timeLayout, array[0], loc)
  377. mreq.Timestamp = t.Unix()
  378. }
  379. reply, err := rpc_apis.Statistics.LogQueryAccessLogThirdpartLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  380. if err != nil {
  381. l.Error("rpc",
  382. zap.String("call", "LogQueryAccessLogThirdpartLog"),
  383. zap.String("args", utils.MarshalJsonString(req)),
  384. zap.String("error", err.Error()))
  385. return errors.ErrorTransform(err)
  386. }
  387. resp := param_v1_0.LogQueryAccessLogThirdpartLogResp{
  388. SimpleResp: param_base.SimpleResp{
  389. Code: 0,
  390. Msg: "SUCCESS",
  391. },
  392. }
  393. resp.Data = reply
  394. httper.JSON(u.Ctx, resp, u.LogID)
  395. return nil
  396. }
  397. // 执行以上定义的任务
  398. task.Do(&task.PanicRecover{
  399. Ctx: u.Ctx,
  400. LogID: u.LogID}, u.Ctx,
  401. getParamsTask, handleTokenCheck, handleDataTask,
  402. )
  403. }
  404. // @Title 访问日志用户统计报表
  405. // @Description 访问日志用户统计报表
  406. // @Param token header string true "token"
  407. // @Param uid header int64 true "admin id"
  408. // @Param merchant_id query int64 false "商户id"
  409. // @Param api_id query int64 false "基础api id"
  410. // @Param start_timestamp query int64 false "开始时间"
  411. // @Param end_timestamp query int64 false "结束时间"
  412. // @Param page_size query int64 false "页大小"
  413. // @Param page_number query int64 false "页号"
  414. // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountResp "响应信息"
  415. // @Failure 500 服务器错误
  416. // @router /user_access_count [get]
  417. func (u *BaseAccessLogController) LogQueryUserAccessCount() {
  418. u.LogID = fmt.Sprintf("LogQueryUserAccessCount[%d]", time.Now().UnixNano())
  419. req := &param_v1_0.LogQueryUserAccessCountReq{}
  420. getParamsTask := func() error {
  421. httper.FillRequireParams(u.Ctx, req, u.LogID)
  422. return nil
  423. }
  424. handleTokenCheck := func() error {
  425. uid, _, err := utils.ParseToken(req.Token)
  426. if err != nil {
  427. return err
  428. }
  429. if uid != req.Uid {
  430. return errors.UserTokenillegality
  431. }
  432. /*if level == 0 {
  433. return errors.AuthNotAllow
  434. }*/
  435. return nil
  436. }
  437. handleDataTask := func() error {
  438. mreq := gd_statistics.LogQueryUserAccessCountReq{}
  439. mreq.PageNumber = req.PageNumber
  440. mreq.PageSize = req.PageSize
  441. mreq.StartTimestamp = req.StartTimestamp
  442. mreq.EndTimestamp = req.EndTimestamp
  443. mreq.ApiId = req.ApiId
  444. mreq.MerchantId = req.MerchantId
  445. reply, err := rpc_apis.Statistics.LogQueryUserAccessCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  446. if err != nil {
  447. l.Error("rpc",
  448. zap.String("call", "LogQueryUserAccessCount"),
  449. zap.String("args", utils.MarshalJsonString(req)),
  450. zap.String("error", err.Error()))
  451. return errors.ErrorTransform(err)
  452. }
  453. resp := param_v1_0.LogQueryUserAccessCountResp{
  454. SimpleResp: param_base.SimpleResp{
  455. Code: 0,
  456. Msg: "SUCCESS",
  457. },
  458. }
  459. resp.Data = reply
  460. httper.JSON(u.Ctx, resp, u.LogID)
  461. return nil
  462. }
  463. // 执行以上定义的任务
  464. task.Do(&task.PanicRecover{
  465. Ctx: u.Ctx,
  466. LogID: u.LogID}, u.Ctx,
  467. getParamsTask, handleTokenCheck, handleDataTask,
  468. )
  469. }
  470. // @Title 访问日志接口统计详情
  471. // @Description 访问日志接口统计详情
  472. // @Param token header string true "token"
  473. // @Param uid header int64 true "admin id"
  474. // @Param merchant_id query int64 false "商户id"
  475. // @Param api_id query int64 false "基础api id"
  476. // @Param start_timestamp query int64 false "开始时间"
  477. // @Param end_timestamp query int64 false "结束时间"
  478. // @Success 200 {object} params.param_v1_0.LogQueryInterfaceCountResp "响应信息"
  479. // @Failure 500 服务器错误
  480. // @router /access_log_interface_count [get]
  481. func (u *BaseAccessLogController) LogQueryInterfaceCount() {
  482. u.LogID = fmt.Sprintf("LogQueryInterfaceCount[%d]", time.Now().UnixNano())
  483. req := &param_v1_0.LogQueryInterfaceCountReq{}
  484. getParamsTask := func() error {
  485. httper.FillRequireParams(u.Ctx, req, u.LogID)
  486. return nil
  487. }
  488. handleTokenCheck := func() error {
  489. uid, _, err := utils.ParseToken(req.Token)
  490. if err != nil {
  491. return err
  492. }
  493. if uid != req.Uid {
  494. return errors.UserTokenillegality
  495. }
  496. /*if level == 0 {
  497. return errors.AuthNotAllow
  498. }*/
  499. return nil
  500. }
  501. handleDataTask := func() error {
  502. mreq := gd_statistics.LogQueryInterfaceCountReq{}
  503. mreq.StartTimestamp = req.StartTimestamp
  504. mreq.EndTimestamp = req.EndTimestamp
  505. mreq.ApiId = req.ApiId
  506. mreq.MerchantId = req.MerchantId
  507. reply, err := rpc_apis.Statistics.LogQueryInterfaceCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  508. if err != nil {
  509. l.Error("rpc",
  510. zap.String("call", "LogQueryInterfaceCount"),
  511. zap.String("args", utils.MarshalJsonString(req)),
  512. zap.String("error", err.Error()))
  513. return errors.ErrorTransform(err)
  514. }
  515. resp := param_v1_0.LogQueryInterfaceCountResp{
  516. SimpleResp: param_base.SimpleResp{
  517. Code: 0,
  518. Msg: "SUCCESS",
  519. },
  520. }
  521. resp.Data = reply
  522. httper.JSON(u.Ctx, resp, u.LogID)
  523. return nil
  524. }
  525. // 执行以上定义的任务
  526. task.Do(&task.PanicRecover{
  527. Ctx: u.Ctx,
  528. LogID: u.LogID}, u.Ctx,
  529. getParamsTask, handleTokenCheck, handleDataTask,
  530. )
  531. }
  532. // @Title 数据源接口用量统计
  533. // @Description 数据源接口用量统计
  534. // @Param token header string true "token"
  535. // @Param uid header int64 true "admin id"
  536. // @Param provider_api_id query int64 false "数据源api id"
  537. // @Param time query int64 false "时间"
  538. // @Param start_timestamp query int64 false "开始时间"
  539. // @Param end_timestamp query int64 false "结束时间"
  540. // @Success 200 {object} params.param_v1_0.LogQueryThirdpartAccessCountResp "响应信息"
  541. // @Failure 500 服务器错误
  542. // @router /thirdpart_access_count [get]
  543. func (u *BaseAccessLogController) LogQueryThirdpartAccessCount() {
  544. u.LogID = fmt.Sprintf("LogQueryInterfaceCount[%d]", time.Now().UnixNano())
  545. req := &param_v1_0.LogQueryThirdpartAccessCountReq{}
  546. getParamsTask := func() error {
  547. httper.FillRequireParams(u.Ctx, req, u.LogID)
  548. return nil
  549. }
  550. handleTokenCheck := func() error {
  551. uid, _, err := utils.ParseToken(req.Token)
  552. if err != nil {
  553. return err
  554. }
  555. if uid != req.Uid {
  556. return errors.UserTokenillegality
  557. }
  558. /*if level == 0 {
  559. return errors.AuthNotAllow
  560. }*/
  561. return nil
  562. }
  563. handleDataTask := func() error {
  564. mreq := gd_statistics.LogQueryThirdpartAccessCountReq{}
  565. mreq.StartTimestamp = req.StartTimestamp
  566. mreq.EndTimestamp = req.EndTimestamp
  567. mreq.ProviderApiId = req.ProviderApiId
  568. if req.Time > 0 {
  569. mreq.Time = time.Unix(req.Time, 0).Format("2006-01-02")
  570. }
  571. reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  572. if err != nil {
  573. l.Error("rpc",
  574. zap.String("call", "LogQueryThirdpartAccessCount"),
  575. zap.String("args", utils.MarshalJsonString(req)),
  576. zap.String("error", err.Error()))
  577. return errors.ErrorTransform(err)
  578. }
  579. resp := param_v1_0.LogQueryThirdpartAccessCountResp{
  580. SimpleResp: param_base.SimpleResp{
  581. Code: 0,
  582. Msg: "SUCCESS",
  583. },
  584. }
  585. resp.Data = reply
  586. httper.JSON(u.Ctx, resp, u.LogID)
  587. return nil
  588. }
  589. // 执行以上定义的任务
  590. task.Do(&task.PanicRecover{
  591. Ctx: u.Ctx,
  592. LogID: u.LogID}, u.Ctx,
  593. getParamsTask, handleTokenCheck, handleDataTask,
  594. )
  595. }
  596. // @Title 数据源接口统计报表
  597. // @Description 数据源接口统计报表
  598. // @Param token header string true "token"
  599. // @Param uid header int64 true "admin id"
  600. // @Param provider_api_id query int64 false "数据源api id"
  601. // @Param start_timestamp query int64 false "开始时间"
  602. // @Param end_timestamp query int64 false "结束时间"
  603. // @Param page_size query int64 false "页大小"
  604. // @Param page_number query int64 false "页号"
  605. // @Success 200 {object} params.param_v1_0.LogQueryThirdpartInterfaceCountResp "响应信息"
  606. // @Failure 500 服务器错误
  607. // @router /thirdpart_access_interface_count [get]
  608. func (u *BaseAccessLogController) LogQueryThirdpartInterfaceCount() {
  609. u.LogID = fmt.Sprintf("LogQueryThirdpartInterfaceCount[%d]", time.Now().UnixNano())
  610. req := &param_v1_0.LogQueryThirdpartInterfaceCountReq{}
  611. getParamsTask := func() error {
  612. httper.FillRequireParams(u.Ctx, req, u.LogID)
  613. return nil
  614. }
  615. handleTokenCheck := func() error {
  616. uid, _, err := utils.ParseToken(req.Token)
  617. if err != nil {
  618. return err
  619. }
  620. if uid != req.Uid {
  621. return errors.UserTokenillegality
  622. }
  623. /*if level == 0 {
  624. return errors.AuthNotAllow
  625. }*/
  626. return nil
  627. }
  628. handleDataTask := func() error {
  629. mreq := gd_statistics.LogQueryThirdpartInterfaceCountReq{}
  630. mreq.StartTimestamp = req.StartTimestamp
  631. mreq.EndTimestamp = req.EndTimestamp
  632. mreq.ProviderApiId = req.ProviderApiId
  633. mreq.PageNumber = req.PageNumber
  634. mreq.PageSize = req.PageSize
  635. reply, err := rpc_apis.Statistics.LogQueryThirdpartInterfaceCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  636. if err != nil {
  637. l.Error("rpc",
  638. zap.String("call", "LogQueryThirdpartInterfaceCount"),
  639. zap.String("args", utils.MarshalJsonString(req)),
  640. zap.String("error", err.Error()))
  641. return errors.ErrorTransform(err)
  642. }
  643. resp := param_v1_0.LogQueryThirdpartInterfaceCountResp{
  644. SimpleResp: param_base.SimpleResp{
  645. Code: 0,
  646. Msg: "SUCCESS",
  647. },
  648. }
  649. resp.Data = reply
  650. httper.JSON(u.Ctx, resp, u.LogID)
  651. return nil
  652. }
  653. // 执行以上定义的任务
  654. task.Do(&task.PanicRecover{
  655. Ctx: u.Ctx,
  656. LogID: u.LogID}, u.Ctx,
  657. getParamsTask, handleTokenCheck, handleDataTask,
  658. )
  659. }
  660. func ExportUpdate(u *BaseAccessLogController, exportReq *gd_statistics.LogExportCreateReq) {
  661. _, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), exportReq)
  662. if err != nil {
  663. l.Error("rpc",
  664. zap.String("call", "LogExportCreate"),
  665. zap.String("args", utils.MarshalJsonString(exportReq)),
  666. zap.String("error", err.Error()))
  667. }
  668. }
  669. var ErrCodeMutex sync.Mutex
  670. var ErrorCodeMap = map[string]string{}
  671. func IsErrorCodeMapExist() bool {
  672. ErrCodeMutex.Lock()
  673. defer ErrCodeMutex.Unlock()
  674. if len(ErrorCodeMap) > 0 {
  675. return true
  676. }
  677. return false
  678. }
  679. func SetErrorCodeMap() {
  680. ErrCodeMutex.Lock()
  681. defer ErrCodeMutex.Unlock()
  682. mreq := gd_management.ManagementGetErrorListReq{}
  683. mreq.PageNumber = 1
  684. mreq.IsAll = true
  685. reply, err := rpc_apis.Management.ManagementGetErrorList(context.Background(), &mreq)
  686. if err != nil {
  687. return
  688. }
  689. ErrorCodeMap = map[string]string{}
  690. for _, v := range reply.ErrorCodeList {
  691. ErrorCodeMap[v.Code] = v.Msg
  692. }
  693. }
  694. func makeXlsxErrorHeader(sheet *xlsx.Sheet, codes []gd_statistics.ErrorCodeCount) {
  695. if IsErrorCodeMapExist() == false {
  696. SetErrorCodeMap()
  697. }
  698. row := sheet.AddRow()
  699. cell := row.AddCell()
  700. cell.Value = "日期"
  701. cell = row.AddCell()
  702. cell.Value = "错误总量"
  703. for _, v := range codes {
  704. cell := row.AddCell()
  705. if msg, ok := ErrorCodeMap[v.Code]; ok {
  706. cell.Value = fmt.Sprintf("%s(%s)", v.Code, msg)
  707. } else {
  708. cell.Value = v.Code
  709. }
  710. cell = row.AddCell()
  711. cell.Value = v.Code + "占比"
  712. }
  713. }
  714. func makeXlsxSourceHeader(sheet *xlsx.Sheet, names []gd_statistics.SourceNameCount) {
  715. row := sheet.AddRow()
  716. cell := row.AddCell()
  717. cell.Value = "日期"
  718. cell = row.AddCell()
  719. cell.Value = "来源总量"
  720. for _, v := range names {
  721. cell := row.AddCell()
  722. cell.Value = v.Name
  723. cell = row.AddCell()
  724. cell.Value = v.Name + "占比"
  725. }
  726. }
  727. func makeXlsxHeader(sheet *xlsx.Sheet, timeList string) {
  728. tArray := strings.Split(timeList, ",")
  729. row := sheet.AddRow()
  730. dateCell := row.AddCell()
  731. dateCell.Value = "时间"
  732. //dateCell.HMerge
  733. dateCell.VMerge = 1
  734. cell := row.AddCell()
  735. cell.Value = "总调用量情况"
  736. cell.HMerge = 4
  737. row.AddCell()
  738. row.AddCell()
  739. row.AddCell()
  740. row.AddCell()
  741. cell = row.AddCell()
  742. cell.Value = "有效调用量情况"
  743. cell.HMerge = 10
  744. if len(tArray) > 0 && tArray[0] != "" {
  745. cell.HMerge += len(tArray)
  746. }
  747. row = sheet.AddRow()
  748. row.AddCell()
  749. totalCell := row.AddCell()
  750. totalCell.Value = "调用总量"
  751. validCell := row.AddCell()
  752. validCell.Value = "有效量"
  753. validRateCell := row.AddCell()
  754. validRateCell.Value = "有效率"
  755. chargeCell := row.AddCell()
  756. chargeCell.Value = "计费量"
  757. chargeRateCell := row.AddCell()
  758. chargeRateCell.Value = "计费率"
  759. successCell := row.AddCell()
  760. successCell.Value = "成功量"
  761. successRateCell := row.AddCell()
  762. successRateCell.Value = "成功率"
  763. queryCell := row.AddCell()
  764. queryCell.Value = "查得量"
  765. queryRateCell := row.AddCell()
  766. queryRateCell.Value = "查得率"
  767. reuseCell := row.AddCell()
  768. reuseCell.Value = "复用量"
  769. reuseRateCell := row.AddCell()
  770. reuseRateCell.Value = "复用率"
  771. platformErrorCell := row.AddCell()
  772. platformErrorCell.Value = "平台异常量"
  773. platformErrorRateCell := row.AddCell()
  774. platformErrorRateCell.Value = "平台异常率"
  775. providerErrorCell := row.AddCell()
  776. providerErrorCell.Value = "数据源异常量"
  777. providerErrorRateCell := row.AddCell()
  778. providerErrorRateCell.Value = "数据源异常率"
  779. avgElapsedCell := row.AddCell()
  780. avgElapsedCell.Value = "平均时长"
  781. offset := 17
  782. for i, v := range tArray {
  783. if v == "" {
  784. return
  785. }
  786. cell := row.AddCell()
  787. cell.Value = fmt.Sprintf("时长大于%s秒", v)
  788. sheet.SetColWidth(17+i, 17+i, 20)
  789. offset++
  790. }
  791. for i, v := range tArray {
  792. if v == "" {
  793. return
  794. }
  795. cell := row.AddCell()
  796. cell.Value = fmt.Sprintf("计费调用中时长大于%s秒", v)
  797. sheet.SetColWidth(offset+i, offset+i, 30)
  798. }
  799. }
  800. func makeProviderXlsxHeader(sheet *xlsx.Sheet, timeList string) {
  801. row := sheet.AddRow()
  802. dateCell := row.AddCell()
  803. dateCell.Value = "时间"
  804. nameCell := row.AddCell()
  805. nameCell.Value = "供应商"
  806. totalCell := row.AddCell()
  807. totalCell.Value = "总量"
  808. successCell := row.AddCell()
  809. successCell.Value = "成功"
  810. failCell := row.AddCell()
  811. failCell.Value = "失败"
  812. failRateCell := row.AddCell()
  813. failRateCell.Value = "失败率"
  814. queryCell := row.AddCell()
  815. queryCell.Value = "查得"
  816. queryNoRecordCell := row.AddCell()
  817. queryNoRecordCell.Value = "查无"
  818. queryNoRecordRateCell := row.AddCell()
  819. queryNoRecordRateCell.Value = "查无率"
  820. avgElapsedCell := row.AddCell()
  821. avgElapsedCell.Value = "平均时长"
  822. tArray := strings.Split(timeList, ",")
  823. for _, v := range tArray {
  824. if v == "" {
  825. break
  826. }
  827. cell := row.AddCell()
  828. cell.Value = fmt.Sprintf("时长大于%s秒", v)
  829. }
  830. for _, v := range tArray {
  831. if v == "" {
  832. break
  833. }
  834. cell := row.AddCell()
  835. cell.Value = fmt.Sprintf("计费调用中时长大于%s秒", v)
  836. }
  837. }
  838. func parseSumRate(rate string) string {
  839. array := strings.Split(rate, "-")
  840. total := float64(0)
  841. for _, v := range array {
  842. valuestring := strings.TrimRight(v, "%")
  843. value, _ := strconv.ParseFloat(valuestring, 64)
  844. total += value
  845. }
  846. ret := strconv.FormatFloat(float64(total)/float64(len(array)), 'f', 3, 64) + "%"
  847. return ret
  848. }
  849. func parseSum(sum *gd_statistics.LogQueryUserAcessCountExport, sheet *xlsx.Sheet) {
  850. row := sheet.AddRow()
  851. if sum.Total == 0 {
  852. sum.ValidRate = "0%"
  853. sum.ChargeRate = "0%"
  854. } else {
  855. sum.ValidRate = strconv.FormatFloat(float64(100*sum.Valid)/float64(sum.Total), 'f', 2, 64) + "%"
  856. sum.ChargeRate = strconv.FormatFloat(float64(100*sum.Charge)/float64(sum.Total), 'f', 2, 64) + "%"
  857. }
  858. if sum.Valid == 0 {
  859. sum.QueryRate = "0%"
  860. sum.SuccessRate = "0%"
  861. sum.ReuseRate = "0%"
  862. } else {
  863. sum.QueryRate = strconv.FormatFloat(float64(100*sum.Query)/float64(sum.Valid), 'f', 2, 64) + "%"
  864. sum.SuccessRate = strconv.FormatFloat(float64(100*sum.Success)/float64(sum.Valid), 'f', 2, 64) + "%"
  865. sum.ReuseRate = strconv.FormatFloat(float64(100*sum.Reuse)/float64(sum.Valid), 'f', 2, 64) + "%"
  866. sum.PlatformErrorRate = strconv.FormatFloat(float64(100*sum.PlatformError)/float64(sum.Valid), 'f', 2, 64) + "%"
  867. sum.ProviderErrorRate = strconv.FormatFloat(float64(100*sum.ProviderError)/float64(sum.Valid), 'f', 2, 64) + "%"
  868. }
  869. dateCell := row.AddCell()
  870. dateCell.Value = sum.Date
  871. totalCell := row.AddCell()
  872. totalCell.SetInt(int(sum.Total))
  873. validCell := row.AddCell()
  874. validCell.SetInt(int(sum.Valid))
  875. validRateCell := row.AddCell()
  876. validRateCell.Value = sum.ValidRate
  877. SetPercentForXlsx(sum.ValidRate, validRateCell)
  878. chargeCell := row.AddCell()
  879. chargeCell.SetInt(sum.Charge)
  880. chargeRateCell := row.AddCell()
  881. SetPercentForXlsx(sum.ChargeRate, chargeRateCell)
  882. successCell := row.AddCell()
  883. successCell.SetInt(sum.Success)
  884. successRateCell := row.AddCell()
  885. SetPercentForXlsx(sum.SuccessRate, successRateCell)
  886. queryCell := row.AddCell()
  887. queryCell.SetInt(sum.Query)
  888. queryRateCell := row.AddCell()
  889. SetPercentForXlsx(sum.QueryRate, queryRateCell)
  890. reuseCell := row.AddCell()
  891. reuseCell.SetInt(sum.Reuse)
  892. reuseRateCell := row.AddCell()
  893. SetPercentForXlsx(sum.ReuseRate, reuseRateCell)
  894. platformErrorCell := row.AddCell()
  895. platformErrorCell.SetInt(sum.PlatformError)
  896. platformErrorRateCell := row.AddCell()
  897. SetPercentForXlsx(sum.PlatformErrorRate, platformErrorRateCell)
  898. providerErrorCell := row.AddCell()
  899. providerErrorCell.SetInt(sum.ProviderError)
  900. providerErrorRateCell := row.AddCell()
  901. SetPercentForXlsx(sum.ProviderErrorRate, providerErrorRateCell)
  902. avgElapsedCell := row.AddCell()
  903. sum.AvgElapsed = sum.SumElapsed / float64(sum.Total)
  904. elStr := strconv.FormatFloat(sum.AvgElapsed, 'f', 2, 64)
  905. el, _ := strconv.ParseFloat(elStr, 64)
  906. avgElapsedCell.SetFloatWithFormat(el, "0.00")
  907. for _, v := range sum.BigElapsedList {
  908. cell := row.AddCell()
  909. cell.SetInt(v)
  910. }
  911. for _, v := range sum.ChargeBigElapsedList {
  912. cell := row.AddCell()
  913. cell.SetInt(v)
  914. }
  915. }
  916. func parseProviderSum(sum *gd_statistics.LogQueryProviderCountExport, sheet *xlsx.Sheet) {
  917. row := sheet.AddRow()
  918. if sum.Total == 0 {
  919. sum.FailedRate = "0%"
  920. sum.QueryNoRecordRate = "0%"
  921. } else {
  922. sum.FailedRate = strconv.FormatFloat(float64(100*sum.Failed)/float64(sum.Total), 'f', 2, 64) + "%"
  923. sum.QueryNoRecordRate = strconv.FormatFloat(float64(100*sum.QueryNoRecord)/float64(sum.Total), 'f', 2, 64) + "%"
  924. }
  925. dateCell := row.AddCell()
  926. dateCell.Value = sum.Date
  927. nameCell := row.AddCell()
  928. nameCell.Value = " "
  929. totalCell := row.AddCell()
  930. totalCell.SetInt(int(sum.Total))
  931. successCell := row.AddCell()
  932. successCell.SetInt(int(sum.Success))
  933. failedCell := row.AddCell()
  934. failedCell.SetInt(int(sum.Failed))
  935. failedRateCell := row.AddCell()
  936. SetPercentForXlsx(sum.FailedRate, failedRateCell)
  937. queryCell := row.AddCell()
  938. queryCell.SetInt(int(sum.Query))
  939. queryNoRecordCell := row.AddCell()
  940. queryNoRecordCell.SetInt(int(sum.QueryNoRecord))
  941. queryNoRecordRateCell := row.AddCell()
  942. SetPercentForXlsx(sum.QueryNoRecordRate, queryNoRecordRateCell)
  943. avgElapsedCell := row.AddCell()
  944. elStr := strconv.FormatFloat(sum.SumElapsed/float64(sum.Total), 'f', 2, 64)
  945. el, _ := strconv.ParseFloat(elStr, 64)
  946. avgElapsedCell.SetFloatWithFormat(el, "0.00")
  947. for _, v := range sum.BigElapsedList {
  948. cell := row.AddCell()
  949. cell.SetInt(v)
  950. }
  951. for _, v := range sum.ChargeBigElapsedList {
  952. cell := row.AddCell()
  953. cell.SetInt(v)
  954. }
  955. }
  956. func parseErrorsCount(reply *gd_statistics.LogQueryUserAccessCountExportReply, file *xlsx.File) error {
  957. table := make(map[string][]gd_statistics.ErrorExport, 0)
  958. for index, _ := range reply.ErrorCount {
  959. table[reply.ErrorCount[index].ApiName] = append(table[reply.ErrorCount[index].ApiName], reply.ErrorCount[index])
  960. }
  961. if len(table) == 0 {
  962. file.AddSheet("空")
  963. }
  964. for k, v := range table {
  965. sheet, err := file.AddSheet(k + "失败分布")
  966. if err != nil {
  967. return err
  968. }
  969. makeXlsxErrorHeader(sheet, v[0].Errors)
  970. sumTotal := 0
  971. sumRate := make([]gd_statistics.ErrorCodeCount, len(v[0].Errors))
  972. for index, _ := range v {
  973. row := sheet.AddRow()
  974. cell := row.AddCell()
  975. cell.Value = v[index].Date
  976. cell = row.AddCell()
  977. cell.Value = fmt.Sprintf("%d", v[index].Total)
  978. sumTotal += v[index].Total
  979. for i := 0; i < len(v[index].Errors); i++ {
  980. cell := row.AddCell()
  981. cell.Value = fmt.Sprintf("%d", v[index].Errors[i].Count)
  982. cell = row.AddCell()
  983. cell.Value = v[index].Errors[i].Rate
  984. sumRate[i].Count += v[index].Errors[i].Count
  985. }
  986. }
  987. row := sheet.AddRow()
  988. cell := row.AddCell()
  989. cell.Value = "总"
  990. cell = row.AddCell()
  991. cell.Value = fmt.Sprintf("%d", sumTotal)
  992. for i := 0; i < len(sumRate); i++ {
  993. cell = row.AddCell()
  994. cell.Value = fmt.Sprintf("%d", sumRate[i].Count)
  995. cell = row.AddCell()
  996. cell.Value = strconv.FormatFloat(float64(100*sumRate[i].Count)/float64(sumTotal), 'f', 2, 64) + "%"
  997. }
  998. }
  999. return nil
  1000. }
  1001. func parseSourceCount(reply *gd_statistics.LogQueryUserAccessCountExportReply, file *xlsx.File) error {
  1002. table := make(map[string][]gd_statistics.SourceExport, 0)
  1003. for index, _ := range reply.SourceCount {
  1004. table[reply.SourceCount[index].ApiName] = append(table[reply.SourceCount[index].ApiName], reply.SourceCount[index])
  1005. }
  1006. if len(table) == 0 {
  1007. file.AddSheet("空")
  1008. }
  1009. for k, v := range table {
  1010. sheet, err := file.AddSheet(k + "来源分布")
  1011. if err != nil {
  1012. return err
  1013. }
  1014. makeXlsxSourceHeader(sheet, v[0].Sources)
  1015. sumTotal := 0
  1016. sumRate := make([]gd_statistics.SourceNameCount, len(v[0].Sources))
  1017. for index, _ := range v {
  1018. row := sheet.AddRow()
  1019. cell := row.AddCell()
  1020. cell.Value = v[index].Date
  1021. cell = row.AddCell()
  1022. cell.Value = fmt.Sprintf("%d", v[index].Total)
  1023. sumTotal += v[index].Total
  1024. for i := 0; i < len(v[index].Sources); i++ {
  1025. cell := row.AddCell()
  1026. cell.Value = fmt.Sprintf("%d", v[index].Sources[i].Count)
  1027. cell = row.AddCell()
  1028. cell.Value = v[index].Sources[i].Rate
  1029. sumRate[i].Count += v[index].Sources[i].Count
  1030. }
  1031. }
  1032. row := sheet.AddRow()
  1033. cell := row.AddCell()
  1034. cell.Value = "总"
  1035. cell = row.AddCell()
  1036. cell.Value = fmt.Sprintf("%d", sumTotal)
  1037. for i := 0; i < len(sumRate); i++ {
  1038. cell = row.AddCell()
  1039. cell.Value = fmt.Sprintf("%d", sumRate[i].Count)
  1040. cell = row.AddCell()
  1041. cell.Value = strconv.FormatFloat(float64(100*sumRate[i].Count)/float64(sumTotal), 'f', 2, 64) + "%"
  1042. }
  1043. }
  1044. return nil
  1045. }
  1046. func sumBigElapseds(oldList []int, newList []int) []int {
  1047. if len(oldList) == 0 {
  1048. return newList
  1049. }
  1050. if len(oldList) != len(newList) {
  1051. return oldList
  1052. }
  1053. for i, _ := range oldList {
  1054. oldList[i] = oldList[i] + newList[i]
  1055. }
  1056. return oldList
  1057. }
  1058. func setAllCells(file *xlsx.File) {
  1059. style := xlsx.NewStyle()
  1060. font := xlsx.NewFont(10, "Microsoft YaHei")
  1061. style.Font = *font
  1062. style.Border = *xlsx.NewBorder("thin", "none", "thin", "thin")
  1063. headerStyle := xlsx.NewStyle()
  1064. fill := xlsx.NewFill("solid", "00B0C4DE", "00000000")
  1065. headerStyle.Font = *font
  1066. headerStyle.Fill = *fill
  1067. headerStyle.Border = *xlsx.NewBorder("thin", "none", "thin", "thin")
  1068. sheets := file.Sheets
  1069. for i := 0; i < len(sheets); i++ {
  1070. rows := sheets[i].Rows
  1071. for j := 0; j < len(rows); j++ {
  1072. cells := rows[j].Cells
  1073. for k := 0; k < len(cells); k++ {
  1074. if j < 2 {
  1075. cells[k].SetStyle(headerStyle)
  1076. } else {
  1077. cells[k].SetStyle(style)
  1078. }
  1079. }
  1080. }
  1081. }
  1082. }
  1083. func parseAccessCount(reply *gd_statistics.LogQueryUserAccessCountExportReply, file *xlsx.File, timeList string) error {
  1084. table := make(map[string][]gd_statistics.LogQueryUserAcessCountExport, 0)
  1085. for index, _ := range reply.LogQueryUserAcessCount {
  1086. table[reply.LogQueryUserAcessCount[index].ApiName] = append(table[reply.LogQueryUserAcessCount[index].ApiName], reply.LogQueryUserAcessCount[index])
  1087. }
  1088. if len(table) == 0 {
  1089. file.AddSheet("空")
  1090. }
  1091. for k, v := range table {
  1092. sheet, err := file.AddSheet(k + "指标")
  1093. if err != nil {
  1094. return err
  1095. }
  1096. makeXlsxHeader(sheet, timeList)
  1097. sum := gd_statistics.LogQueryUserAcessCountExport{}
  1098. sum.Date = "总"
  1099. for index, _ := range v {
  1100. row := sheet.AddRow()
  1101. dateCell := row.AddCell()
  1102. dateCell.Value = v[index].Date
  1103. totalCell := row.AddCell()
  1104. sum.Total += int(v[index].Total)
  1105. totalCell.SetInt(int(v[index].Total))
  1106. validCell := row.AddCell()
  1107. sum.Valid += int(v[index].Valid)
  1108. validCell.SetInt(int(v[index].Valid))
  1109. validRateCell := row.AddCell()
  1110. SetPercentForXlsx(v[index].ValidRate, validRateCell)
  1111. chargeCell := row.AddCell()
  1112. sum.Charge += int(v[index].Charge)
  1113. chargeCell.SetInt(int(v[index].Charge))
  1114. chargeRateCell := row.AddCell()
  1115. SetPercentForXlsx(v[index].ChargeRate, chargeRateCell)
  1116. successCell := row.AddCell()
  1117. successCell.SetInt(v[index].Success)
  1118. sum.Success += v[index].Success
  1119. successRateCell := row.AddCell()
  1120. SetPercentForXlsx(v[index].SuccessRate, successRateCell)
  1121. queryCell := row.AddCell()
  1122. queryCell.SetInt(v[index].Query)
  1123. sum.Query += v[index].Query
  1124. queryRateCell := row.AddCell()
  1125. SetPercentForXlsx(v[index].QueryRate, queryRateCell)
  1126. reuseCell := row.AddCell()
  1127. reuseCell.SetInt(v[index].Reuse)
  1128. sum.Reuse += v[index].Reuse
  1129. reuseRateCell := row.AddCell()
  1130. SetPercentForXlsx(v[index].ReuseRate, reuseRateCell)
  1131. platformErrorCell := row.AddCell()
  1132. platformErrorCell.SetInt(v[index].PlatformError)
  1133. sum.PlatformError += v[index].PlatformError
  1134. platformErrorRateCell := row.AddCell()
  1135. SetPercentForXlsx(v[index].PlatformErrorRate, platformErrorRateCell)
  1136. providerErrorCell := row.AddCell()
  1137. providerErrorCell.SetInt(v[index].ProviderError)
  1138. sum.ProviderError += v[index].ProviderError
  1139. providerErrorRateCell := row.AddCell()
  1140. SetPercentForXlsx(v[index].ProviderErrorRate, providerErrorRateCell)
  1141. avgElapsedCell := row.AddCell()
  1142. elStr := strconv.FormatFloat(v[index].AvgElapsed, 'f', 2, 64)
  1143. el, _ := strconv.ParseFloat(elStr, 64)
  1144. avgElapsedCell.SetFloatWithFormat(el, "0.00")
  1145. sum.SumElapsed += v[index].SumElapsed
  1146. for _, big := range v[index].BigElapsedList {
  1147. cell := row.AddCell()
  1148. cell.SetInt(big)
  1149. }
  1150. sum.BigElapsedList = sumBigElapseds(sum.BigElapsedList, v[index].BigElapsedList)
  1151. for _, big := range v[index].ChargeBigElapsedList {
  1152. cell := row.AddCell()
  1153. cell.SetInt(big)
  1154. }
  1155. sum.ChargeBigElapsedList = sumBigElapseds(sum.ChargeBigElapsedList, v[index].ChargeBigElapsedList)
  1156. }
  1157. parseSum(&sum, sheet)
  1158. }
  1159. return nil
  1160. }
  1161. // @Title 访问日志用户统计报表导出
  1162. // @Description 访问日志用户统计报表导出
  1163. // @Param token header string true "token"
  1164. // @Param uid header int64 true "admin id"
  1165. // @Param export body rpc_apis.gd_statistics.LogQueryUserAccessCountExportReq true "数据源"
  1166. // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountResp "响应信息"
  1167. // @Failure 500 服务器错误
  1168. // @router /user_access_count_export [post]
  1169. func (u *BaseAccessLogController) LogQueryUserAccessCountExport() {
  1170. u.LogID = fmt.Sprintf("LogQueryUserAccessCountExport[%d]", time.Now().UnixNano())
  1171. req := &param_v1_0.LogQueryUserAccessCountExportReq{}
  1172. getParamsTask := func() error {
  1173. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1174. return nil
  1175. }
  1176. handleTokenCheck := func() error {
  1177. uid, _, err := utils.ParseToken(req.Token)
  1178. if err != nil {
  1179. return err
  1180. }
  1181. if uid != req.Uid {
  1182. return errors.UserTokenillegality
  1183. }
  1184. /*if level == 0 {
  1185. return errors.AuthNotAllow
  1186. }*/
  1187. return nil
  1188. }
  1189. handleDataTask := func() error {
  1190. exportReq := gd_statistics.LogExportCreateReq{}
  1191. exportReq.Status = "开始"
  1192. exportReq.FileName = req.Export.ExportName
  1193. if exportReq.FileName == "" {
  1194. return errors.ArgsError
  1195. }
  1196. host := u.Ctx.Request.Host
  1197. if strings.Contains(ServerIp, "0.0.0.0") == false {
  1198. host = ServerIp + ":" + ServerPort
  1199. } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
  1200. host = u.Ctx.Request.Host + ":" + ServerPort
  1201. }
  1202. exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
  1203. if true {
  1204. exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
  1205. }
  1206. exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
  1207. if err != nil {
  1208. l.Error("rpc",
  1209. zap.String("call", "LogExportCreate"),
  1210. zap.String("args", utils.MarshalJsonString(req)),
  1211. zap.String("error", err.Error()))
  1212. return errors.ErrorTransform(err)
  1213. }
  1214. exportReq.Id = exportReply.Id
  1215. defer ExportUpdate(u, &exportReq)
  1216. mreq := gd_statistics.LogQueryUserAccessCountExportReq{}
  1217. mreq.StartTimestamp = req.Export.StartTimestamp
  1218. mreq.EndTimestamp = req.Export.EndTimestamp
  1219. mreq.ApiIdList = req.Export.ApiIdList
  1220. mreq.MerchantId = req.Export.MerchantId
  1221. mreq.TimeList = req.Export.TimeList
  1222. reply, err := rpc_apis.Statistics.LogQueryUserAccessCountExport(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1223. if err != nil {
  1224. l.Error("rpc",
  1225. zap.String("call", "LogQueryUserAccessCountExport"),
  1226. zap.String("args", utils.MarshalJsonString(req)),
  1227. zap.String("error", err.Error()))
  1228. exportReq.Status = "失败"
  1229. return errors.ErrorTransform(err)
  1230. }
  1231. resp := param_v1_0.LogQueryUserAccessCountExportResp{
  1232. SimpleResp: param_base.SimpleResp{
  1233. Code: 0,
  1234. Msg: "SUCCESS",
  1235. },
  1236. }
  1237. file := xlsx.NewFile()
  1238. if err := parseAccessCount(&reply, file, mreq.TimeList); err != nil {
  1239. exportReq.Status = "失败"
  1240. return err
  1241. }
  1242. if err := parseErrorsCount(&reply, file); err != nil {
  1243. exportReq.Status = "失败"
  1244. return err
  1245. }
  1246. if err := parseSourceCount(&reply, file); err != nil {
  1247. exportReq.Status = "失败"
  1248. return err
  1249. }
  1250. setAllCells(file)
  1251. err = file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
  1252. if true {
  1253. utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
  1254. }
  1255. //resp.Data = reply
  1256. if err != nil {
  1257. exportReq.Status = "失败"
  1258. } else {
  1259. exportReq.Status = "完成"
  1260. }
  1261. httper.JSON(u.Ctx, resp, u.LogID)
  1262. return err
  1263. }
  1264. // 执行以上定义的任务
  1265. task.Do(&task.PanicRecover{
  1266. Ctx: u.Ctx,
  1267. LogID: u.LogID}, u.Ctx,
  1268. getParamsTask, handleTokenCheck, handleDataTask,
  1269. )
  1270. }
  1271. // @Title 数据源日志用户统计报表导出
  1272. // @Description 数据源日志用户统计报表导出
  1273. // @Param token header string true "token"
  1274. // @Param uid header int64 true "admin id"
  1275. // @Param export body rpc_apis.gd_statistics.LogQueryProviderCountExportReq true ""
  1276. // @Success 200 {object} params.param_v1_0.LogQueryProviderCountExportResp "响应信息"
  1277. // @Failure 500 服务器错误
  1278. // @router /provider_count_export [post]
  1279. func (u *BaseAccessLogController) LogQueryProviderCountExport() {
  1280. u.LogID = fmt.Sprintf("LogQueryProviderCountExport[%d]", time.Now().UnixNano())
  1281. req := &param_v1_0.LogQueryProviderCountExportReq{}
  1282. getParamsTask := func() error {
  1283. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1284. return nil
  1285. }
  1286. handleTokenCheck := func() error {
  1287. uid, _, err := utils.ParseToken(req.Token)
  1288. if err != nil {
  1289. return err
  1290. }
  1291. if uid != req.Uid {
  1292. return errors.UserTokenillegality
  1293. }
  1294. /*if level == 0 {
  1295. return errors.AuthNotAllow
  1296. }*/
  1297. return nil
  1298. }
  1299. handleDataTask := func() error {
  1300. exportReq := gd_statistics.LogExportCreateReq{}
  1301. exportReq.ExportType = 1
  1302. exportReq.Status = "开始"
  1303. exportReq.FileName = req.Export.ExportName
  1304. if exportReq.FileName == "" {
  1305. return errors.ArgsError
  1306. }
  1307. host := u.Ctx.Request.Host
  1308. if strings.Contains(ServerIp, "0.0.0.0") == false {
  1309. host = ServerIp + ":" + ServerPort
  1310. } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
  1311. host = u.Ctx.Request.Host + ":" + ServerPort
  1312. }
  1313. exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
  1314. if true {
  1315. exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
  1316. }
  1317. exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
  1318. if err != nil {
  1319. l.Error("rpc",
  1320. zap.String("call", "LogExportCreate"),
  1321. zap.String("args", utils.MarshalJsonString(req)),
  1322. zap.String("error", err.Error()))
  1323. return errors.ErrorTransform(err)
  1324. }
  1325. exportReq.Id = exportReply.Id
  1326. defer ExportUpdate(u, &exportReq)
  1327. mreq := gd_statistics.LogQueryProviderCountExportReq{}
  1328. mreq.StartTimestamp = req.Export.StartTimestamp
  1329. mreq.EndTimestamp = req.Export.EndTimestamp
  1330. mreq.ProviderApiIdList = req.Export.ProviderApiIdList
  1331. mreq.ProviderId = req.Export.ProviderId
  1332. mreq.TimeList = req.Export.TimeList
  1333. reply, err := rpc_apis.Statistics.LogQueryProviderCountExport(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1334. if err != nil {
  1335. l.Error("rpc",
  1336. zap.String("call", "LogQueryProviderCountExport"),
  1337. zap.String("args", utils.MarshalJsonString(req)),
  1338. zap.String("error", err.Error()))
  1339. exportReq.Status = "失败"
  1340. return errors.ErrorTransform(err)
  1341. }
  1342. resp := param_v1_0.LogQueryProviderCountExportResp{
  1343. SimpleResp: param_base.SimpleResp{
  1344. Code: 0,
  1345. Msg: "SUCCESS",
  1346. },
  1347. }
  1348. table := make(map[string][]gd_statistics.LogQueryProviderCountExport, 0)
  1349. for index, _ := range reply.LogQueryProviderCount {
  1350. table[reply.LogQueryProviderCount[index].ProviderApiName] = append(table[reply.LogQueryProviderCount[index].ProviderApiName], reply.LogQueryProviderCount[index])
  1351. }
  1352. file := xlsx.NewFile()
  1353. if len(table) == 0 {
  1354. file.AddSheet("空")
  1355. }
  1356. for k, v := range table {
  1357. sheet, err := file.AddSheet(k)
  1358. if err != nil {
  1359. exportReq.Status = "失败"
  1360. return err
  1361. }
  1362. makeProviderXlsxHeader(sheet, mreq.TimeList)
  1363. sum := gd_statistics.LogQueryProviderCountExport{}
  1364. sum.Date = "总"
  1365. for index, _ := range v {
  1366. row := sheet.AddRow()
  1367. dateCell := row.AddCell()
  1368. dateCell.Value = v[index].Date
  1369. nameCell := row.AddCell()
  1370. nameCell.Value = v[index].ProviderName
  1371. totalCell := row.AddCell()
  1372. sum.Total += v[index].Total
  1373. totalCell.SetInt(int(v[index].Total))
  1374. successCell := row.AddCell()
  1375. sum.Success += v[index].Success
  1376. successCell.SetInt(int(v[index].Success))
  1377. failedCell := row.AddCell()
  1378. sum.Failed += v[index].Failed
  1379. failedCell.SetInt(int(v[index].Failed))
  1380. failedRateCell := row.AddCell()
  1381. SetPercentForXlsx(v[index].FailedRate, failedRateCell)
  1382. queryCell := row.AddCell()
  1383. queryCell.SetInt(int(v[index].Query))
  1384. sum.Query += v[index].Query
  1385. queryNoRecordCell := row.AddCell()
  1386. queryNoRecordCell.SetInt(int(v[index].QueryNoRecord))
  1387. sum.QueryNoRecord += v[index].QueryNoRecord
  1388. queryNoRecordRateCell := row.AddCell()
  1389. SetPercentForXlsx(v[index].QueryNoRecordRate, queryNoRecordRateCell)
  1390. avgElapsedCell := row.AddCell()
  1391. elStr := strconv.FormatFloat(v[index].AvgElapsed, 'f', 2, 64)
  1392. el, _ := strconv.ParseFloat(elStr, 64)
  1393. avgElapsedCell.SetFloatWithFormat(el, "0.00")
  1394. sum.AvgElapsed += v[index].AvgElapsed
  1395. sum.SumElapsed += v[index].SumElapsed
  1396. for _, big := range v[index].BigElapsedList {
  1397. cell := row.AddCell()
  1398. cell.SetInt(big)
  1399. }
  1400. sum.BigElapsedList = sumBigElapseds(sum.BigElapsedList, v[index].BigElapsedList)
  1401. for _, big := range v[index].ChargeBigElapsedList {
  1402. cell := row.AddCell()
  1403. cell.SetInt(big)
  1404. }
  1405. sum.ChargeBigElapsedList = sumBigElapseds(sum.ChargeBigElapsedList, v[index].ChargeBigElapsedList)
  1406. }
  1407. parseProviderSum(&sum, sheet)
  1408. }
  1409. err = file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
  1410. if true {
  1411. utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
  1412. }
  1413. //resp.Data = reply
  1414. if err != nil {
  1415. exportReq.Status = "失败"
  1416. } else {
  1417. exportReq.Status = "完成"
  1418. }
  1419. httper.JSON(u.Ctx, resp, u.LogID)
  1420. return err
  1421. }
  1422. // 执行以上定义的任务
  1423. task.Do(&task.PanicRecover{
  1424. Ctx: u.Ctx,
  1425. LogID: u.LogID}, u.Ctx,
  1426. getParamsTask, handleTokenCheck, handleDataTask,
  1427. )
  1428. }
  1429. var exportStatusMap = map[string]int{
  1430. "开始": 1,
  1431. "完成": 2,
  1432. "失败": 3,
  1433. }
  1434. // 导出文件时去掉文件后的时间戳后缀
  1435. func convertExportFileName(src string) string {
  1436. array := strings.Split(src, "_")
  1437. length := len(array)
  1438. if length < 2 {
  1439. return src
  1440. }
  1441. timestampString := array[length-1]
  1442. if len([]byte(timestampString)) < 19 {
  1443. return src
  1444. }
  1445. _, err := strconv.ParseInt(timestampString, 10, 64)
  1446. if err != nil {
  1447. return src
  1448. }
  1449. return strings.TrimRight(src, "_"+timestampString)
  1450. }
  1451. // @Title 获取导出列表
  1452. // @Description 获取导出列表
  1453. // @Param token header string true "token"
  1454. // @Param uid header int64 true "admin id"
  1455. // @Param page_number query int64 false "当前页"
  1456. // @Param is_all query bool false "是否返回所有"
  1457. // @Param export_type query int false "api报表或数据源列表"
  1458. // @Success 200 {object} params.param_v1_0.LogExportListResp "响应信息"
  1459. // @Failure 500 服务器错误
  1460. // @router /exports [get]
  1461. func (u *BaseAccessLogController) LogExportList() {
  1462. u.LogID = fmt.Sprintf("LogExportList[%d]", time.Now().UnixNano())
  1463. req := &param_v1_0.LogExportListReq{}
  1464. getParamsTask := func() error {
  1465. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1466. return nil
  1467. }
  1468. handleTokenCheck := func() error {
  1469. uid, _, err := utils.ParseToken(req.Token)
  1470. if err != nil {
  1471. return err
  1472. }
  1473. if uid != req.Uid {
  1474. return errors.UserTokenillegality
  1475. }
  1476. /*if level == 0 {
  1477. return errors.AuthNotAllow
  1478. }*/
  1479. return nil
  1480. }
  1481. handleDataTask := func() error {
  1482. mreq := gd_statistics.LogExportListReq{}
  1483. mreq.PageNumber = req.PageNumber
  1484. mreq.IsAll = req.IsAll
  1485. mreq.ExportType = req.ExportType
  1486. reply, err := rpc_apis.Statistics.LogExportList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1487. if err != nil {
  1488. l.Error("rpc",
  1489. zap.String("call", "LogExportList"),
  1490. zap.String("args", utils.MarshalJsonString(req)),
  1491. zap.String("error", err.Error()))
  1492. return errors.ErrorTransform(err)
  1493. }
  1494. resp := param_v1_0.LogExportListResp{
  1495. SimpleResp: param_base.SimpleResp{
  1496. Code: 0,
  1497. Msg: "SUCCESS",
  1498. },
  1499. }
  1500. for i, v := range reply.ExportList {
  1501. reply.ExportList[i].StatusCode, _ = exportStatusMap[v.Status]
  1502. reply.ExportList[i].FileName = convertExportFileName(v.FileName)
  1503. }
  1504. resp.Data = reply
  1505. httper.JSON(u.Ctx, resp, u.LogID)
  1506. return nil
  1507. }
  1508. // 执行以上定义的任务
  1509. task.Do(&task.PanicRecover{
  1510. Ctx: u.Ctx,
  1511. LogID: u.LogID}, u.Ctx,
  1512. getParamsTask, handleTokenCheck, handleDataTask,
  1513. )
  1514. }
  1515. // @Title 删除导出报表
  1516. // @Description 删除导出报表
  1517. // @Param token header string true "token"
  1518. // @Param uid header int64 true "admin id"
  1519. // @Param id query int64 false "导出报告id"
  1520. // @Success 200 {object} params.param_v1_0.LogExportDeleteResp "响应信息"
  1521. // @Failure 500 服务器错误
  1522. // @router /export [delete]
  1523. func (u *BaseAccessLogController) LogExportDelete() {
  1524. u.LogID = fmt.Sprintf("LogExportDelete[%d]", time.Now().UnixNano())
  1525. req := &param_v1_0.LogExportDeleteReq{}
  1526. getParamsTask := func() error {
  1527. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1528. return nil
  1529. }
  1530. handleTokenCheck := func() error {
  1531. uid, _, err := utils.ParseToken(req.Token)
  1532. if err != nil {
  1533. return err
  1534. }
  1535. if uid != req.Uid {
  1536. return errors.UserTokenillegality
  1537. }
  1538. /*if level == 0 {
  1539. return errors.AuthNotAllow
  1540. }*/
  1541. return nil
  1542. }
  1543. handleDataTask := func() error {
  1544. mreq := gd_statistics.LogExportDeleteReq{}
  1545. mreq.Id = req.Id
  1546. mreq.ExportDir = beego.BConfig.WebConfig.StaticDir["/export"]
  1547. reply, err := rpc_apis.Statistics.LogExportDelete(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1548. if err != nil {
  1549. l.Error("rpc",
  1550. zap.String("call", "LogExportDelete"),
  1551. zap.String("args", utils.MarshalJsonString(req)),
  1552. zap.String("error", err.Error()))
  1553. return errors.ErrorTransform(err)
  1554. }
  1555. if reply.RealPath != "" {
  1556. cache.Redis.Publish(BatchRemoveFileNotifyChannel, reply.RealPath)
  1557. }
  1558. resp := param_v1_0.LogExportDeleteResp{
  1559. SimpleResp: param_base.SimpleResp{
  1560. Code: 0,
  1561. Msg: "SUCCESS",
  1562. },
  1563. }
  1564. //resp.Data = reply
  1565. httper.JSON(u.Ctx, resp, u.LogID)
  1566. return nil
  1567. }
  1568. // 执行以上定义的任务
  1569. task.Do(&task.PanicRecover{
  1570. Ctx: u.Ctx,
  1571. LogID: u.LogID}, u.Ctx,
  1572. getParamsTask, handleTokenCheck, handleDataTask,
  1573. )
  1574. }
  1575. // @Title 访问日志接口异常分析
  1576. // @Description 访问日志接口异常分析
  1577. // @Param token header string true "token"
  1578. // @Param uid header int64 true "admin id"
  1579. // @Param merchant_id query int64 false "商户id"
  1580. // @Param api_id query int64 false "基础api id"
  1581. // @Param start_timestamp query int64 false "开始时间"
  1582. // @Param status query int false "0 全部 1 成功 2 失败"
  1583. // @Param end_timestamp query int64 false "结束时间"
  1584. // @Success 200 {object} params.param_v1_0.LogQueryInterfaceAnalyzeResp "响应信息"
  1585. // @Failure 500 服务器错误
  1586. // @router /access_log_interface_analyze [get]
  1587. func (u *BaseAccessLogController) LogQueryInterfaceAnalyze() {
  1588. u.LogID = fmt.Sprintf("LogQueryInterfaceAnalyze[%d]", time.Now().UnixNano())
  1589. req := &param_v1_0.LogQueryInterfaceCountReq{}
  1590. getParamsTask := func() error {
  1591. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1592. return nil
  1593. }
  1594. handleTokenCheck := func() error {
  1595. uid, _, err := utils.ParseToken(req.Token)
  1596. if err != nil {
  1597. return err
  1598. }
  1599. if uid != req.Uid {
  1600. return errors.UserTokenillegality
  1601. }
  1602. /*if level == 0 {
  1603. return errors.AuthNotAllow
  1604. }*/
  1605. return nil
  1606. }
  1607. handleDataTask := func() error {
  1608. mreq := gd_statistics.LogQueryInterfaceCountReq{}
  1609. mreq.StartTimestamp = req.StartTimestamp
  1610. mreq.EndTimestamp = req.EndTimestamp
  1611. mreq.ApiId = req.ApiId
  1612. mreq.MerchantId = req.MerchantId
  1613. mreq.Option = req.Status
  1614. reply, err := rpc_apis.Statistics.LogQueryInterfaceAnalyzeError(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1615. if err != nil {
  1616. l.Error("rpc",
  1617. zap.String("call", "LogQueryInterfaceAnalyzeError"),
  1618. zap.String("args", utils.MarshalJsonString(req)),
  1619. zap.String("error", err.Error()))
  1620. return errors.ErrorTransform(err)
  1621. }
  1622. resp := param_v1_0.LogQueryInterfaceAnalyzeResp{
  1623. SimpleResp: param_base.SimpleResp{
  1624. Code: 0,
  1625. Msg: "SUCCESS",
  1626. },
  1627. Data: make([]gd_statistics.LogQueryInterfaceAnalyzeError, 0),
  1628. }
  1629. resp.Data = reply.List
  1630. httper.JSON(u.Ctx, resp, u.LogID)
  1631. return nil
  1632. }
  1633. // 执行以上定义的任务
  1634. task.Do(&task.PanicRecover{
  1635. Ctx: u.Ctx,
  1636. LogID: u.LogID}, u.Ctx,
  1637. getParamsTask, handleTokenCheck, handleDataTask,
  1638. )
  1639. }
  1640. // @Title 访问日志接口数据源分析
  1641. // @Description 访问日志接口数据源分析
  1642. // @Param token header string true "token"
  1643. // @Param uid header int64 true "admin id"
  1644. // @Param merchant_id query int64 false "商户id"
  1645. // @Param api_id query int64 false "基础api id"
  1646. // @Param start_timestamp query int64 false "开始时间"
  1647. // @Param end_timestamp query int64 false "结束时间"
  1648. // @Success 200 {object} params.param_v1_0.LogQueryInterfaceAnalyzeResp "响应信息"
  1649. // @Failure 500 服务器错误
  1650. // @router /third_party_analyze [get]
  1651. func (u *BaseAccessLogController) LogQueryThirdPartyAnalyze() {
  1652. u.LogID = fmt.Sprintf("LogQueryThirdPartyAnalyze[%d]", time.Now().UnixNano())
  1653. req := &param_v1_0.LogQueryInterfaceCountReq{}
  1654. getParamsTask := func() error {
  1655. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1656. return nil
  1657. }
  1658. handleTokenCheck := func() error {
  1659. uid, _, err := utils.ParseToken(req.Token)
  1660. if err != nil {
  1661. return err
  1662. }
  1663. if uid != req.Uid {
  1664. return errors.UserTokenillegality
  1665. }
  1666. /*if level == 0 {
  1667. return errors.AuthNotAllow
  1668. }*/
  1669. return nil
  1670. }
  1671. handleDataTask := func() error {
  1672. mreq := gd_statistics.LogQueryInterfaceCountReq{}
  1673. mreq.StartTimestamp = req.StartTimestamp
  1674. mreq.EndTimestamp = req.EndTimestamp
  1675. mreq.ApiId = req.ApiId
  1676. mreq.MerchantId = req.MerchantId
  1677. reply, err := rpc_apis.Statistics.LogQueryInterfaceThirdPartyCount(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1678. if err != nil {
  1679. l.Error("rpc",
  1680. zap.String("call", "LogQueryInterfaceThirdPartyCount"),
  1681. zap.String("args", utils.MarshalJsonString(req)),
  1682. zap.String("error", err.Error()))
  1683. return errors.ErrorTransform(err)
  1684. }
  1685. resp := param_v1_0.ThirdPartyAnalyzeResp{
  1686. SimpleResp: param_base.SimpleResp{
  1687. Code: 0,
  1688. Msg: "SUCCESS",
  1689. },
  1690. Data: make([]gd_statistics.LogQueryInterfaceThirdPartyCount, 0),
  1691. }
  1692. resp.Data = reply.List
  1693. httper.JSON(u.Ctx, resp, u.LogID)
  1694. return nil
  1695. }
  1696. // 执行以上定义的任务
  1697. task.Do(&task.PanicRecover{
  1698. Ctx: u.Ctx,
  1699. LogID: u.LogID}, u.Ctx,
  1700. getParamsTask, handleTokenCheck, handleDataTask,
  1701. )
  1702. }
  1703. // @Title 数据源异常分析
  1704. // @Description 数据源异常分析
  1705. // @Param token header string true "token"
  1706. // @Param uid header int64 true "admin id"
  1707. // @Param provider_api_id query int64 false "基础api id"
  1708. // @Param status query int false "0 全部 1 成功 2 异常"
  1709. // @Param start_timestamp query int64 false "开始时间"
  1710. // @Param end_timestamp query int64 false "结束时间"
  1711. // @Success 200 {object} params.param_v1_0.ThirdPartyInterfaceErrorAnalyzeResp "响应信息"
  1712. // @Failure 500 服务器错误
  1713. // @router /third_party_err_analyze [get]
  1714. func (u *BaseAccessLogController) ThirdPartyInterfaceErrorAnalyze() {
  1715. u.LogID = fmt.Sprintf("LogQueryThirdPartyAnalyze[%d]", time.Now().UnixNano())
  1716. req := &param_v1_0.ThirdPartyInterfaceErrorAnalyzeReq{}
  1717. getParamsTask := func() error {
  1718. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1719. return nil
  1720. }
  1721. handleTokenCheck := func() error {
  1722. uid, _, err := utils.ParseToken(req.Token)
  1723. if err != nil {
  1724. return err
  1725. }
  1726. if uid != req.Uid {
  1727. return errors.UserTokenillegality
  1728. }
  1729. /*if level == 0 {
  1730. return errors.AuthNotAllow
  1731. }*/
  1732. return nil
  1733. }
  1734. handleDataTask := func() error {
  1735. mreq := gd_statistics.ThirdPartyInterfaceErrorAnalyzeReq{}
  1736. mreq.StartTimestamp = req.StartTimestamp
  1737. mreq.EndTimestamp = req.EndTimestamp
  1738. mreq.ProviderApiId = req.ProviderApiId
  1739. mreq.Status = req.Status
  1740. reply, err := rpc_apis.Statistics.ThirdPartyInterfaceErrorAnalyze(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1741. if err != nil {
  1742. l.Error("rpc",
  1743. zap.String("call", "ThirdPartyInterfaceErrorAnalyze"),
  1744. zap.String("args", utils.MarshalJsonString(req)),
  1745. zap.String("error", err.Error()))
  1746. return errors.ErrorTransform(err)
  1747. }
  1748. resp := param_v1_0.ThirdPartyInterfaceErrorAnalyzeResp{
  1749. SimpleResp: param_base.SimpleResp{
  1750. Code: 0,
  1751. Msg: "SUCCESS",
  1752. },
  1753. Data: make([]gd_statistics.ThirdPartyInterfaceErrorAnalyze, 0),
  1754. }
  1755. resp.Data = reply.List
  1756. httper.JSON(u.Ctx, resp, u.LogID)
  1757. return nil
  1758. }
  1759. // 执行以上定义的任务
  1760. task.Do(&task.PanicRecover{
  1761. Ctx: u.Ctx,
  1762. LogID: u.LogID}, u.Ctx,
  1763. getParamsTask, handleTokenCheck, handleDataTask,
  1764. )
  1765. }
  1766. func ExportImpl(req *param_v1_0.LogQueryUserAccessLogExportReq,u *BaseAccessLogController) error {
  1767. defer func() {
  1768. if r := recover(); r != nil {
  1769. err := fmt.Errorf("%+v", r)
  1770. fmt.Println("export err:",err)
  1771. }
  1772. }()
  1773. var headMap map[string]string
  1774. if !req.Export.EnglishHeader {
  1775. hReq := gd_management.ManagementGetBaseApiByRouterReq{}
  1776. hReq.MerchantId = int(req.Export.MerchantId)
  1777. hReq.ApiId = int(req.Export.ApiId)
  1778. hReply, err := rpc_apis.Management.ManagementGetBaseApiByRouter(utils.NewContextFromBeegoCtx(u.Ctx), &hReq)
  1779. if err != nil {
  1780. l.Error("rpc",
  1781. zap.String("call", "ManagementGetBaseApiByRouter"),
  1782. zap.String("args", utils.MarshalJsonString(req)),
  1783. zap.String("error", err.Error()))
  1784. //return errors.ErrorTransform(err)
  1785. } else {
  1786. headMap = hReply.Data
  1787. }
  1788. fmt.Println("ManagementGetBaseApiByRouter:", hReply, err)
  1789. }
  1790. // 创建导出任务
  1791. req.Export.ExportName = fmt.Sprintf("%s_%d", req.Export.ExportName, time.Now().UnixNano())
  1792. exportReq := gd_statistics.LogExportCreateReq{}
  1793. exportReq.Status = "开始"
  1794. exportReq.ExportType = 2
  1795. exportReq.FileName = req.Export.ExportName
  1796. if exportReq.FileName == "" {
  1797. return errors.ArgsError
  1798. }
  1799. host := u.Ctx.Request.Host
  1800. if strings.Contains(ServerIp, "0.0.0.0") == false {
  1801. host = ServerIp + ":" + ServerPort
  1802. } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
  1803. host = u.Ctx.Request.Host + ":" + ServerPort
  1804. }
  1805. exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
  1806. if true {
  1807. exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
  1808. }
  1809. exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
  1810. if err != nil {
  1811. l.Error("rpc",
  1812. zap.String("call", "LogExportCreate"),
  1813. zap.String("args", utils.MarshalJsonString(req)),
  1814. zap.String("error", err.Error()))
  1815. return errors.ErrorTransform(err)
  1816. }
  1817. exportReq.Id = exportReply.Id
  1818. // 任务执行完成后更新任务
  1819. defer ExportUpdate(u, &exportReq)
  1820. // 调微服务获取日志数据
  1821. mreq := gd_statistics.LogQueryAccessLogReq{}
  1822. mreq.StartTimestamp = req.Export.StartTimestamp
  1823. mreq.EndTimestamp = req.Export.EndTimestamp
  1824. mreq.ApiId = req.Export.ApiId
  1825. mreq.MerchantId = req.Export.MerchantId
  1826. mreq.PageNumber = 0
  1827. mreq.PageSize = 10000
  1828. mreq.UseId = true
  1829. // 初始化excel manager
  1830. mg := initLogExcelManagerNew(req.Export.IsParseParam)
  1831. exportReq.Status = "进行中"
  1832. ExportUpdate(u, &exportReq)
  1833. // 考虑到数据量问题分批获取数据
  1834. for {
  1835. fmt.Println("111111111111111111111111111111111111111111111111111111",mreq.PageNumber)
  1836. mreq.PageNumber += 1
  1837. reply, err := rpc_apis.Statistics.LogExport(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1838. if err != nil {
  1839. l.Error("rpc",
  1840. zap.String("call", "LogExport"),
  1841. zap.String("args", utils.MarshalJsonString(req)),
  1842. zap.String("error", err.Error()))
  1843. exportReq.Status = "失败"
  1844. return errors.ErrorTransform(err)
  1845. }
  1846. logLen := int64(len(reply.AccessLogs))
  1847. if len(reply.AccessLogs) == 0 {
  1848. break
  1849. }
  1850. // 写入execel
  1851. accessLogWriteToExcelNew(mg, reply.AccessLogs, headMap)
  1852. if logLen < mreq.PageSize{
  1853. break
  1854. }
  1855. mreq.LastId = reply.AccessLogs[logLen-1].Id
  1856. }
  1857. exportReq.Status = "完成"
  1858. // 保存execel
  1859. mg.baseSheet.Flush()
  1860. if req.Export.IsParseParam{
  1861. if mg.reqSheet != nil{
  1862. mg.reqSheet.Flush()
  1863. }
  1864. if mg.resSheet != nil{
  1865. mg.resSheet.Flush()
  1866. }
  1867. }
  1868. mg.file.SaveAs(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
  1869. //mg.file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
  1870. if true {
  1871. utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
  1872. }
  1873. return nil
  1874. }
  1875. // @Title 平台日志导出
  1876. // @Description 平台日志导出
  1877. // @Param token header string true "token"
  1878. // @Param uid header int64 true "admin id"
  1879. // @Param export body params.param_v1_0.LogExportInfo true "导出任务信息"
  1880. // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountExportResp "响应信息"
  1881. // @Failure 500 服务器错误
  1882. // @router /access_log_export [post]
  1883. func (u *BaseAccessLogController) LogQueryUserAccessLogExport() {
  1884. u.LogID = fmt.Sprintf("LogQueryUserAccessLogExport[%d]", time.Now().UnixNano())
  1885. req := &param_v1_0.LogQueryUserAccessLogExportReq{}
  1886. getParamsTask := func() error {
  1887. httper.FillRequireParams(u.Ctx, req, u.LogID)
  1888. return nil
  1889. }
  1890. handleDataTask := func() error {
  1891. /*var headMap map[string]string
  1892. if !req.Export.EnglishHeader {
  1893. hReq := gd_management.ManagementGetBaseApiByRouterReq{}
  1894. hReq.MerchantId = int(req.Export.MerchantId)
  1895. hReq.ApiId = int(req.Export.ApiId)
  1896. hReply, err := rpc_apis.Management.ManagementGetBaseApiByRouter(utils.NewContextFromBeegoCtx(u.Ctx), &hReq)
  1897. if err != nil {
  1898. l.Error("rpc",
  1899. zap.String("call", "ManagementGetBaseApiByRouter"),
  1900. zap.String("args", utils.MarshalJsonString(req)),
  1901. zap.String("error", err.Error()))
  1902. } else {
  1903. headMap = hReply.Data
  1904. }
  1905. fmt.Println("ManagementGetBaseApiByRouter:", hReply, err)
  1906. }
  1907. // 创建导出任务
  1908. req.Export.ExportName = fmt.Sprintf("%s_%d", req.Export.ExportName, time.Now().UnixNano())
  1909. exportReq := gd_statistics.LogExportCreateReq{}
  1910. exportReq.Status = "开始"
  1911. exportReq.ExportType = 2
  1912. exportReq.FileName = req.Export.ExportName
  1913. if exportReq.FileName == "" {
  1914. return errors.ArgsError
  1915. }
  1916. host := u.Ctx.Request.Host
  1917. if strings.Contains(ServerIp, "0.0.0.0") == false {
  1918. host = ServerIp + ":" + ServerPort
  1919. } else if strings.Contains(u.Ctx.Request.Host, ":") == false {
  1920. host = u.Ctx.Request.Host + ":" + ServerPort
  1921. }
  1922. exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
  1923. if true {
  1924. exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
  1925. }
  1926. exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
  1927. if err != nil {
  1928. l.Error("rpc",
  1929. zap.String("call", "LogExportCreate"),
  1930. zap.String("args", utils.MarshalJsonString(req)),
  1931. zap.String("error", err.Error()))
  1932. return errors.ErrorTransform(err)
  1933. }
  1934. exportReq.Id = exportReply.Id
  1935. defer ExportUpdate(u, &exportReq)
  1936. mreq := gd_statistics.LogQueryAccessLogReq{}
  1937. mreq.StartTimestamp = req.Export.StartTimestamp
  1938. mreq.EndTimestamp = req.Export.EndTimestamp
  1939. mreq.ApiId = req.Export.ApiId
  1940. mreq.MerchantId = req.Export.MerchantId
  1941. mreq.PageNumber = 0
  1942. mreq.PageSize = 1000
  1943. // 初始化excel manager
  1944. mg := initLogExcelManagerNew(req.Export.IsParseParam)
  1945. total := int64(0)
  1946. handled := int64(0)
  1947. // 考虑到数据量问题分批获取数据
  1948. for {
  1949. mreq.PageNumber += 1
  1950. reply, err := rpc_apis.Statistics.LogQueryAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  1951. if err != nil {
  1952. l.Error("rpc",
  1953. zap.String("call", "LogQueryAccessLog"),
  1954. zap.String("args", utils.MarshalJsonString(req)),
  1955. zap.String("error", err.Error()))
  1956. exportReq.Status = "失败"
  1957. return errors.ErrorTransform(err)
  1958. }
  1959. // 设置总数
  1960. if total == 0 {
  1961. total = reply.Total
  1962. }
  1963. // 写入execel
  1964. accessLogWriteToExcelNew(mg, reply.AccessLogs, headMap)
  1965. handled += int64(len(reply.AccessLogs))
  1966. // 处理完毕
  1967. if handled >= total {
  1968. break
  1969. }
  1970. }
  1971. exportReq.Status = "完成"
  1972. // 保存execel
  1973. mg.baseSheet.Flush()
  1974. if req.Export.IsParseParam{
  1975. if mg.reqSheet != nil{
  1976. mg.reqSheet.Flush()
  1977. }
  1978. if mg.resSheet != nil{
  1979. mg.resSheet.Flush()
  1980. }
  1981. }
  1982. mg.file.SaveAs(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
  1983. if true {
  1984. utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
  1985. }*/
  1986. if req.Export.ExportName == "" {
  1987. return errors.ArgsError
  1988. }
  1989. if req.Export.StartTimestamp == 0 || req.Export.EndTimestamp == 0 {
  1990. return errors.ArgsError
  1991. }
  1992. // TODO 判断是否在一个月内
  1993. monthstar := time.Unix(req.Export.StartTimestamp,0).Month()
  1994. monthEnd := time.Unix(req.Export.EndTimestamp,0).Month()
  1995. if monthstar != monthEnd{
  1996. return jsonrpc2.NewJsonError(20001, "参数错误,不能跨月导出")
  1997. }
  1998. go ExportImpl(req,u)
  1999. resp := param_v1_0.LogQueryUserAccessCountExportResp{
  2000. SimpleResp: param_base.SimpleResp{
  2001. Code: 0,
  2002. Msg: "SUCCESS",
  2003. },
  2004. }
  2005. httper.JSON(u.Ctx, resp, u.LogID)
  2006. return nil
  2007. }
  2008. // 执行以上定义的任务
  2009. task.Do(&task.PanicRecover{
  2010. Ctx: u.Ctx,
  2011. LogID: u.LogID}, u.Ctx,
  2012. getParamsTask, handleDataTask,
  2013. )
  2014. }
  2015. // @Title 数据源日志导出
  2016. // @Description 数据源日志导出
  2017. // @Param token header string true "token"
  2018. // @Param uid header int64 true "admin id"
  2019. // @Param export body params.param_v1_0.ThirdpartLogExportInfo true "导出任务信息"
  2020. // @Success 200 {object} params.param_v1_0.LogQueryUserAccessCountExportResp "响应信息"
  2021. // @Failure 500 服务器错误
  2022. // @router /thirdpart_log_export [post]
  2023. func (u *BaseAccessLogController) LogQueryUserThirdpartLogExport() {
  2024. u.LogID = fmt.Sprintf("LogQueryUserThirdpartLogExport[%d]", time.Now().UnixNano())
  2025. req := &param_v1_0.LogQueryUserThirdpartLogExportReq{}
  2026. getParamsTask := func() error {
  2027. httper.FillRequireParams(u.Ctx, req, u.LogID)
  2028. return nil
  2029. }
  2030. handleDataTask := func() error {
  2031. // 创建导出任务
  2032. req.Export.ExportName = fmt.Sprintf("%s_%d", req.Export.ExportName, time.Now().UnixNano())
  2033. exportReq := gd_statistics.LogExportCreateReq{}
  2034. exportReq.Status = "开始"
  2035. exportReq.ExportType = 3
  2036. exportReq.FileName = req.Export.ExportName
  2037. if exportReq.FileName == "" {
  2038. return errors.ArgsError
  2039. }
  2040. host := ServerIp + ":" + ServerPort
  2041. exportReq.Path = "http://" + host + exportPath + req.Export.ExportName + ".xlsx"
  2042. if true {
  2043. exportReq.Path = getOssFileUrl(req.Export.ExportName + ".xlsx")
  2044. }
  2045. exportReply, err := rpc_apis.Statistics.LogExportCreate(utils.NewContextFromBeegoCtx(u.Ctx), &exportReq)
  2046. if err != nil {
  2047. l.Error("rpc",
  2048. zap.String("call", "LogExportCreate"),
  2049. zap.String("args", utils.MarshalJsonString(req)),
  2050. zap.String("error", err.Error()))
  2051. return errors.ErrorTransform(err)
  2052. }
  2053. exportReq.Id = exportReply.Id
  2054. // 任务执行完成后更新任务
  2055. defer ExportUpdate(u, &exportReq)
  2056. // 调微服务获取日志数据
  2057. mreq := gd_statistics.LogQueryThirdpartAccessLogReq{}
  2058. mreq.StartTimestamp = req.Export.StartTimestamp
  2059. mreq.EndTimestamp = req.Export.EndTimestamp
  2060. mreq.ProviderApiId = req.Export.ProviderApiId
  2061. mreq.ProviderId = req.Export.ProviderId
  2062. mreq.PageNumber = 0
  2063. mreq.PageSize = 1000
  2064. // 初始化excel manager
  2065. mg := initLogExcelManager(req.Export.IsParseParam)
  2066. total := int64(0)
  2067. handled := int64(0)
  2068. // 考虑到数据量问题分批获取数据
  2069. for {
  2070. mreq.PageNumber += 1
  2071. reply, err := rpc_apis.Statistics.LogQueryThirdpartAccessLog(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
  2072. if err != nil {
  2073. l.Error("rpc",
  2074. zap.String("call", "LogQueryThirdpartAccessLog"),
  2075. zap.String("args", utils.MarshalJsonString(req)),
  2076. zap.String("error", err.Error()))
  2077. exportReq.Status = "失败"
  2078. return errors.ErrorTransform(err)
  2079. }
  2080. // 设置总数
  2081. if total == 0 {
  2082. total = reply.Total
  2083. }
  2084. // 数据写入execel
  2085. thirdLogWriteToExcel(mg, reply.ThirdpartLogs)
  2086. handled += int64(len(reply.ThirdpartLogs))
  2087. // 处理完毕
  2088. if handled >= total {
  2089. break
  2090. }
  2091. }
  2092. exportReq.Status = "完成"
  2093. // 保存execel
  2094. mg.file.Save(beego.BConfig.WebConfig.StaticDir["/export"] + req.Export.ExportName + ".xlsx")
  2095. if true {
  2096. utils.OssUploadFile(beego.BConfig.WebConfig.StaticDir["/export"]+req.Export.ExportName+".xlsx", req.Export.ExportName+".xlsx")
  2097. }
  2098. resp := param_v1_0.LogQueryUserAccessCountExportResp{
  2099. SimpleResp: param_base.SimpleResp{
  2100. Code: 0,
  2101. Msg: "SUCCESS",
  2102. },
  2103. }
  2104. httper.JSON(u.Ctx, resp, u.LogID)
  2105. return err
  2106. }
  2107. // 执行以上定义的任务
  2108. task.Do(&task.PanicRecover{
  2109. Ctx: u.Ctx,
  2110. LogID: u.LogID}, u.Ctx,
  2111. getParamsTask, handleDataTask,
  2112. )
  2113. }