在客户端请求接口时,经常会出现接口相应慢,接口等待超时,接口错误,为了这事相信不少后台开发者为此背锅,记下请求日志,拿出有力证据这才是关键。

1.接口请求错误记录

很多时候接口请求出现的500,404这些错误,请求当时出现如果客户端没有日志记录,有些问题是很难复现,虽然系统日志中也会记录,但是不够系统。

那么可以通过接下来的方式记录系统错误信息,这时我们可以在Global中添加Application_Error的处理:

 void Application_Error(object sender, EventArgs e)
{
//获取错误信息
Exception lastError = Server.GetLastError();
int httpCode = ;
HttpException httpError = lastError as HttpException;
if (httpError != null)
{
//获取错误代码
httpCode = httpError.GetHttpCode();
}
// 在出现未处理的错误时运行的代码
Exception objErr = Server.GetLastError().GetBaseException();
string error = string.Empty;
string errortime = string.Empty;
string erroraddr = string.Empty;
string errorinfo = string.Empty;
string errorsource = string.Empty;
string errortrace = string.Empty;
string errorcode = string.Empty; error += "发生时间:" + System.DateTime.Now.ToString() + "<br>";
errortime = "发生时间:" + System.DateTime.Now.ToString(); error += "发生异常页: " + Request.Url.ToString() + "<br>";
erroraddr = "发生异常页: " + Request.Url.ToString(); error += "返回状态码: " + httpCode + "<br>";
errorcode = "返回状态码: " + httpCode; error += "异常信息: " + objErr.Message + "<br>";
errorinfo = "异常信息: " + objErr.Message;
//error +="错误源:"+objErr.Source+"<br>";
//error += "堆栈信息:" + objErr.StackTrace + "<br>";
errorsource = "错误源:" + objErr.Source;
errortrace = "堆栈信息:" + objErr.StackTrace;
error += "--------------------------------------<br>";
Server.ClearError();
Application["error"] = error;
//独占方式,因为文件只能由一个进程写入.
System.IO.StreamWriter writer = null;
try
{
lock (this)
{
// 写入日志
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString();
string path = string.Empty;
string filename = DateTime.Now.Day.ToString() + ".txt";
path = Server.MapPath("~/App_Data/log/") + year + "/" + month;
//如果目录不存在则创建
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
System.IO.FileInfo file = new System.IO.FileInfo(path + "/" + filename);
//if (!file.Exists)
// file.Create();
//file.Open(System.IO.FileMode.Append);
writer = new System.IO.StreamWriter(file.FullName, true);//文件不存在就创建,true表示追加
writer.WriteLine("用户IP:" + Request.UserHostAddress);
// if (Session["Identity"] != null)
// {
// writer.WriteLine("登录帐号:" System.Web.HttpContext.Current.Session["Identity"]).YongHuInfo.ACCOUNTID);
// }
writer.WriteLine(errortime);
writer.WriteLine(erroraddr);
writer.WriteLine(errorcode);
writer.WriteLine(errorinfo);
writer.WriteLine(errorsource);
writer.WriteLine(errortrace);
writer.WriteLine("--------------------------------------------------------------------------------------");
}
}
finally
{
if (writer != null)
writer.Close();
}
//服务端返回状态码
Response.StatusCode = ;
Response.AddHeader("errormsg", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(objErr.Message)));
}

2.接口请求记录

记录每一次请求接口的时间和参数,方便请求错误重现。

在Application_BeginRequest添加如下配置:

        void Application_BeginRequest(object source, EventArgs e)
{ var requestUrl = DateTime.Now + "请求链接" + Request.Url.ToString() + "\r\n";
var requestData = DateTime.Now + "请求参数" + ApiSign.GetxtParams() + "\r\n";
// 写入日志
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString();
string path = string.Empty;
string filename = DateTime.Now.Day.ToString() + "_request" + ".txt";
path = Server.MapPath("~/App_Data/log/") + year + "/" + month;
string Filepath=path + "/" + filename; if (requestUrl.ToUpper().IndexOf("API/") != -)
{
Task.Run(() =>{Ecio_Admin.Common.ToolKit.PrintText(requestUrl + requestData, Filepath, true);});
}
}

当然这里有一个比较常用的日志文件记录方法,这里把单独封装了PrintText。

  /// <summary>
/// 本地打印文本记录
/// </summary>
/// <param name="text">需要写入的值</param>
/// <param name="path">文件路径</param>
/// <param name="IsAppend">是否追加至最后一行</param>
/// <returns>追加结果</returns>
public static void PrintText(string text, string path, bool IsAppend)
{
try
{
if (!Directory.Exists(path.Split(new string[] { path.Substring(path.LastIndexOf('\\')) }, StringSplitOptions.RemoveEmptyEntries)[]))
Directory.CreateDirectory(path);
if (!File.Exists(path))
{
using (System.IO.StreamWriter Creat = File.CreateText(path)) { }
}
if (IsAppend)
{ using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
{
lock (sw)
{
sw.WriteLine(text);
}
}
}
else
{
System.IO.File.WriteAllText(path, text);
}
}
catch { }
}

