c# - Serilog + Azure - Log Analytics 工作区中没有出现自定义日志

标签 c# azure asp.net-core serilog azure-log-analytics

我尝试使用 Serilog 从应用服务登录到 Log Analytics 工作区,但我的任何 Controller (使用 DI 获取 ILogger)都没有记录任何内容。

我是否遗漏了一些明显的东西?工作区不显示自定义日志,并且对 API 的调用会返回预期返回的所有内容。

public class Program
    {
        public static void Main(string[] args)
        {

            // The initial "bootstrap" logger is able to log errors during start-up. It's completely replaced by the
            // logger configured in `UseSerilog()` below, once configuration and dependency-injection have both been
            // set up successfully.
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Console()
                .CreateBootstrapLogger();

            Log.Information("Starting up!");

            try
            {
                CreateHostBuilder(args).Build().Run();
                Log.Information("Stopped cleanly");
                return;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "An unhandled exception occured during bootstrapping");
                return;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
             .UseSerilog((context, services, configuration) => configuration
                    .ReadFrom.Configuration(context.Configuration)
                    .ReadFrom.Services(services)
                    .Enrich.FromLogContext())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            // Controllers
            services.AddControllers().AddNewtonsoftJson();

            // Web
            services.AddWebRegistry(Configuration);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            // Write streamlined request completion events, instead of the more verbose ones from the framework.
            // To use the default framework request logging instead, remove this line and set the "Microsoft"
            // level in appsettings.json to "Information".
            app.UseSerilogRequestLogging();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
{
  "Serilog": {
    "Using": [ "Serilog.Sinks.AzureAnalytics" ],
    "MinimumLevel": "Debug",
    "Override": {
      "System": "Information",
      "Microsoft": "Information",
      "Microsoft.AspNetCore.Authentication": "Information",
      "Microsoft.AspNetCore.SignalR": "Debug",
      "Microsoft.AspNetCore.Http.Connections": "Debug"
    },
    "WriteTo": [
      {
        "Name": "AzureAnalytics",
        "Args": {
          "logName": "devlog",
          "authenticationId": "secret",
          "workspaceId": "secret"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "WithThreadName", "WithEventType" ]
  },

最佳答案

我认为您缺少将日志从 Serilog 接收到 Log Analytics 的包:

添加以下包:

Serilog.AspNetCore
Serilog.Sinks.AzureAnalytics

然后:

public static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .WriteTo.AzureAnalytics(workspaceId: "WORKSPACE ID", 
                                authenticationId: "PRIMARY KEY")
        .CreateLogger();

    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseSerilog();

关于c# - Serilog + Azure - Log Analytics 工作区中没有出现自定义日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68298896/

相关文章:

c# - 自动从 ListView 子项构建数组

azure - 如何修复 azure wiki 中的 toc 超链接 anchor 滚动位置(当存在重复 anchor 时 - 例如 : sub-topic)?

c# - .Net Core IsAuthenticated false 即使我手动使用 HttpContext.SignInAsync

c# - 直接绘制到 Excel 单元格 Canvas

c# - 为什么 C# 的 String.Join 不在某一时刻使用 StringBuilder?

powershell - 登录-AzureRMAccount 返回 "Unknown User Type"

c# - 为什么按类型添加 AutoValidateAntiForgeryTokenAttribute 不起作用?

twitter-bootstrap - 使用 Bootstrap 模态确认删除列表项

c# - excel列中的UsedRange

azure - 使用Azure CLI在运行于Azure容器实例上的Docker容器上执行命令