我已经创建了API
。通过Web API Tracing using Log4net我已经创建了日志文件。但是在此文件中,仅显示一些成功的日志。但我想显示所有可能的事件,即我的日志中所有stack trace
都带有line number
。以下是我所做的
创建了API跟踪器类
namespace ActualWebService
{
public class MyAPITracer : ITraceWriter
{
private static readonly ILog log = LogManager.GetLogger(typeof(MyAPITracer));
public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
{
TraceRecord rec = new TraceRecord(request,category,level);
traceAction(rec);
WriteLog(rec);
}
private void WriteLog(TraceRecord rec)
{
string strLog = string.Format("{0};{1};{3}", rec.Category,rec.Operator,rec.Operation,rec.Message);
log.Info(strLog);
}
}
}
Web.config
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
// other.....
</configSections>
<log4net>
<root>
<appender-ref ref="RollingFileAppender" />
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="E:\MyLog\LogFile.txt" />
<param name="AppendToFile" value="false" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<CountDirection value="1" />
<staticLogFileName value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date [%thread] %-5level %logger - %meesage%newline" />
</layout>
</appender>
<logger name="ApiLog">
<level value="ALL" />
</logger>
</log4net>
</configuration>
WebApiConfig.cs
log4net.Config.XmlConfigurator.Configure();
config.Services.Replace(typeof(System.Web.Http.Tracing.ITraceWriter), new MyAPITracer());
下面是我的日志文件内容
2018-07-07 14:23:05,593 [1] INFO ActualWebService.MyAPITracer -
System.Web.Http.Controllers;WebHostHttpControllerTypeResolver;eesage
2018-07-07 14:23:05,614 [1] INFO ActualWebService.MyAPITracer -
System.Web.Http.Controllers;WebHostHttpControllerTypeResolver;eesage
2018-07-07 14:23:22,793 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.Request;;http://localhost:14909/api/meters/GetByMsn/002997001022/
2018-07-06T11:10:43eesage
2018-07-07 14:23:22,793 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.MessageHandlers;PassiveAuthenticationMessageHandler;eesage
2018-07-07 14:23:22,803 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.Controllers;DefaultHttpControllerSelector;Route='controller:meters,action:GetByMsn,msn:002997001022,dt:2018-07-06T11:10:43'eesage
2018-07-07 14:23:22,806 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.Controllers;DefaultHttpControllerSelector;Meterseesage
2018-07-07 14:23:22,807 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.Controllers;HttpControllerDescriptor;eesage
2018-07-07 14:23:22,808 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.Controllers;DefaultHttpControllerActivator;eesage
2018-07-07 14:23:23,145 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.Controllers;DefaultHttpControllerActivator;ActualWebService.Controllers.MetersControllereesage
2018-07-07 14:23:23,146 [8] INFO ActualWebService.MyAPITracer - System.Web.Http.Controllers;HttpControllerDescriptor;ActualWebService.Controllers.MetersControllereesage
我创建了一个异常/错误,但未在日志文件中显示。如何显示行号在其中的所有堆栈跟踪?
任何帮助将不胜感激。
答案 0 :(得分:1)
您需要更改WriteLog
方法。
在此方法类中使用TraceRecord类,您可以从该类中记录错误。
回顾一下我对这种方法的实现:
private void WriteLog(TraceRecord rec)
{
if (rec.Exception == null)
{
string infoLog = string.Format("{0};{1};{3}", rec.Category, rec.Operator, rec.Operation, rec.Message);
log.Info(infoLog);
}
else
{
string errorLog = string.Format("{0};{1};{3}", rec.Category, rec.Operator, rec.Operation, rec.Message);
log.Error(errorLog, rec.Exception);
}
}
看到错误日志后:
2018-07-09 14:23:44,561 [11] ERROR TestErrorLogging.MyAPITracer - System.Web.Http.Controllers;TestController;eesage
System.Exception: Test Exception
в TestErrorLogging.Controllers.TestController.Get() в C:\Users\Александр\Desktop\TestErrorLogging\TestErrorLogging\Controllers\TestController.cs:строка 15
в lambda_method(Closure , Object , Object[] )
в System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
в System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
в System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()
答案 1 :(得分:1)
正如@Alexander I.所说,您必须使用不同的日志方法,例如Info(),Warn(),Error()等。
这里是包含有关log4Net的一些有用信息的进一步链接:
https://stackify.com/log4net-guide-dotnet-logging/
对于asp.net Web API中的执行处理/跟踪,您还可以使用ExceptionFilter(https://docs.microsoft.com/de-de/aspnet/web-api/overview/error-handling/web-api-global-error-handling)。
答案 2 :(得分:1)
异常堆栈中的行号来自PDB文件。查看您的发行版的构建配置。 [项目属性| Build]-> Advanced(高级)按钮->调试信息下拉菜单
完整或仅PDB就足够了。
答案 3 :(得分:1)
如果要每条日志消息的堆栈跟踪,可以在模式布局中使用%stacktrace
甚至%stacktracedetail
:
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline%stacktrace%newline" />
</layout>
有关更多信息,请参见the docs。