应用1:webconfig.cs中设置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//error log
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
config.Services.Add(typeof(IExceptionLogger), new ApiExceptionLogger());
}
}
应用二:Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
Response.Filter = null;
var lastError = Server.GetLastError();
if (lastError != null)
{
_logger.Error(lastError, "CRM site exception");
}
}
ApiExceptionLogger.cs:
public class ApiExceptionLogger: ExceptionLogger
{
public ApiExceptionLogger(){}
public override void Log(ExceptionLoggerContext context)
{
StringBuilder sb = new StringBuilder();
var r = context.Request;
if (r != null)
{
sb.AppendLine($"Unhandled exception processing {r.Method} for {r.RequestUri}");
if (r.Headers.Count() > 0)
{
sb.AppendLine("Headers Begin:");
sb.AppendLine($"{r.Headers.ToString()}");
sb.AppendLine("Headers End.");
}
if (r.Content!=null)
{
var content = r.Content.ReadAsStringAsync().Result;
sb.AppendLine("Contents Begin:");
sb.AppendLine(content);
sb.AppendLine("Contents End.");
}
}
IIocHelper ioc = IocFactory.Instance;
var logger = ioc.GetInstance<ILogBase>();
logger.Error(sb.ToString(), context.Exception);
}
}
logger:可以使用NLog实现