用于容器的Azure WebApp中的日志记录方法

如何解决用于容器的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核心应用程序中的逐步详细说明。

enter image description here

,

这是在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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-