如何解决用于容器的Azure WebApp中的日志记录方法
我正在设计一个ASP.NET Core应用程序作为WebApp for Container运行。我正在文本文件中记录应用程序异常。我还使用Application Insight软件包捕获遥测。我已经将应用程序托管在WebAapp for Container中。
在哪里可以找到并下载日志文本文件?
此外,当应用程序设计为Container的WebApp时,上述方法是否适合记录日志?如果没有,那么正确的方法是什么?
此外,Application Insight主要生成遥测信息。是否可以将应用程序的文本日志与Application Insight集成在一起,以进行更好的应用程序日志分析?
解决方法
您不必将应用程序异常明确地写入文件。将Application Insights与应用程序集成时,将记录所有异常。您可以在AI实例的 Failures 刀片中查看例外情况
Update1:
在下面的屏幕截图中,您可以查看前3个例外类型。而且, 500 响应代码还会向您显示异常。所有这些都不需要太多代码。您可以查看我的文章here,以获取有关如何将Application Insights集成到asp.net核心应用程序中的逐步详细说明。
,这是在Application Insight上记录请求和响应的中间件。您也可以创建用于记录日志的服务,以在应用程序Insight中记录异常。
中间件
public class LoggingMiddleware
{
private static readonly TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.CreateDefault();
private readonly TelemetryClient telemetryClient;
private IConfiguration configuration;
private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager;
private readonly string appName;
private readonly bool loggingEnabled;
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next,IConfiguration config)
{
_next = next;
configuration = config;
_recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
telemetryConfiguration.InstrumentationKey = configuration.GetValue<string>("ApplicationInsights:InstrumentationKey");
telemetryClient = new TelemetryClient(telemetryConfiguration);
appName = configuration.GetValue<string>("AppName");
loggingEnabled = configuration.GetValue<bool>("Logging:LogRequestResponse");
}
public async Task Invoke(HttpContext httpContext)
{
if(loggingEnabled)
{
await LogRequest(httpContext);
await LogResponse(httpContext);
}
}
private async Task LogRequest(HttpContext context)
{
context.Request.EnableBuffering();
await using var requestStream = _recyclableMemoryStreamManager.GetStream();
await context.Request.Body.CopyToAsync(requestStream);
string correlationId = context.Request.Headers.Keys.FirstOrDefault(h => h.ToLower() == "correlationid");
if (correlationId == null) correlationId = string.Empty;
if (context.Request.Path != "/")
{
telemetryClient.TrackEvent($"{appName}-RequestMiddleware",new Dictionary<string,string>
{
{ "AppName",appName },{ "CorrelationId",correlationId },{ "Method",context.Request.Method },{ "Scheme",context.Request.Scheme},{ "Host",context.Request.Host.Value },{ "Path",context.Request.Path },{ "QueryString",context.Request.QueryString.Value },{ "Request Body",ReadStreamInChunks(requestStream) }
});
}
context.Request.Body.Position = 0;
}
private static string ReadStreamInChunks(Stream stream)
{
const int readChunkBufferLength = 4096;
stream.Seek(0,SeekOrigin.Begin);
using var textWriter = new StringWriter();
using var reader = new StreamReader(stream);
var readChunk = new char[readChunkBufferLength];
int readChunkLength;
do
{
readChunkLength = reader.ReadBlock(readChunk,readChunkBufferLength);
textWriter.Write(readChunk,readChunkLength);
} while (readChunkLength > 0);
return textWriter.ToString();
}
private async Task LogResponse(HttpContext context)
{
var originalBodyStream = context.Response.Body;
await using var responseBody = _recyclableMemoryStreamManager.GetStream();
context.Response.Body = responseBody;
await _next(context);
context.Response.Body.Seek(0,SeekOrigin.Begin);
var text = await new StreamReader(context.Response.Body).ReadToEndAsync();
context.Response.Body.Seek(0,SeekOrigin.Begin);
if (context.Request.Path != "/")
{
telemetryClient.TrackEvent($"{appName}-ResponseMiddleware",string> {
{"Scheme",{ "AppName",{"Host",context.Request.Host.Value},{"Path",context.Request.Path},{"QueryString",context.Request.QueryString.Value},{"Response Body",text}
});
}
await responseBody.CopyToAsync(originalBodyStream);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class LoggingMiddlewareExtensions
{
public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LoggingMiddleware>();
}
}
,
我正在设计一个ASP.NET Core应用程序作为Container的WebApp运行。我正在文本文件中记录应用程序异常。我还使用Application Insight软件包捕获遥测。我已经将应用程序托管在WebAapp for Container中。
我也会将异常记录到Application Insights(AI)。如果使用SDK,未处理的异常将最终在AI中出现。另外,您可以手动跟踪它们:
try
{
....
}
catch(Exception ex)
{
telemetryClient.TrackException(ex);
}
此外,Application Insight主要生成遥测信息。我可以将应用程序的文本日志与Application Insight集成在一起,以进行更好的应用程序日志分析吗?
可以。使用AI SDK,您可以发送多种遥测类型,请参见the docs。对于文本记录,我建议使用TrackTrace
:
telemetry.trackTrace("a message",SeverityLevel.Information);
您也可以使用TrackEvent
,但它可以存储较少的数据(source)
现在,除了使用TrackTrace
进行自定义文本记录外,您还可以使用ILogger
界面并像the usual .net core way一样进行记录。它具有support for AI,并将日志也作为跟踪写入AI。
在所有情况下,请注意sampling可能会导致AI中并非所有遥测都可用,因此请将其关闭或接受。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。