Serilog + Azure -日志分析工作区中不显示自定义日志

db2dz4w8  于 2022-12-19  发布在  其他
关注(0)|答案(2)|浏览(165)

我尝试使用Serilog从应用服务登录到Log Analytics工作区,但我的任何控制器(使用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" ]
  },
ia2d9nvy

ia2d9nvy1#

我认为您错过了将日志从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();
fumotvh3

fumotvh32#

var logger = new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).Enrich.FromLogContext()
    .CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);

这是我的配置文件

"Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.AzureAnalytics" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "SerilogTest": "Debug",
        "Microsoft.AspNetCore": "Warning",
        "Microsoft": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "../logs/webapi-.log",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
        }
      },
      {
        "Name": "AzureAnalytics",
        "Args": {
          "logName": "mycustomtablename",
          "authenticationId": "xxxxxxx",
          "workspaceId": "xxxxxx",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
        }
      }
    ]
  }

相关问题