3.记录接口请求时间

这里我是用了一个windows系统服务来轮询每一个接口的请求和响应时间,可以参考下面这个文章,建一个服务,然后测试接口响应时间。

http://www.cnblogs.com/loyung/p/6123317.html

Global配置接口访问日志以及测试日志记录的更多相关文章

  1. Spring Boot从入门到实战:集成AOPLog来记录接口访问日志

    日志是一个Web项目中必不可少的部分,借助它我们可以做许多事情,比如问题排查.访问统计.监控告警等.一般通过引入slf4j的一些实现框架来做日志功能,如log4j,logback,log4j2,其性能 ...

  2. SpringBoot应用中使用AOP记录接口访问日志

    SpringBoot应用中使用AOP记录接口访问日志 本文主要讲述AOP在mall项目中的应用,通过在controller层建一个切面来实现接口访问的统一日志记录. AOP AOP为Aspect Or ...

  3. Spring Boot 2 配置服务器访问日志

    Tomcat控制台中看到的日志是服务器的日志,而服务器访问日志则是记录服务处理的请求信息. 开发环境:IntelliJ IDEA 2019.2.2Spring Boot版本:2.1.8 1.新建一个名 ...

  4. 循序渐进VUE+Element 前端应用开发(31)--- 系统的日志管理,包括登录日志、接口访问日志、实体变化历史日志

    在一个系统的权限管理模块中,一般都需要跟踪一些具体的日志,ABP框架的系统的日志管理,包括登录日志.接口访问日志.实体变化历史日志,本篇随笔介绍ABP框架中这些日志的管理和界面处理. 1.系统登录日志 ...

  5. Apache配置 5.访问日志不记录静态文件

    介绍:项目中的CSS.图片.js都是静态文件.一般会将静态文件放到一个单独的目录中,以方便管理. 1. 配置 # vim /usr/local/apache2.4/conf/extra/httpd-v ...

  6. SpringBoot 使用AOP记录接口访问日志

    文章来源:https://macrozheng.github.io/mall-learning/#/technology/aop_log AOP AOP为Aspect Oriented Program ...

  7. 通过Nginx,Tomcat访问日志(access log)记录请求耗时

    一.Nginx通过$upstream_response_time $request_time统计请求和后台服务响应时间 nginx.conf使用配置方式: log_format main '$remo ...

  8. Nginx 笔记与总结(4)配置 server 访问日志

    打开 nginx.conf: [root@localhost ~]# cd /usr/local/nginx/conf [root@localhost conf]# vim nginx.conf 在默 ...

  9. Centos下Nginx配置WEB访问日志并结合shell脚本定时切割

    在一个成熟的WEB系统里,没有日志管理是不可以的,有了日志,可以帮助你得到用户地域来源.跳转来源.使用终端.某个URL访问量等相关信息:通过错误日志,你可以得到系统某个服务或server的性能瓶颈等. ...

随机推荐

  1. 外部javascript

  2. multi-head attention

    ■ 论文 | Attention Is All You Need ■ 链接 | https://www.paperweekly.site/papers/224 ■ 源码 | https://githu ...

  3. Linux下mysql出错:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

    安装: 1.新开的云服务器,需要检测系统是否自带安装mysql # yum list installed | grep mysql 2.如果发现有系统自带mysql,果断这么干 # yum -y re ...

  4. 02 JDBC相关

    ====================================================================================JDBC JAVA Databa ...

  5. Vim+Ctags+Cscope安装

    对比了下,感觉还是Vim比较专业. 一:使用说明: ‘/’查找忽略大小写,比如需要查找“book”,当输入/b的时候会自动找到第一个以"b"开头的单词 实现C程序的缩减 查询中自由 ...

  6. hdu4565 So Easy! 矩阵快速幂

    A sequence Sn is defined as: Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example ...

  7. python os模块使用笔记(更新)

    import os 添加os模块 walk方法: os.walk(path) path是string形式的目标目录 生成一个某目录下递归树形目录迭代器,方便递归访问子目录,访问目录就能够轻松访问子文件 ...

  8. 浅谈log4j-4-不同目的地(转)

    public class DifferentAppender { private static Logger logger=Logger.getLogger(DifferentAppender.cla ...

  9. 剑指offer-反向遍历链表-栈和递归2种方法(一次性跑通)

  10. System类的使用

    1.System类: 不能被实例化,调用方式:  System.方法 2.用于计算程序执行的时间,currentTimeMillis()方法 System.currentTimeMillis(): p ...