我正在尝试登录到SQL Server。从我发现的情况来看,它应该是正确的,但似乎仍然没有日志记录。您能看到我在这段代码中做什么吗?抱歉,将代码作为图片发布,此处的格式不适合我。
我试图以一种与实际情况更接近的方式尝试这种方式,但是仍然没有运气。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.MSSqlServer(connectionString: "",
tableName: "Logs"
, schemaName: "LOG"
, autoCreateSqlTable: true,
restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();
}
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)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddSerilog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
public class ValuesController : ControllerBase
{
private readonly ILogger<ValuesController> _logger;
public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
_logger.LogInformation($"Start:");
return new string[] { "value1", "value2" };
}
}
您的代码未设置默认的Serilog记录器,因此所有记录调用都将丢失。您应该添加
Log.Logger=logger;`
在Serilog.AspNetCore回购页面中显示:
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting web host");
CreateWebHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog(); // <-- Add this line;
}